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
//
// Copyright (c) 2023 ZettaScale Technology
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
//
// Contributors:
//   Pierre Avital, <pierre.avital@me.com>
//

use core::task::Context;

use crate::enums::IDeterminantProvider;
use crate::option::Option;
use crate::vtable::HasDropVt;
use crate::{IPtrMut, IPtrOwned, IStable};

pub use stable_waker::StableWaker;
#[cfg(unsafe_wakers = "true")]
mod stable_waker {
    use core::task::Waker;

    use crate::StableLike;
    /// A waker that promises to be ABI stable.
    ///
    /// With the `unsafe_wakers` feature enabled, this is actually a lie: the waker is not guaranteed to
    /// be ABI-stable! However, since building ABI-stable wakers that are compatible with Rust's wakers is
    /// costly in terms of runtime, you might want to experiment with unsafe wakers, to bench the cost of
    /// stable wakers if nothing else.
    #[crate::stabby]
    pub struct StableWaker<'a>(StableLike<&'a Waker, &'a ()>);
    impl StableWaker<'_> {
        /// Exposes `self` as a [`core::task::Waker`], letting you use it to run standard futures.
        ///
        /// You generally shouldn't need to do this manually.
        pub fn with_waker<'a, F: FnOnce(&'a Waker) -> U, U>(&'a self, f: F) -> U {
            f(unsafe { self.0.as_ref_unchecked() })
        }
    }
    impl<'a> From<&'a Waker> for StableWaker<'a> {
        fn from(value: &'a Waker) -> Self {
            Self(StableLike::new(value))
        }
    }
}
#[cfg(any(not(unsafe_wakers), unsafe_wakers = "false"))]
mod stable_waker {
    use core::{
        mem::ManuallyDrop,
        ptr::NonNull,
        task::{RawWaker, RawWakerVTable, Waker},
    };

    use crate::alloc::{sync::Arc, AllocPtr, IAlloc};
    use crate::StableLike;

    mod seal {
        use super::*;
        use crate::Tuple as Tuple2;
        #[crate::stabby]
        pub struct StableWakerInner {
            pub waker: StableLike<ManuallyDrop<Waker>, Tuple2<*const (), &'static ()>>,
            pub wake_by_ref: StableLike<for<'b> unsafe extern "C" fn(&'b Waker), &'static ()>,
            pub drop: StableLike<unsafe extern "C" fn(&mut ManuallyDrop<Waker>), &'static ()>,
        }
        unsafe impl Send for StableWakerInner {}
        unsafe impl Sync for StableWakerInner {}
        impl Drop for StableWakerInner {
            fn drop(&mut self) {
                unsafe { (self.drop.as_mut_unchecked())(self.waker.as_mut_unchecked()) }
            }
        }
        #[crate::stabby]
        pub struct SharedStableWaker<Alloc: IAlloc>(pub Arc<StableWakerInner, Alloc>);
        impl<Alloc: IAlloc> SharedStableWaker<Alloc> {
            unsafe fn clone(this: *const ()) -> RawWaker {
                Arc::<_, Alloc>::increment_strong_count(this);
                RawWaker::new(this, &Self::VTABLE)
            }
            unsafe fn drop(this: *const ()) {
                let this = AllocPtr {
                    ptr: NonNull::new(this as *mut _).unwrap(),
                    marker: core::marker::PhantomData,
                };
                let this = Arc::from_raw(this);
                Self(this);
            }
            unsafe fn wake(this: *const ()) {
                Self::wake_by_ref(this);
                Self::drop(this);
            }
            unsafe fn wake_by_ref(this: *const ()) {
                let this = unsafe { &*(this as *const StableWakerInner) };
                (this.wake_by_ref.as_ref_unchecked())(this.waker.as_ref_unchecked())
            }
            const VTABLE: RawWakerVTable =
                RawWakerVTable::new(Self::clone, Self::wake, Self::wake_by_ref, Self::drop);
            pub fn into_raw_waker(self) -> RawWaker {
                RawWaker::new(
                    Arc::into_raw(self.0).ptr.as_ptr() as *const _,
                    &Self::VTABLE,
                )
            }
        }
    }
    use seal::*;
    /// An ABI-stable waker.
    ///
    /// This is done by wrapping a provided [`core::task::Waker`] with calling convention-shims.
    ///
    /// While this is the only way to guarantee ABI-stability when interacting with futures, this does add
    /// a layer of indirection, and cloning this waker will cause an allocation. To bench the performance cost
    /// of this wrapper and decide if you want to risk ABI-unstability on wakers, you may use `RUST_FLAGS='--cfg unsafe_wakers="true"'`, which will turn [`StableWaker`] into a newtype of [`core::task::Waker`].
    #[crate::stabby]
    pub struct StableWaker<'a, Alloc: IAlloc = crate::alloc::DefaultAllocator> {
        waker: StableLike<&'a Waker, &'a ()>,
        #[allow(improper_ctypes_definitions)]
        clone: unsafe extern "C" fn(StableLike<&'a Waker, &'a ()>) -> SharedStableWaker<Alloc>,
        wake_by_ref: StableLike<unsafe extern "C" fn(&Waker), &'a ()>,
    }
    impl<'a, Alloc: IAlloc + Default> StableWaker<'a, Alloc> {
        /// Turns this into a waker whose clone implementation is to clone the underlying waker into a stable Arc.
        pub fn with_waker<F: FnOnce(&Waker) -> U, U>(&self, f: F) -> U {
            const VTABLE: RawWakerVTable =
                RawWakerVTable::new(clone, wake_by_ref, wake_by_ref, drop);
            unsafe fn clone(this: *const ()) -> RawWaker {
                let this = unsafe { &*(this as *const StableWaker) };
                (this.clone)(this.waker).into_raw_waker()
            }
            unsafe fn wake_by_ref(this: *const ()) {
                let this = unsafe { &*(this as *const StableWaker) };
                (this.wake_by_ref.as_ref_unchecked())(this.waker.as_ref_unchecked())
            }
            const unsafe fn drop(_: *const ()) {}
            let waker = RawWaker::new(self as *const Self as *const _, &VTABLE);
            let waker = unsafe { Waker::from_raw(waker) };
            f(&waker)
        }
        unsafe extern "C" fn waker_drop(waker: &mut ManuallyDrop<Waker>) {
            ManuallyDrop::drop(waker)
        }
        unsafe extern "C" fn waker_wake_by_ref(waker: &Waker) {
            waker.wake_by_ref()
        }
        unsafe extern "C" fn clone_borrowed(
            borrowed_waker: StableLike<&Waker, &()>,
        ) -> SharedStableWaker<Alloc> {
            let borrowed_waker = *borrowed_waker.as_ref_unchecked();
            let waker = borrowed_waker.clone();
            let waker = StableWakerInner {
                waker: StableLike::new(ManuallyDrop::new(waker)),
                wake_by_ref: StableLike::new(Self::waker_wake_by_ref),
                drop: StableLike::new(Self::waker_drop),
            };
            let shared = Arc::new_in(waker, Default::default());
            SharedStableWaker(shared)
        }
    }
    impl<'a, Alloc: IAlloc + Default> From<&'a Waker> for StableWaker<'a, Alloc> {
        fn from(value: &'a Waker) -> Self {
            StableWaker {
                waker: StableLike::new(value),
                clone: Self::clone_borrowed,
                wake_by_ref: StableLike::new(Self::waker_wake_by_ref),
            }
        }
    }
}

