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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
#![deny(missing_docs)]

//! A simple crate to create a promise/future pair.
//!
//! Promise/future pair is a very common pattern in other languages. You can think it as a
//! oneshot channel, but it's only one way future. The crate is also executor independent.
//!
//! # Usage
//!
//! Include it in cargo dependency:
//!
//! ```toml
//! mrwei = "0.1"
//! ```
//!
//! You can use `pair` to create an instance of future and promise.
//! ```ignored
//! let (f, p) = mrwei::pair::<Type>();
//! ```
//!
//! You probably need to either move the future or the promise to another
//! thread and await or set a value respectively. When the promise is offered
//! a value, the corresponding future will also be notified.

use std::mem::MaybeUninit;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::task::Waker;
use std::{
    cell::UnsafeCell,
    pin::Pin,
    ptr::NonNull,
    task::{Context, Poll},
};

/// When the promise/future is just created, the state is IDLE.
const IDLE: usize = 0;
/// When the promise is set to a value and its current state is IDLE,
/// it will transit to SET.
const SET: usize = 1;
/// When a promise is set to a value and its current state is WAIT,
/// it will transit to SET_WAIT and then calls wake. If it's WAIT_REPLACE,
/// it will transit to SET_WAIT and not calls wake.
const SET_WAIT: usize = 2;
/// When a future is polled and its current state is IDLE, it will update
/// waker and then transit to WAIT.
const WAIT: usize = 3;
/// When a future is polled and its current state is WAIT, it's necessary
/// to update waker, it will transit to WAIT_REPLACE first.
const WAIT_REPLACE: usize = 4;
/// When a future is polled and its current state is SET or SET_WAIT, it
/// take the value and transit to DRAIN.
const DRAIN: usize = 5;
/// When a future is dropped:
///     if current state is IDLE, it will transit to WASTE;
///     if current state is SET/SET_WAIT, it will drop the value and transit to WASTE;
///     if current state is WAIT, it will transit to WASTE and drop the waker;
///     if current state is WASTE/DRAIN, it will no nothing.
/// When a promise is dropped:
///     if current state is IDLE, it will transit to WASTE;
///     if current state is WAIT, it will transit to WASTE and notify the waker;
///     if current state is WAIT_REPLACE, it will transit to WASTE;
///     if current state is SET/SET_WAIT/DRAIN/WASTE, it will do nothing.
/// When a future is polled and its current state is WASTE, it will drop the waker;
/// When a promise is set to a value and its current value is WASTE, it will do nothing.
const WASTE: usize = 6;

/// An error indicates either future or promise is dropped before the other end
/// makes any actions.
#[derive(Debug, PartialEq)]
pub struct Waste;

#[repr(C)]
struct Shared<T> {
    value: UnsafeCell<MaybeUninit<T>>,
    state: AtomicUsize,
    waker: UnsafeCell<Option<Waker>>,
}

/// A struct that accepts a value and notify the corresponding future.
pub struct Promise<T> {
    shared: NonNull<Shared<T>>,
}

unsafe impl<T: Send> Send for Promise<T> {}
unsafe impl<T: Send> Send for Future<T> {}

fn get_poll_state(s: usize) -> usize {
    s & 0x07
}

fn set_poll_state(s: usize, poll_state: usize) -> usize {
    (s & !0x07) | poll_state
}

fn get_ref_state(s: usize) -> usize {
    s >> 3
}

fn desc_ref_state(s: usize) -> usize {
    s - 0x08
}

impl<T> Promise<T> {
    /// Offers a value to the promise.
    ///
    /// It will wake up any awaited futures.
    pub fn set_value(self, value: T) -> Option<T> {
        let shared = unsafe { self.shared.as_ref() };
        unsafe {
            (&mut *shared.value.get()).as_mut_ptr().write(value);
        }
        self.notify_value()
    }

    /// Get a mutable pointer to the underlying value.
    ///
    /// Remember to use `from_raw` to reclaim the memory and make notification work
    /// correctly.
    pub fn into_raw(s: Promise<T>) -> NonNull<MaybeUninit<T>> {
        let ptr = s.shared.as_ptr() as *mut MaybeUninit<T>;
        std::mem::forget(s);
        unsafe { NonNull::new_unchecked(ptr) }
    }

    /// Reconstruct the promise from given pointer.
    ///
    /// The pointer must be the returned value of `into_raw`.
    ///
    /// # Safety
    ///
    /// If the pointer is not generated by `into_raw`, it can lead to undefined behavior.
    pub unsafe fn from_raw(ptr: NonNull<MaybeUninit<T>>) -> Promise<T> {
        let ptr = ptr.as_ptr() as *mut Shared<T>;
        Promise {
            shared: NonNull::new_unchecked(ptr),
        }
    }

