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
// Pasts
// Copyright © 2019-2021 Jeron Aldaron Lau.
//
// Licensed under any of:
// - Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0)
// - MIT License (https://mit-license.org/)
// - Boost Software License, Version 1.0 (https://www.boost.org/LICENSE_1_0.txt)
// At your choosing (See accompanying files LICENSE_APACHE_2_0.txt,
// LICENSE_MIT.txt and LICENSE_BOOST_1_0.txt).
//
//! This file contains functions and macros that require unsafe code to work.
//! The rest of the libary should be unsafe-free.

use core::task::{Context, RawWaker, RawWakerVTable, Waker};

use crate::exec::Exec;

/// Create a future that waits on multiple futures concurrently and returns
/// their results as a tuple.
///
/// ```rust
/// use pasts::join;
///
/// async fn async_main() {
///     let a = async { "Hello, World!" };
///     let b = async { 15u32 };
///     let c = async { 'c' };
///     assert_eq!(("Hello, World!", 15u32, 'c'), join!(a, b, c));
/// }
///
/// pasts::block_on(async_main());
/// ```
#[macro_export]
macro_rules! join {
    // FIXME: Make this code simpler and easier to understand.
    ($($future:ident),* $(,)?) => {{
        use core::{
            task::{Poll, Context}, mem::MaybeUninit, pin::Pin, future::Future
        };

        // Move and Pin all the futures passed in.
        $(
            let mut $future = $future;
            // unsafe: safe because once value is moved and then shadowed, one
            // can't directly access anymore.
            let mut $future = unsafe {
                Pin::<&mut dyn Future<Output = _>>::new_unchecked(&mut $future)
            };
        )*

        // Join Algorithm
        struct MaybeFuture<'a, T, F: Future<Output = T>>(Option<Pin<&'a mut F>>);
        impl <T, F: Future<Output = T>> Future for MaybeFuture<'_, T, F> {
            type Output = T;
            fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
                let mut this = self.as_mut();
                if let Some(future) = this.0.as_mut() {
                    match future.as_mut().poll(cx) {
                        Poll::Ready(t) => {
                            this.0 = None;
                            Poll::Ready(t)
                        },
                        a => a,
                    }
                } else {
                    Poll::Pending
                }
            }
        }
        let mut count = 0usize;
        $(
            let mut $future = MaybeFuture(Some(Pin::new(&mut $future)));
            let mut $future = (Pin::new(&mut $future), MaybeUninit::uninit());
            count += 1;
        )*
        for _ in 0..count {
            struct __Pasts_Selector<'a, T> {
                closure: &'a mut dyn FnMut(&mut Context<'_>) -> Poll<T>,
            }
            impl<'a, T> Future for __Pasts_Selector<'a, T> {
                type Output = T;
                fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
                    (self.get_mut().closure)(cx)
                }
            }
            __Pasts_Selector { closure: &mut |__pasts_cx: &mut Context<'_>| {
                $(
                    match $future.0.as_mut().poll(__pasts_cx) {
                        Poll::Ready(pattern) => {
                            $future.1 = MaybeUninit::new(pattern);
                            return Poll::Ready(());
                        }
                        Poll::Pending => {}
                    }
                )*
                Poll::Pending
            } }.await
        }
        unsafe {
            ($($future.1.assume_init()),*)
        }
    }};
}

// Create a `Waker`.
//
// unsafe: Safe because `Waker`/`Context` can't outlive `Exec`.
#[inline]
#[allow(unsafe_code)]
pub(super) fn waker<F, T>(exec: &Exec, f: F) -> T
where
    F: FnOnce(&mut Context<'_>) -> T,
{
    let exec: *const Exec = exec;
    const RWVT: RawWakerVTable = RawWakerVTable::new(clone, wake, wake, drop);

    #[inline]
    unsafe fn clone(data: *const ()) -> RawWaker {
        RawWaker::new(data, &RWVT)
    }
    #[inline]
    unsafe fn wake(data: *const ()) {
        let exec: *const Exec = data.cast();
        (*exec).wake();
    }
    #[inline]
    unsafe fn drop(_: *const ()) {}

    let waker = unsafe { Waker::from_raw(RawWaker::new(exec.cast(), &RWVT)) };
    f(&mut Context::from_waker(&waker))
}

#[cfg(any(target_arch = "wasm32", not(feature = "std")))]
static mut EXEC: core::mem::MaybeUninit<Exec> =
    core::mem::MaybeUninit::<Exec>::uninit();

#[cfg(any(target_arch = "wasm32", not(feature = "std")))]
#[allow(unsafe_code)]
// unsafe: sound because threads can't happen on targets with no threads.
pub(crate) fn exec() -> &'static mut Exec {
    unsafe {
        EXEC = core::mem::MaybeUninit::new(Exec::new());
        &mut *EXEC.as_mut_ptr()
    }
}