diff --git a/README.md b/README.md index 828ab71..f2e9c4e 100644 --- a/README.md +++ b/README.md @@ -329,6 +329,10 @@ assert_eq!(eval_with_context_mut("a = 10; b = 1.0;", &mut context), Ok(().into() // ...and read the value in code like this assert_eq!(context.get_value("a"), Some(&Value::from_int(10))); assert_eq!(context.get_value("b"), Some(&Value::from_float(1.0))); +// ...and remove the value in code like this +assert_eq!(context.remove_value("a"), Ok(Some(Value::from_int(10)))); +// ...and if the value does not exist when removing, it returns None. +assert_eq!(context.remove_value("a"), Ok(None)); ``` Contexts are also required for user-defined functions. diff --git a/src/context/mod.rs b/src/context/mod.rs index 82a83f2..ea7b8d5 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -56,6 +56,14 @@ pub trait ContextWithMutableVariables: Context { ) -> EvalexprResult<(), Self::NumericTypes> { Err(EvalexprError::ContextNotMutable) } + + /// Removes the variable with the given identifier from the context. + fn remove_value( + &mut self, + _identifier: &str, + ) -> EvalexprResult>, Self::NumericTypes> { + Err(EvalexprError::ContextNotMutable) + } } /// A context that allows to assign to function identifiers. @@ -352,6 +360,14 @@ impl ContextWithMutableVariables self.variables.insert(identifier, value); Ok(()) } + + fn remove_value( + &mut self, + identifier: &str, + ) -> EvalexprResult>, Self::NumericTypes> { + // Removes a value from the `self.variables`, returning the value at the key if the key was previously in the map. + Ok(self.variables.remove(identifier)) + } } impl ContextWithMutableFunctions diff --git a/src/lib.rs b/src/lib.rs index 4f8a35a..50136e6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -309,6 +309,10 @@ //! // ...and read the value in code like this //! assert_eq!(context.get_value("a"), Some(&Value::from_int(10))); //! assert_eq!(context.get_value("b"), Some(&Value::from_float(1.0))); +//! // ...and remove the value in code like this +//! assert_eq!(context.remove_value("a"), Ok(Some(Value::from_int(10)))); +//! // ...and if the value does not exist when removing, it returns None. +//! assert_eq!(context.remove_value("a"), Ok(None)); //! ``` //! //! Contexts are also required for user-defined functions. diff --git a/tests/integration.rs b/tests/integration.rs index 96a772a..cbd0852 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -142,6 +142,16 @@ fn test_with_context() { eval_with_context("five < six && true", &context), Ok(Value::Boolean(true)) ); + + assert_eq!(context.remove_value("half"), Ok(Some(Value::Float(0.5)))); + assert_eq!(context.remove_value("zero"), Ok(Some(Value::Int(0)))); + assert_eq!(context.remove_value("zero"), Ok(None)); + assert_eq!( + eval_with_context("zero", &context), + Err(EvalexprError::VariableIdentifierNotFound( + "zero".to_string() + )) + ); } #[test]