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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#![allow(unused)]
#![deny(unsafe_code)]
#![allow(clippy::type_complexity)]

use core::{
    any::{Any, TypeId},
    ops::Deref,
};
use std::{
    collections::HashMap,
    sync::{Mutex, MutexGuard, OnceLock, RwLock},
};

use effectful::{block_on::Spin, blocking::Blocking as Block, bound::No};

pub mod builder;
pub mod protocol;
pub mod walker;

pub struct StaticTypeMap {
    map: OnceLock<RwLock<HashMap<TypeId, &'static (dyn Any + Send + Sync)>>>,
}

impl StaticTypeMap {
    pub const fn new() -> Self {
        Self {
            map: OnceLock::new(),
        }
    }

    pub fn get_or_init<T: Send + Sync + 'static, F: FnOnce() -> T>(&self, f: F) -> &'static T {
        let map_init = || RwLock::new(HashMap::new());

        let map = self.map.get_or_init(map_init).read().unwrap();

        if let Some(once) = map.get(&TypeId::of::<T>()) {
            return once.downcast_ref::<T>().unwrap();
        }

        drop(map);

        let mut map = self.map.get_or_init(map_init).write().unwrap();
        let once = &*Box::leak(Box::new(f()));
        map.insert(TypeId::of::<T>(), once);

        once
    }
}

pub struct ContextLock<T> {
    lock: Mutex<T>,
    checkpoint: fn(&T),
}

impl<T> ContextLock<T> {
    pub const fn new(context: T, checkpoint: fn(&T)) -> Self {
        Self {
            lock: Mutex::new(context),
            checkpoint,
        }
    }

    pub fn lock(&self) -> ContextGuard<'_, T> {
        ContextGuard {
            lock: self,
            guard: self.lock.lock().unwrap(),
        }
    }
}

pub struct ContextGuard<'a, T> {
    lock: &'a ContextLock<T>,
    guard: MutexGuard<'a, T>,
}

impl<'a, T> Drop for ContextGuard<'a, T> {
    fn drop(&mut self) {
        (self.lock.checkpoint)(&*self.guard)
    }
}

impl<'a, T> Deref for ContextGuard<'a, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.guard
    }
}