rustic_jsonrpc/
container.rs

1use std::any::{Any, TypeId};
2use std::collections::HashMap;
3
4/// A struct that acts as a container for storing and retrieving values of different types.
5pub struct Container {
6    map: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
7}
8
9impl Container {
10    /// Creates a new, empty Container.
11    pub fn new() -> Self {
12        Self {
13            map: HashMap::new(),
14        }
15    }
16
17    /// Retrieves a reference to a value of type T from the container, if it exists.
18    #[inline]
19    pub fn get<T>(&self) -> Option<&T>
20    where
21        T: Send + Sync + 'static,
22    {
23        self.map
24            .get(&TypeId::of::<T>())
25            .map(|v| v.downcast_ref().unwrap())
26    }
27
28    /// Inserts a value of type T into the container.
29    /// Return the previous value of type T if it existed, or `None` if it did not.
30    pub fn put<T>(&mut self, value: T) -> Option<Box<T>>
31    where
32        T: Send + Sync + 'static,
33    {
34        self.map
35            .insert(TypeId::of::<T>(), Box::new(value))
36            .map(|v| v.downcast().unwrap())
37    }
38}