tearup/
shared_context.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use anymap::{CloneAny, Map};
use std::time::Duration;

#[cfg(feature = "async")]
pub use asyncc::*;

#[derive(PartialEq, Debug)]
pub struct TimeoutError {
    pub duration: Duration,
    pub ready_checks_interval: Duration,
}

type AnyMap = Map<dyn CloneAny>;

pub struct SharedContext(AnyMap);

impl SharedContext {
    pub fn register<T: 'static + Clone>(&mut self, value: T) {
        self.0.insert(value);
    }

    pub fn get<T: 'static + Clone>(&mut self) -> Option<T> {
        self.0.get::<T>().cloned()
    }
}

impl Default for SharedContext {
    fn default() -> Self {
        Self(AnyMap::new())
    }
}

#[cfg(feature = "async")]
pub mod asyncc {
    use anymap::{CloneAny, Map};
    use std::sync::Arc;
    use tokio::sync::Mutex;

    type AnymapSend = Map<dyn CloneAny + Send>;

    #[derive(Clone)]
    pub struct AsyncSharedContext(Arc<Mutex<AnymapSend>>);

    impl AsyncSharedContext {
        pub async fn register<T: 'static + Send + Clone>(&self, value: T) {
            let mut map = self.0.lock().await;
            map.insert(value);
        }

        pub async fn get<T: 'static + Send + Clone>(&mut self) -> Option<T> {
            self.0.lock().await.get::<T>().cloned()
        }
    }

    impl Default for AsyncSharedContext {
        fn default() -> Self {
            Self(Arc::new(Mutex::new(AnymapSend::new())))
        }
    }
}