diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..ee202d8 --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,16 @@ +{ + "configurations": [ + { + "name": "Linux", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [], + "compilerPath": "/usr/bin/clang", + "cStandard": "c11", + "cppStandard": "c++17", + "intelliSenseMode": "clang-x64" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/src/context.rs b/src/context.rs new file mode 100644 index 0000000..3823048 --- /dev/null +++ b/src/context.rs @@ -0,0 +1,65 @@ +use std::any::{Any, TypeId}; +use std::collections::HashMap; + +#[derive(Default)] +pub struct Context { + container: HashMap>, +} + +impl Context { + pub fn get(&self) -> Option<&T> { + self.container + .get(&TypeId::of::()) + .map(|boxed| boxed.downcast_ref().unwrap()) + } + + pub fn get_mut(&mut self) -> Option<&mut T> { + self.container + .get_mut(&TypeId::of::()) + .map(|boxed| boxed.downcast_mut().unwrap()) + } + + pub fn set(&mut self, t: T) { + self.container.insert(TypeId::of::(), Box::from(t)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_set_and_get() { + // Given Context + let mut context = Context::default(); + // And values + context.set(1_u32); + context.set(String::from("text")); + + // When + let num: &u32 = context.get().unwrap(); + let text: &String = context.get().unwrap(); + + // Then + assert_eq!(*num, 1); + assert_eq!(text, "text"); + } + + #[test] + fn test_set_and_get_mut() { + // Given Context + let mut context = Context::default(); + // And values + context.set(1_u32); + + // When + { + let num: &mut u32 = context.get_mut().unwrap(); + *num = 2; + } + let num: &u32 = context.get().unwrap(); + + // Then + assert_eq!(*num, 2); + } +} diff --git a/src/lib.rs b/src/lib.rs index 31e1bb2..9efb2ab 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,7 +1 @@ -#[cfg(test)] -mod tests { - #[test] - fn it_works() { - assert_eq!(2 + 2, 4); - } -} +pub mod context;