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
use core::{
    marker::PhantomData,
    pin::pin,
    ptr,
    task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
};

use crate::{higher_ranked_trait, higher_ranked_type, hkt::Marker};

higher_ranked_trait! {
    pub type class SendFuture[Output] for<'a> {
        type Bound = &'a Output;

        type T: { core::future::Future<Output = Output> + Sized + Send + 'a }
        where {
            Output: 'a
        };
        type HigherRanked: {} where {
            // Output: Send
        };
    }
}

/// Trait for effects.
pub trait Effect: Send + 'static {
    type Future<T: Send>: SendFuture::MemberType<T>;

    fn wrap<'a, F>(future: F) -> SendFuture::T<'a, F::Output, Self::Future<F::Output>>
    where
        F: core::future::Future + Send + 'a,
        <F as core::future::Future>::Output: Send;

    fn ready<'a, T: Send>(value: T) -> SendFuture::T<'a, T, Self::Future<T>>;

    fn map<'a, T, U, F>(
        future: SendFuture::T<'a, T, Self::Future<T>>,
        func: F,
    ) -> SendFuture::T<'a, U, Self::Future<U>>
    where
        T: Send,
        U: Send,
        F: FnOnce(T) -> U + Send + 'a;

    #[cfg(feature = "alloc")]
    #[inline]
    fn wrap_boxed<'a, F>(
        future: core::pin::Pin<Box<F>>,
    ) -> SendFuture::T<'a, F::Output, Self::Future<F::Output>>
    where
        F: core::future::Future + Send + 'a,
        <F as core::future::Future>::Output: Send,
    {
        Self::wrap(future)
    }
}

pub type Future<'a, T, E> = SendFuture::T<'a, T, <E as Effect>::Future<T>>;

pub struct Blocking<B = Spin> {
    _marker: PhantomData<fn() -> B>,
}

pub trait BlockOn: 'static {
    fn block_on<F>(future: F) -> F::Output
    where
        F: core::future::Future + Send,
        <F as core::future::Future>::Output: Send;
}

/// [`BlockOn`] implementer that just spins on the future.
///
/// This is useful for futures that are alwayd ready.
pub enum Spin {}

impl BlockOn for Spin {
    #[inline(always)]
    fn block_on<F>(future: F) -> F::Output
    where
        F: core::future::Future + Send,
    {
        let waker = noop();
        let mut context = Context::from_waker(&waker);

        let mut future = pin!(future);
        loop {
            if let Poll::Ready(value) = future.as_mut().poll(&mut context) {
                return value;
            }
        }
    }
}

#[inline]
pub fn noop() -> Waker {
    const VTABLE: &RawWakerVTable = &RawWakerVTable::new(
        // Cloning just returns a new no-op raw waker
        |_| RAW,
        // `wake` does nothing
        |_| {},
        // `wake_by_ref` does nothing
        |_| {},
        // Dropping does nothing as we don't allocate anything
        |_| {},
    );
    const RAW: RawWaker = RawWaker::new(ptr::null(), VTABLE);
    unsafe { Waker::from_raw(RAW) }
}

higher_ranked_type! {
    impl SendFuture {
        impl['a, Output] type T['a, Output] for core::future::Ready<Output> =
            core::future::Ready<Output>
        where {
            Output: Send
        };

        impl['a, Output] type HigherRanked['a, Output] for core::future::Ready<Output> =
            core::future::Ready<Output>
        where {
            Output: Send
        };
    }
}

impl<B: BlockOn> Effect for Blocking<B> {
    type Future<T: Send> = core::future::Ready<T>;

    fn wrap<'a, F>(future: F) -> SendFuture::T<'a, F::Output, Self::Future<F::Output>>
    where
        F: core::future::Future + Send + 'a,
        <F as core::future::Future>::Output: Send,
    {
        core::future::ready(B::block_on(future))
    }

    fn ready<'a, T: Send>(value: T) -> SendFuture::T<'a, T, Self::Future<T>> {
        core::future::ready(value)
    }

    fn map<'a, T, U, F>(
        future: SendFuture::T<'a, T, Self::Future<T>>,
        func: F,
    ) -> SendFuture::T<'a, U, Self::Future<U>>
    where
        T: Send,
        U: Send,
        F: FnOnce(T) -> U + Send + 'a,
    {
        let value = B::block_on(future);
        core::future::ready(func(value))
    }
}

mod sealed {
    pub enum BoxedFuture<'lt, Output> {
        Box(core::pin::Pin<Box<dyn core::future::Future<Output = Output> + Send + 'lt>>),
        Ready(core::future::Ready<Output>),
    }

    impl<'lt, Output> core::future::Future for BoxedFuture<'lt, Output> {
        type Output = Output;

        fn poll(
            mut self: core::pin::Pin<&mut Self>,
            cx: &mut core::task::Context<'_>,
        ) -> core::task::Poll<Self::Output> {
            match &mut *self {
                BoxedFuture::Box(future) => future.as_mut().poll(cx),
                BoxedFuture::Ready(future) => core::pin::Pin::new(future).poll(cx),
            }
        }
    }
}

#[cfg(feature = "alloc")]
pub struct BoxedFutureHrt<Output>(Marker<Output>);

#[cfg(feature = "alloc")]
higher_ranked_type! {
    impl SendFuture {
        impl['a, Output] type T['a, Output] for BoxedFutureHrt<Output> =
            sealed::BoxedFuture<'a, Output>
        where {
            Output: Send
        };

        impl['a, Output] type HigherRanked['a, Output] for sealed::BoxedFuture<'a, Output> =
            BoxedFutureHrt<Output>
        where {
            Output: Send
        };
    }
}

#[cfg(feature = "alloc")]
pub enum Async {}

#[cfg(feature = "alloc")]
impl Effect for Async {
    type Future<T: Send> = BoxedFutureHrt<T>;

    fn wrap<'a, F>(future: F) -> SendFuture::T<'a, F::Output, Self::Future<F::Output>>
    where
        F: core::future::Future + Send + 'a,
        <F as core::future::Future>::Output: Send,
    {
        sealed::BoxedFuture::Box(Box::pin(future))
    }

    fn ready<'a, T: Send>(value: T) -> SendFuture::T<'a, T, Self::Future<T>> {
        sealed::BoxedFuture::Ready(core::future::ready(value))
    }

    fn map<'a, T, U, F>(
        future: SendFuture::T<'a, T, Self::Future<T>>,
        func: F,
    ) -> SendFuture::T<'a, U, Self::Future<U>>
    where
        T: Send,
        U: Send,
        F: FnOnce(T) -> U + Send + 'a,
    {
        match future {
            sealed::BoxedFuture::Box(future) => Self::wrap(async { func(future.await) }),
            sealed::BoxedFuture::Ready(future) => {
                let value = Spin::block_on(future);
                Self::ready(func(value))
            }
        }
    }

    fn wrap_boxed<'a, F>(
        future: core::pin::Pin<Box<F>>,
    ) -> SendFuture::T<'a, F::Output, Self::Future<F::Output>>
    where
        F: core::future::Future + Send + 'a,
        <F as core::future::Future>::Output: Send,
    {
        sealed::BoxedFuture::Box(future)
    }
}