cats_utils/dict.rs
1//! WIP: not fully functionnal/practical
2use std::{any::Any, collections::HashMap, hash::Hash};
3
4pub struct Dict<T> {
5 pub(self) inner: HashMap<T, Box<dyn Any>>,
6}
7/// WIP: not fully functionnal/practical
8/// there is a way of getting a type name with `std::any::type_name::<T>()` which returns `"T" as &str`
9/// with a macro we can get the reversed processus by parsing the `"T"` inside `downcast_ref::<T>()`
10/// allowing a behavior such as `let value = dict.get!(my_key).unwrap();`, which could be simplified as
11/// `let value = dict[my_key]`, instead of `let value: &T = dict.get::<T>(my_key).unwrap();`
12/// `.unwrap()` is needed as it is the responsibility of the coder to handle missbehavior of the dict usage
13/// # Example of current usage
14/// ```rust
15/// # use cats_utils::dict::Dict;
16/// let mut my_dict = Dict::new();
17/// my_dict.insert("key", "value");
18/// println!("{}", my_dict.get::<&str>("key").unwrap());
19/// ```
20impl<T> Dict<T>
21where
22 T: Eq + PartialEq + Hash,
23{
24 pub fn new() -> Self {
25 Dict {
26 inner: HashMap::new(),
27 }
28 }
29 pub fn insert<U: 'static>(&mut self, key: T, hole: U) {
30 self.inner.insert(key, Box::new(hole));
31 }
32
33 pub fn get<U: 'static>(&self, key: T) -> Result<&U, DictError> {
34 // match self.inner.get(&key).unwrap().as_ref().downcast_ref::<U>()
35 match self.inner.get(&key) {
36 Some(boxed_value) => match boxed_value.as_ref().downcast_ref::<U>() {
37 Some(value) => Ok(value),
38 None => Err(DictError::FailedCasting),
39 },
40 None => Err(DictError::KeyNotFound),
41 }
42 }
43 pub fn get_mut<U: 'static>(&mut self, key: T) -> Result<&mut U, DictError> {
44 // match self.inner.get(&key).unwrap().as_ref().downcast_ref::<U>()
45 match self.inner.get_mut(&key) {
46 Some(boxed_value) => match boxed_value.as_mut().downcast_mut::<U>() {
47 Some(value) => Ok(value),
48 None => Err(DictError::FailedCasting),
49 },
50 None => Err(DictError::KeyNotFound),
51 }
52 }
53}
54#[derive(Debug)]
55pub enum DictError {
56 KeyNotFound,
57 FailedCasting,
58}