mf_state/
gotham_state.rs

1use std::any::Any;
2use std::any::TypeId;
3use std::sync::Arc;
4
5use dashmap::DashMap;
6
7#[derive(Default, Debug)]
8pub struct GothamState {
9    /// 使用BTreeMap存储不同类型的数据,以TypeId为键
10    data: DashMap<TypeId, Arc<dyn Any + Send + Sync>>,
11}
12
13impl GothamState {
14    /// 将数据存入状态容器中
15    ///
16    /// # 参数
17    /// * `t` - 要存储的数据,必须是'static生命周期
18    pub fn put<T: Clone + Send + Sync + 'static>(
19        &self,
20        t: T,
21    ) {
22        let type_id = TypeId::of::<T>();
23        self.data.insert(type_id, Arc::new(t));
24    }
25
26    /// 检查状态容器中是否包含指定类型的数据
27    ///
28    /// # 参数
29    /// * 泛型参数T - 要检查的类型
30    ///
31    /// # 返回值
32    /// * 如果存在返回true,否则返回false
33    pub fn has<T: Send + Sync + 'static>(&self) -> bool {
34        let type_id = TypeId::of::<T>();
35        self.data.contains_key(&type_id)
36    }
37    pub fn get<T: Clone + Send + Sync + 'static>(&self) -> Option<Arc<T>> {
38        self.try_get::<T>()
39    }
40
41    pub fn try_get<T: Clone + Send + Sync + 'static>(&self) -> Option<Arc<T>> {
42        let type_id = TypeId::of::<T>();
43        if let Some(v) = self.data.get(&type_id) {
44            let value = v.value().clone();
45            Arc::downcast(value).ok()
46        } else {
47            None
48        }
49    }
50
51    pub fn try_take<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
52        let type_id = TypeId::of::<T>();
53        match self.data.remove(&type_id) {
54            Some((_, v)) => Arc::downcast(v).ok(),
55            None => None,
56        }
57    }
58    /// 从状态容器中移除并返回指定类型的数据
59    ///
60    /// # 参数
61    /// * 泛型参数T - 要移除的类型
62    ///
63    /// # 返回值
64    /// * 返回T,如果数据不存在则返回None
65    pub fn take<T: Send + Sync + 'static>(&mut self) -> Option<Arc<T>> {
66        self.try_take::<T>()
67    }
68}