From 7e14f71eaa46f24875e4b2564b9d2d90a0be321f Mon Sep 17 00:00:00 2001 From: Savanni D'Gerinel Date: Tue, 10 Oct 2023 23:19:38 -0400 Subject: [PATCH] Fill out the sled-style tests --- error-training/src/lib.rs | 60 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/error-training/src/lib.rs b/error-training/src/lib.rs index 40e23cb..6ddd52e 100644 --- a/error-training/src/lib.rs +++ b/error-training/src/lib.rs @@ -24,6 +24,27 @@ pub enum DatabaseError { NotFound, } +#[derive(Clone, Debug, Error, PartialEq)] +pub enum OperationError { + #[error("database error occurred: {0}")] + DatabaseError(DatabaseError), + + #[error("math error occurred: {0}")] + MathError(MathError), +} + +impl From for OperationError { + fn from(err: DatabaseError) -> Self { + Self::DatabaseError(err) + } +} + +impl From for OperationError { + fn from(err: MathError) -> Self { + Self::MathError(err) + } +} + pub mod sled { //! Sled-style error handling is based on Result, FatalError>. //! FatalErrors do not get resolved. LocalErrors get bubbled up until they can be handled. @@ -58,5 +79,42 @@ pub mod sled { } } - pub fn run() {} + fn op(val: i8) -> Result { + if val as i32 + 120_i32 > (i8::MAX as i32) { + Err(MathError::ExceedsMaxint) + } else { + Ok(val + 120) + } + } + + /// This function exists to test several of the major cases. This is where I will figure out + /// how to handle everything and also have clean code. + /// ```rust + /// use error_training::{*, sled::*}; + /// + /// let db = DB::new(vec![("a".to_owned(), 15), ("b".to_owned(), 0)]); + /// assert_eq!(run_op(&db, "a"), Ok(Ok(i8::MAX))); + /// assert_eq!(run_op(&db, "b"), Ok(Ok(120))); + /// assert_eq!(run_op(&db, "c"), Ok(Ok(0))); + /// assert_eq!(run_op(&db, "fail"), Err(FatalError::DatabaseCorruption)); + /// ``` + /// + /// I have defined this function such that a database miss becomes a 0 and no operation will be + /// performed on it. Since that is the only database error that can occur, this function can + /// only return a `MathError` or a `FatalError`. + pub fn run_op(db: &DB, key: &str) -> Result, FatalError> { + let val = db.get(key)?; + + let res = match val { + Err(DatabaseError::NotFound) => Ok(0), + Ok(val) => op(val), + }; + + Ok(match res { + Ok(val) => Ok(val), + Err(MathError::ExceedsMaxint) => Ok(127), + Err(err) => Err(err), + }) + } } +