    fn notify_value(self) -> Option<T> {
        let shared = unsafe { self.shared.as_ref() };
        let mut state = shared.state.load(Ordering::Relaxed);
        let mut poll_state = get_poll_state(state);
        loop {
            let mut next_state = match poll_state {
                IDLE => set_poll_state(state, SET),
                WAIT | WAIT_REPLACE => set_poll_state(state, SET_WAIT),
                WASTE => unsafe {
                    return Some((&*shared.value.get()).as_ptr().read());
                },
                _ => unreachable!("unexpected state {}", poll_state),
            };
            next_state = desc_ref_state(next_state);
            match shared.state.compare_exchange_weak(
                state,
                next_state,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => break,
                Err(s) => {
                    state = s;
                    poll_state = get_poll_state(state);
                }
            }
        }

        if poll_state == WAIT {
            unsafe { &mut *shared.waker.get() }.take().unwrap().wake()
        }
        // We don't need to call dropping as ref count is done above.
        // Note that ref count has to be larger than 0 as future ref count
        // can only be changed when future is dropped, which will also change
        // the state to WASTE.
        std::mem::forget(self);
        None
    }

    /// Assumes the value is set.
    ///
    /// It will wake up any awaited futures.
    ///
    /// # Safety
    ///
    /// If no value has been set, calling the function lead to undefined behavior.
    pub unsafe fn assume_value_set(self) {
        self.notify_value();
    }
}

impl<T> Drop for Promise<T> {
    /// Drops the promise.
    ///
    /// It will wake up any awaited futures.
    fn drop(&mut self) {
        let shared = unsafe { self.shared.as_ref() };
        let mut state = shared.state.load(Ordering::Relaxed);
        let mut poll_state;
        loop {
            poll_state = get_poll_state(state);
            let next_state = if let DRAIN | WASTE = poll_state {
                desc_ref_state(state)
            } else if let SET | SET_WAIT = poll_state {
                unreachable!("unexpected state {}", poll_state);
            } else {
                desc_ref_state(set_poll_state(state, WASTE))
            };
            match shared.state.compare_exchange_weak(
                state,
                next_state,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => break,
                Err(s) => state = s,
            }
        }
        if let IDLE | WAIT_REPLACE = poll_state {
            return;
        }
        if poll_state == WAIT {
            unsafe {
                (&mut *shared.waker.get()).take().unwrap().wake();
            }
        }
        if get_ref_state(state) == 1 {
            unsafe {
                Box::from_raw(self.shared.as_ptr());
            }
        }
    }
}

/// A future waiting for the remote value set by `Promise`.
pub struct Future<T> {
    shared: NonNull<Shared<T>>,
}

impl<T> Future<T> {
    fn poll_idle(&self, shared: &Shared<T>, mut state: usize) -> Poll<Result<T, Waste>> {
        loop {
            let next_state = set_poll_state(state, WAIT);
            match shared.state.compare_exchange_weak(
                state,
                next_state,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => return Poll::Pending,
                Err(s) => {
                    state = s;
                    match get_poll_state(state) {
                        IDLE => (),
                        SET => return self.poll_set(shared, state),
                        WASTE => {
                            unsafe { &mut *shared.waker.get() }.take();
                            return Poll::Ready(Err(Waste));
                        }
                        s => unreachable!("unexpected state {}", s),
                    }
                }
            }
        }
    }

    fn poll_set(&self, shared: &Shared<T>, mut state: usize) -> Poll<Result<T, Waste>> {
        loop {
            let next_state = set_poll_state(state, DRAIN);
            match shared.state.compare_exchange_weak(
                state,
                next_state,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => unsafe {
                    let value = &mut *shared.value.get();
                    return Poll::Ready(Ok(value.as_ptr().read()));
                },
                Err(s) => {
                    state = s;
                    match get_poll_state(state) {
                        SET | SET_WAIT => (),
                        s => unreachable!("unexpacted state {}", s),
                    }
                }
            }
        }
    }