/// [`core::future::Future`], but ABI-stable.
#[crate::stabby]
pub trait Future {
    /// The output type of the future.
    type Output: IDeterminantProvider<()>;
    /// Equivalent to [`core::future::Future::poll`].
    extern "C" fn poll<'a>(&'a mut self, waker: StableWaker<'a>) -> Option<Self::Output>;
}
impl<T: core::future::Future> Future for T
where
    T::Output: IDeterminantProvider<()>,
{
    type Output = T::Output;
    #[allow(improper_ctypes_definitions)]
    extern "C" fn poll(&mut self, waker: StableWaker) -> Option<Self::Output> {
        waker.with_waker(|waker| {
            match core::future::Future::poll(
                unsafe { core::pin::Pin::new_unchecked(self) },
                &mut Context::from_waker(waker),
            ) {
                core::task::Poll::Ready(v) => Option::Some(v),
                core::task::Poll::Pending => Option::None(),
            }
        })
    }
}

impl<'a, Vt: HasDropVt, P: IPtrOwned + IPtrMut, Output: IDeterminantProvider<()>>
    core::future::Future
    for crate::Dyn<'a, P, crate::vtable::VTable<StabbyVtableFuture<Output>, Vt>>
{
    type Output = Output;
    fn poll(
        self: core::pin::Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> core::task::Poll<Self::Output> {
        unsafe {
            let this = core::pin::Pin::get_unchecked_mut(self);
            (this.vtable().head.poll.as_ref_unchecked())(this.ptr_mut().as_mut(), cx.waker().into())
                .match_owned(|v| core::task::Poll::Ready(v), || core::task::Poll::Pending)
        }
    }
}

impl<'a, Vt: HasDropVt, P: IPtrOwned + IPtrMut, Output: IDeterminantProvider<()>>
    core::future::Future
    for crate::Dyn<
        'a,
        P,
        crate::vtable::VtSend<crate::vtable::VTable<StabbyVtableFuture<Output>, Vt>>,
    >
{
    type Output = Output;
    fn poll(
        self: core::pin::Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> core::task::Poll<Self::Output> {
        unsafe {
            let this = core::pin::Pin::get_unchecked_mut(self);
            (this.vtable().0.head.poll.as_ref_unchecked())(
                this.ptr_mut().as_mut(),
                cx.waker().into(),
            )
            .match_owned(|v| core::task::Poll::Ready(v), || core::task::Poll::Pending)
        }
    }
}

impl<'a, Vt: HasDropVt, P: IPtrOwned + IPtrMut, Output: IDeterminantProvider<()>>
    core::future::Future
    for crate::Dyn<
        'a,
        P,
        crate::vtable::VtSync<crate::vtable::VTable<StabbyVtableFuture<Output>, Vt>>,
    >
{
    type Output = Output;
    fn poll(
        self: core::pin::Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> core::task::Poll<Self::Output> {
        unsafe {
            let this = core::pin::Pin::get_unchecked_mut(self);
            (this.vtable().0.head.poll.as_ref_unchecked())(
                this.ptr_mut().as_mut(),
                cx.waker().into(),
            )
            .match_owned(|v| core::task::Poll::Ready(v), || core::task::Poll::Pending)
        }
    }
}

impl<'a, Vt: HasDropVt, P: IPtrOwned + IPtrMut, Output: IDeterminantProvider<()>>
    core::future::Future
    for crate::Dyn<
        'a,
        P,
        crate::vtable::VtSync<
            crate::vtable::VtSend<crate::vtable::VTable<StabbyVtableFuture<Output>, Vt>>,
        >,
    >
{
    type Output = Output;
    fn poll(
        self: core::pin::Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> core::task::Poll<Self::Output> {
        unsafe {
            let this = core::pin::Pin::get_unchecked_mut(self);
            (this.vtable().0 .0.head.poll.as_ref_unchecked())(
                this.ptr_mut().as_mut(),
                cx.waker().into(),
            )
            .match_owned(|v| core::task::Poll::Ready(v), || core::task::Poll::Pending)
        }
    }
}

impl<'a, Vt: HasDropVt, P: IPtrOwned + IPtrMut, Output: IDeterminantProvider<()>>
    core::future::Future
    for crate::Dyn<
        'a,
        P,
        crate::vtable::VtSend<
            crate::vtable::VtSync<crate::vtable::VTable<StabbyVtableFuture<Output>, Vt>>,
        >,
    >
{
    type Output = Output;
    fn poll(
        self: core::pin::Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> core::task::Poll<Self::Output> {
        unsafe {
            let this = core::pin::Pin::get_unchecked_mut(self);
            (this.vtable().0 .0.head.poll.as_ref_unchecked())(
                this.ptr_mut().as_mut(),
                cx.waker().into(),
            )
            .match_owned(|v| core::task::Poll::Ready(v), || core::task::Poll::Pending)
        }
    }
}

impl<Output> crate::vtable::CompoundVt for dyn core::future::Future<Output = Output>
where
    dyn Future<Output = Output>: crate::vtable::CompoundVt,
{
    type Vt<T> = <dyn Future<Output = Output> as crate::vtable::CompoundVt>::Vt<T>;
}

/// A future that may have already been resolved from the moment it was constructed.
#[crate::stabby]
pub enum MaybeResolved<T, F>
where
    F: core::future::Future<Output = T>,
{
    /// The future was resolved from its construction.
    Resolved(T),
    /// The future has been consumed already.
    Empty,
    /// The future is yet to be resolved.
    Pending(F),
}
impl<T: IStable + Unpin, F: IStable + core::future::Future<Output = T> + Unpin> core::future::Future
    for MaybeResolved<T, F>
where
    F: crate::IStable,
    crate::Result<(), F>: crate::IStable,
    T: crate::IDeterminantProvider<crate::Result<(), F>>,
    (): crate::IDeterminantProvider<F>,
{
    type Output = T;
    fn poll(
        self: core::pin::Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> core::task::Poll<Self::Output> {
        let this = self.get_mut();
        let inner = this as *mut _;
        this.match_mut(
            |value| {
                let value = unsafe {
                    let value = core::ptr::read(value);
                    core::ptr::write(inner, MaybeResolved::Empty());
                    value
                };
                core::task::Poll::Ready(value)
            },
            || core::task::Poll::Pending,
            |future| match core::future::Future::poll(core::pin::Pin::new(future), cx) {
                core::task::Poll::Ready(value) => {
                    unsafe {
                        core::ptr::replace(inner, MaybeResolved::Empty());
                    }
                    core::task::Poll::Ready(value)
                }
                core::task::Poll::Pending => core::task::Poll::Pending,
            },
        )
    }
}