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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
extern crate futures;

/// A futures implementation of watched variables.
pub mod watched_variables {
    use futures::task::AtomicTask;
    use futures::{Async, Poll, Stream};

    use std::convert::Infallible;
    use std::ops::Deref;
    use std::ops::DerefMut;
    use std::sync::MutexGuard;
    use std::sync::{Arc, Mutex};
    use std::sync::atomic::{AtomicU32, Ordering};

    #[derive(Clone, Debug)]
    pub enum StreamState {
        NotReady,
        Ready(usize),
        Closed,
    }

    /// This `futures::Stream` implementation will be notified whenever a `WatchedVariableAccessor` is dropped
    /// If the accessor was mutably derefenced, then a clone of the value after dropping will be sent upon polling
    ///
    /// It implements Stream, where each frame will be a clone of its content (an Arc on the variable)
    pub struct VariableWatcher<T> {
        pub task: Arc<AtomicTask>,
        pub content: Arc<Mutex<(T, StreamState)>>,
    }

    impl<T> std::fmt::Debug for VariableWatcher<T> {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            match self.content.lock() {
                Ok(guard) => write!(f, "VariableWatcher {{{:?}}}", &guard.1),
                Err(e) => write!(f, "VariableWatcher(Poisonned) {{{:?}}}", e.get_ref().1),
            }
        }
    }

    impl<T> Clone for VariableWatcher<T> {
        fn clone(&self) -> Self {
            VariableWatcher {
                task: self.task.clone(),
                content: self.content.clone(),
            }
        }
    }

    impl<T> Stream for VariableWatcher<T> {
        type Item = Arc<Mutex<(T, StreamState)>>;
        type Error = Infallible;
        fn poll(&mut self) -> Poll<Option<<Self as Stream>::Item>, <Self as Stream>::Error> {
            self.task.register();
            let mut guard = self.content.lock().unwrap();
            match (&mut guard.1) {
                StreamState::NotReady => Ok(Async::NotReady),
                StreamState::Closed => Ok(Async::Ready(None)),
                StreamState::Ready(count) => {
                    *count -= 1;
                    if *count <= 0 {
                        (*guard).1 = StreamState::NotReady;
                    }
                    Ok(Async::Ready(Some(self.content.clone())))
                }
            }
        }
    }

    /// A watched variable. Behaves similarly to a mutex, except that watchers obtained from its
    /// `get_watcher()` method will be notified upon mutable dereferencing.
    pub struct WatchedVariable<T> {
        task: Arc<AtomicTask>,
        content: Arc<Mutex<(T, StreamState)>>,
        counter: Arc<std::sync::atomic::AtomicU32>,
    }

    impl<T> Clone for WatchedVariable<T> {
        fn clone(&self) -> Self {
            self.counter.fetch_add(1, Ordering::Relaxed);
            WatchedVariable {
                task: self.task.clone(),
                content: self.content.clone(),
                counter: self.counter.clone(),
            }
        }
    }

    impl<T> WatchedVariable<T> {
        /// Constructs a `WatchedVariable` from `value`. This initialisation value will be returned by the first `poll()`
        /// on its watchers unless altered before the watchers are started
        pub fn from(value: T) -> WatchedVariable<T> {
            WatchedVariable {
                task: Arc::new(AtomicTask::new()),
                content: Arc::new(Mutex::new((value, StreamState::Ready(1)))),
                counter: Arc::new(AtomicU32::new(1)),
            }
        }

        pub fn get_watcher(&self) -> VariableWatcher<T> {
            VariableWatcher {
                task: self.task.clone(),
                content: self.content.clone(),
            }
        }

        /// Similar to Mutex::lock(), but the provided Accessor will trigger a `poll`
        /// upon `drop`, which will resolve to Ready if the accessor was accessed mutably.
        pub fn lock(&self) -> WatchedVariableAccessor<T> {
            WatchedVariableAccessor {
                task: self.task.clone(),
                content: self.content.lock().unwrap(),
            }
        }

        /// Allows to force ready upon the watcher.
        pub fn force_ready(&self) {
            let mut guard = self.content.lock().unwrap();
            match &mut guard.1 {
                StreamState::Ready(count) => {
                    *count += 1;
                }
                _ => guard.1 = StreamState::Ready(1),
            }
            self.task.notify();
        }
    }

    impl<T> Drop for WatchedVariable<T> {
        fn drop(&mut self) {
            let rc = self.counter.fetch_sub(1, Ordering::Relaxed);
            if rc <= 1 {
                let mut guard = self.content.lock().unwrap();
                guard.1 = StreamState::Closed;
                self.task.notify();
            }
        }
    }

    /// Similar to a MutexGuard, but dropping it will also notify watchers associated with it.
    pub struct WatchedVariableAccessor<'a, T> {
        task: Arc<AtomicTask>,
        content: MutexGuard<'a, (T, StreamState)>,
    }

    impl<'a, T> Drop for WatchedVariableAccessor<'a, T> {
        fn drop(&mut self) {
            self.task.notify();
        }
    }

    impl<'a, T> Deref for WatchedVariableAccessor<'a, T> {
        type Target = T;
        fn deref(&self) -> &<Self as Deref>::Target {
            return &self.content.0;
        }
    }

    impl<'a, T> DerefMut for WatchedVariableAccessor<'a, T> {
        fn deref_mut(&mut self) -> &mut <Self as Deref>::Target {
            match &mut self.content.1 {
                StreamState::Ready(count) => *count += 1,
                _ => self.content.1 = StreamState::Ready(1),
            };
            return &mut self.content.0;
        }
    }
}