    fn poll_wait(
        &self,
        shared: &Shared<T>,
        mut state: usize,
        ctx: &mut Context,
    ) -> Poll<Result<T, Waste>> {
        loop {
            let next_state = set_poll_state(state, WAIT_REPLACE);
            match shared.state.compare_exchange_weak(
                state,
                next_state,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => break,
                Err(s) => {
                    state = s;
                    match get_poll_state(state) {
                        WAIT => (),
                        SET_WAIT => return self.poll_set(shared, state),
                        WASTE => {
                            unsafe { &mut *shared.waker.get() }.take();
                            return Poll::Ready(Err(Waste));
                        }
                        s => unreachable!("unexpected state {}", s),
                    }
                }
            }
        }
        unsafe {
            let w = &mut *shared.waker.get();
            if !w.as_ref().unwrap().will_wake(ctx.waker()) {
                *w = Some(ctx.waker().clone());
            }
        }
        loop {
            let next_state = set_poll_state(state, WAIT);
            match shared.state.compare_exchange_weak(
                state,
                next_state,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => return Poll::Pending,
                Err(s) => {
                    state = s;
                    match get_poll_state(state) {
                        WAIT_REPLACE => (),
                        SET_WAIT => {
                            unsafe {
                                (&mut *shared.waker.get()).take();
                            }
                            return self.poll_set(shared, state);
                        }
                        WASTE => {
                            unsafe { &mut *shared.waker.get() }.take();
                            return Poll::Ready(Err(Waste));
                        }
                        s => unreachable!("unreachable state {}", s),
                    }
                }
            }
        }
    }
}

impl<T> std::future::Future for Future<T> {
    type Output = Result<T, Waste>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let shared = unsafe { self.shared.as_ref() };
        let state = shared.state.load(Ordering::Relaxed);
        let poll_state = get_poll_state(state);
        match poll_state {
            IDLE => {
                unsafe {
                    *shared.waker.get() = Some(cx.waker().clone());
                }
                self.poll_idle(shared, state)
            }
            SET | SET_WAIT => self.poll_set(shared, state),
            WAIT => self.poll_wait(shared, state, cx),
            DRAIN | WASTE => Poll::Ready(Err(Waste)),
            _ => unreachable!("unexpected state {}", poll_state),
        }
    }
}

impl<T> Drop for Future<T> {
    fn drop(&mut self) {
        let shared = unsafe { self.shared.as_ref() };
        let mut state = shared.state.load(Ordering::Acquire);
        loop {
            let poll_state = get_poll_state(state);
            let next_state = match poll_state {
                DRAIN => desc_ref_state(state),
                WASTE => {
                    unsafe { &mut *shared.waker.get() }.take();
                    desc_ref_state(state)
                }
                _ => desc_ref_state(set_poll_state(state, WASTE)),
            };
            match shared.state.compare_exchange_weak(
                state,
                next_state,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => break,
                Err(s) => state = s,
            }
        }
        if let SET | SET_WAIT = get_poll_state(state) {
            unsafe {
                (&mut *shared.value.get()).as_mut_ptr().read();
            }
        }
        if WAIT == get_poll_state(state) {
            unsafe { &mut *shared.waker.get() }.take();
        }
        if get_ref_state(state) == 1 {
            unsafe {
                Box::from_raw(self.shared.as_ptr());
            }
        }
    }
}

/// Creates a pair of future/promise.
pub fn pair<T>() -> (Future<T>, Promise<T>) {
    let shared = unsafe {
        NonNull::new_unchecked(Box::into_raw(Box::new(Shared {
            state: AtomicUsize::new(0x80 * 2),
            value: UnsafeCell::new(MaybeUninit::uninit()),
            waker: UnsafeCell::new(None),
        })))
    };
    (Future { shared }, Promise { shared })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_wake() {
        let (f, p) = crate::pair();
        assert_eq!(None, p.set_value("test"));
        let res = f.await;
        assert_eq!(res, Ok("test"));
    }

    #[tokio::test]
    async fn test_drop_promise() {
        let (f, p) = crate::pair::<usize>();
        drop(p);
        let res = f.await;
        assert_eq!(res, Err(Waste));
    }

    #[tokio::test]
    async fn test_drop_future() {
        let (f, p) = crate::pair();
        drop(f);
        assert_eq!(Some("test"), p.set_value("test"));
    }

    #[tokio::test]
    async fn test_block_future() {
        let (f, p) = crate::pair();
        tokio::spawn(async move {
            let _ = p.set_value("test");
        });
        let res = f.await;
        assert_eq!(res, Ok("test"));
    }

    #[tokio::test]
    async fn test_assume_init() {
        let (f, p) = crate::pair();
        tokio::spawn(async move {
            let ptr = Promise::into_raw(p);
            unsafe {
                ptr.as_ptr().write(MaybeUninit::new("test"));
                Promise::from_raw(ptr).assume_value_set();
            }
        });
        let res = f.await;
        assert_eq!(res, Ok("test"));
    }
}