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
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
use core::any::Any;
use core::future::Future;
use core::pin::Pin;
use std::sync::Arc;

use tokio::sync::mpsc;
use tokio::sync::Notify;
use tokio::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};

#[derive(Debug)]
pub enum Lock<'a, T> {
    ReadOnly(&'a T),
    RwRead(RwLockReadGuard<'a, T>),
    RwWrite(RwLockWriteGuard<'a, T>),
    WriteOnly(MutexGuard<'a, T>),
}

impl<'a, T> Lock<'a, T> {
    pub fn get_ref(&self) -> &T {
        match self {
            Lock::ReadOnly(inner) => &inner,
            Lock::RwRead(inner) => &inner,
            Lock::RwWrite(inner) => &inner,
            Lock::WriteOnly(inner) => &inner,
        }
    }

    pub fn get_mut(&mut self) -> &mut T {
        match self {
            Lock::ReadOnly(_) => panic!("!!"),
            Lock::RwRead(_) => panic!("!!"),
            Lock::RwWrite(inner) => &mut *inner,
            Lock::WriteOnly(inner) => &mut *inner,
        }
    }
}

pub enum Downcasted<T> {
    ReadOnly(Arc<T>),
    ReadWrite(Arc<RwLock<T>>),
    WriteOnly(Arc<Mutex<T>>),
}

impl<T> Clone for Downcasted<T> {
    fn clone(&self) -> Self {
        match self {
            Downcasted::ReadOnly(inner) => Downcasted::ReadOnly(inner.clone()),
            Downcasted::ReadWrite(inner) => Downcasted::ReadWrite(inner.clone()),
            Downcasted::WriteOnly(inner) => Downcasted::WriteOnly(inner.clone()),
        }
    }
}

impl<T: 'static> Downcasted<T> {
    pub async fn lock_read(&self) -> Lock<'_, T> {
        match self {
            Downcasted::ReadOnly(inner) => Lock::ReadOnly(&inner),
            Downcasted::ReadWrite(inner) => Lock::RwRead(inner.read().await),
            Downcasted::WriteOnly(inner) => Lock::WriteOnly(inner.lock().await),
        }
    }
    pub async fn lock_write(&self) -> Lock<'_, T> {
        match self {
            Downcasted::ReadOnly(_) => unimplemented!(),
            Downcasted::ReadWrite(inner) => Lock::RwWrite(inner.write().await),
            Downcasted::WriteOnly(inner) => Lock::WriteOnly(inner.lock().await),
        }
    }
}

#[derive(Clone)]
pub struct Untyped {
    inner: Arc<dyn Any + Send + Sync>,
}

impl Untyped {
    pub fn new_readonly<T: Send + Sync + 'static>(item: T) -> Self {
        Self {
            inner: Arc::new(item),
        }
    }

    pub fn new_rwlock<T: Send + Sync + 'static>(item: T) -> Self {
        Self {
            inner: Arc::new(RwLock::new(item)),
        }
    }

    pub fn new_mutex<T: Send + 'static>(item: T) -> Self {
        Self {
            inner: Arc::new(Mutex::new(item)),
        }
    }

    pub fn new_local<T: 'static, F: FnOnce() -> T + Send + 'static>(f: F) -> Self {
        Self {
            inner: Arc::new(ThreadDedicated::new(f)),
        }
    }

    pub fn downcast_sync<T: Send + Sync + 'static>(self) -> Option<Downcasted<T>> {
        let item = match self.inner.clone().downcast::<RwLock<T>>() {
            Ok(inner) => Downcasted::ReadWrite(inner),
            Err(_) => return None,
        };

        Some(item)
    }

    pub fn downcast_send1<T: Send + 'static>(self) -> Option<Downcasted<T>> {
        let item = match self.inner.clone().downcast::<Mutex<T>>() {
            Ok(inner) => Downcasted::WriteOnly(inner),
            Err(_) => return None,
        };

        Some(item)
    }

    pub fn downcast_send<T: Send + 'static>(self) -> Option<Arc<Mutex<T>>> {
        self.inner.clone().downcast::<Mutex<T>>().ok()
    }

    #[inline]
    pub fn downcast_local<T: 'static>(self) -> Option<Arc<ThreadDedicated<T>>> {
        self.inner.clone().downcast::<ThreadDedicated<T>>().ok()
    }
}

pub struct ThreadDedicated<T: 'static> {
    sender: mpsc::Sender<
        Box<dyn for<'a> FnOnce(&'a mut T) -> Pin<Box<dyn Future<Output = ()> + 'a>> + Send>,
    >,
    notify: Arc<Notify>,
}

impl<T: 'static> ThreadDedicated<T> {
    pub fn new<F: FnOnce() -> T + Send + 'static>(builder: F) -> Self {
        let notify = Arc::new(Notify::new());
        let (sender, mut receiver) = mpsc::channel(1);

        let sender: mpsc::Sender<
            Box<dyn for<'a> FnOnce(&'a mut T) -> Pin<Box<dyn Future<Output = ()> + 'a>> + Send>,
        > = sender;
        let notify_clone = notify.clone();
        std::thread::spawn(move || {
            futures::executor::block_on(async move {
                let mut obj = builder();

                loop {
                    let cb = match receiver.recv().await {
                        Some(x) => x,
                        None => break,
                    };

                    cb(&mut obj).await;
                    notify_clone.notify_one();
                }
            });
        });

        Self { sender, notify }
    }

    pub async fn spawn_local<
        F: for<'a> FnOnce(&'a mut T) -> Pin<Box<dyn Future<Output = ()> + 'a>> + Send + 'static,
    >(
        &self,
        cb: F,
    ) {
        self.sender.send(Box::new(cb)).await.ok().unwrap();

        self.notify.notified().await
    }
}