From 0d00b17cb42dadb8b63be5e2414ca3ecfabaaa5c Mon Sep 17 00:00:00 2001 From: Savanni D'Gerinel Date: Wed, 15 Feb 2023 23:07:45 -0500 Subject: [PATCH] Add Debug and PartialEq traits to flow, when underlying types allow it --- flow/src/lib.rs | 65 +++++++++++++++++++++++++++++-------------------- 1 file changed, 39 insertions(+), 26 deletions(-) diff --git a/flow/src/lib.rs b/flow/src/lib.rs index 28198a2..2bd5c92 100644 --- a/flow/src/lib.rs +++ b/flow/src/lib.rs @@ -17,7 +17,7 @@ You should have received a copy of the GNU General Public License along with Lum //! Where the sled.rs library uses `Result, FatalError>`, these are a little hard to //! work with. This library works out a set of utility functions that allow us to work with the //! nested errors in the same way as a regular Result. -use std::error::Error; +use std::{error::Error, fmt}; /// Implement this trait for the application's fatal errors. /// @@ -110,6 +110,37 @@ impl From> for Flow { } } +impl fmt::Debug for Flow +where + A: fmt::Debug, + FE: fmt::Debug, + E: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Flow::Ok(val) => f.write_fmt(format_args!("Flow::Ok {:?}", val)), + Flow::Err(err) => f.write_fmt(format_args!("Flow::Err {:?}", err)), + Flow::Fatal(err) => f.write_fmt(format_args!("Flow::Fatal {:?}", err)), + } + } +} + +impl PartialEq for Flow +where + A: PartialEq, + FE: PartialEq, + E: PartialEq, +{ + fn eq(&self, rhs: &Self) -> bool { + match (self, rhs) { + (Flow::Ok(val), Flow::Ok(rhs)) => val == rhs, + (Flow::Err(_), Flow::Err(_)) => true, + (Flow::Fatal(_), Flow::Fatal(_)) => true, + _ => false, + } + } +} + /// Convenience function to create an ok value. pub fn ok(val: A) -> Flow { Flow::Ok(val) @@ -177,43 +208,25 @@ mod test { } } - impl PartialEq for Flow { - fn eq(&self, rhs: &Self) -> bool { - match (self, rhs) { - (Flow::Ok(val), Flow::Ok(rhs)) => val == rhs, - (Flow::Err(_), Flow::Err(_)) => true, - (Flow::Fatal(_), Flow::Fatal(_)) => true, - _ => false, - } - } - } - - impl std::fmt::Debug for Flow { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Flow::Ok(val) => f.write_fmt(format_args!("Flow::Ok {}", val)), - Flow::Err(err) => f.write_fmt(format_args!("Flow::Err {:?}", err)), - Flow::Fatal(err) => f.write_fmt(format_args!("Flow::Fatal {:?}", err)), - } - } - } - #[test] fn it_can_map_things() { - let success = ok(15); + let success: Flow = ok(15); assert_eq!(ok(16), success.map(|v| v + 1)); } #[test] fn it_can_chain_success() { - let success = ok(15); + let success: Flow = ok(15); assert_eq!(ok(16), success.and_then(|v| ok(v + 1))); } #[test] fn it_can_handle_an_error() { - let failure = error(Error::Error); - assert_eq!(ok(16), failure.or_else(|_| ok(16))); + let failure: Flow = error(Error::Error); + assert_eq!( + ok::(16), + failure.or_else(|_| ok(16)) + ); } #[test]