teo_runtime/request/
local_objects.rs

1use std::any::Any;
2use std::collections::BTreeMap;
3use std::fmt;
4use std::fmt::{Debug, Formatter};
5use std::sync::Arc;
6use history_box::HistoryBox;
7
8#[derive(Default, Clone)]
9pub struct LocalObjects {
10    inner: Arc<Inner>,
11}
12
13#[derive(Default)]
14struct Inner {
15    map: HistoryBox<BTreeMap<String, HistoryBox<Box<dyn Any>>>>,
16}
17
18impl LocalObjects {
19
20    #[inline]
21    pub fn new() -> LocalObjects {
22        Self {
23            inner: Arc::new(Inner {
24                map: HistoryBox::new_with(BTreeMap::new()),
25            })
26        }
27    }
28
29    fn map_mut(&self) -> &mut BTreeMap<String, HistoryBox<Box<dyn Any>>> {
30        unsafe { self.inner.map.get_mut().unwrap() }
31    }
32
33    fn map_immut(&self) -> &BTreeMap<String, HistoryBox<Box<dyn Any>>> {
34        self.inner.map.get().unwrap()
35    }
36
37    pub fn insert<T: 'static>(&self, key: impl Into<String>, val: T) {
38        let key = key.into();
39        let contains = self.map_immut().contains_key(&key);
40        if contains {
41            self.map_mut().get_mut(&key).unwrap().set(Box::new(val));
42        } else {
43            self.map_mut().insert(key, HistoryBox::new_with(Box::new(val)));
44        }
45    }
46
47    pub fn get<T: 'static>(&self, key: &str) -> Option<&T> {
48        self.map_immut().get(key).and_then(|boxed| boxed.get().unwrap().downcast_ref())
49    }
50
51    pub fn get_mut<T: 'static>(&self, key: &str) -> Option<&mut T> {
52        self.map_immut().get(key).and_then(|boxed| unsafe { boxed.get_mut() }.unwrap().downcast_mut())
53    }
54
55    pub fn contains(&self, key: &str) -> bool {
56        self.map_immut().contains_key(key)
57    }
58
59    pub fn remove(&self, key: &str) {
60        self.map_mut().remove(key);
61    }
62
63    pub fn len(&self) -> usize {
64        self.map_immut().len()
65    }
66
67    pub fn clear(&self) {
68        self.map_mut().clear()
69    }
70}
71
72impl Debug for LocalObjects {
73
74    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
75        let mut debug_struct = f.debug_struct("LocalObjects");
76        for (k, v) in self.map_immut() {
77            debug_struct.field(&k, &v);
78        }
79        debug_struct.finish()
80    }
81}
82
83fn downcast_owned<T: 'static>(boxed: Box<dyn Any>) -> Option<T> {
84    boxed.downcast().ok().map(|boxed| *boxed)
85}
86
87unsafe impl Send for LocalObjects { }
88unsafe impl Sync for LocalObjects { }