/// A futures implementation of JS-like Promises.
pub mod promises {
    use std::cell::Cell;
    use std::sync::{Arc, Mutex};

    use futures::task::AtomicTask;
    use futures::{Async, Future, Poll};

    #[derive(Clone)]
    enum PromiseState {
        NotReady,
        Resolved,
        Rejected(String),
    }

    /// The "sender" side of a Promise
    pub struct Promise<T> {
        content: Arc<Mutex<Cell<Option<T>>>>,
        state: Arc<Mutex<PromiseState>>,
        task: Arc<AtomicTask>,
    }

    impl<T> Promise<T> {
        pub fn new() -> Self {
            Promise {
                content: Arc::new(Mutex::new(Cell::new(None))),
                state: Arc::new(Mutex::new(PromiseState::NotReady)),
                task: Arc::new(AtomicTask::new()),
            }
        }

        pub fn resolve(&self, value: T) {
            let mut guard = self.state.lock().unwrap();
            match (*guard).clone() {
                PromiseState::NotReady => {
                    self.content.lock().unwrap().set(Some(value));
                    *guard = PromiseState::Resolved;
                    self.task.notify();
                }
                _ => {
                    panic!("Attempt to resolve an already finished promise");
                }
            }
        }

        pub fn reject(&self, message: String) {
            let mut guard = self.state.lock().unwrap();
            match (*guard).clone() {
                PromiseState::NotReady => {
                    *guard = PromiseState::Rejected(message);
                    self.task.notify();
                }
                _ => {
                    panic!("Attempt to reject an already finished promise");
                }
            }
        }

        pub fn get_handle(&self) -> PromiseHandle<T> {
            PromiseHandle {
                content: self.content.clone(),
                state: self.state.clone(),
                task: self.task.clone(),
            }
        }
    }

    impl<T> Drop for Promise<T> {
        fn drop(&mut self) {
            let mut guard = self.state.lock().unwrap();
            match (*guard).clone() {
                PromiseState::NotReady => {
                    *guard = PromiseState::Rejected("Promise Dropped".into());
                    self.task.notify();
                }
                _ => {}
            }
        }
    }

    /// The "receiver": a `Future` used to watch a `Promise`
    #[derive(Clone)]
    pub struct PromiseHandle<T> {
        content: Arc<Mutex<Cell<Option<T>>>>,
        state: Arc<Mutex<PromiseState>>,
        task: Arc<AtomicTask>,
    }

    impl<T> Future for PromiseHandle<T> {
        type Item = T;
        type Error = String;

        fn poll(&mut self) -> Poll<<Self as Future>::Item, <Self as Future>::Error> {
            match *self.state.lock().unwrap() {
                PromiseState::NotReady => {
                    self.task.register();
                    Ok(Async::NotReady)
                }
                PromiseState::Rejected(ref reason) => Err(reason.clone()),
                PromiseState::Resolved => match self.content.lock().unwrap().take() {
                    Some(value) => Ok(Async::Ready(value)),
                    None => Err("Promise resolved but value was None".into()),
                },
            }
        }
    }
}