xabi 0.1.2

Generate stable native ABI glue from Rust traits
Documentation
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
use std::ffi::c_void;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};

use crate::{
    ABI_VERSION, ERR_EXPORT, ERR_INVALID_ARGUMENT, ERR_PANIC, Error, OK, POLL_PENDING, POLL_READY,
    Result, XabiCallError, XabiOwnedBytes, XabiOwnedBytesOwner, XabiResult, XabiType,
    catch_unwind_code, validate_abi_version, validate_size,
};

/// Waker handle passed into the xabi future poll ABI.
///
/// `XabiWaker` mirrors Rust's [`Waker`] behavior with C ABI function pointers.
/// Hosts usually construct it with [`XabiWaker::from_waker_ref`]; plugins turn
/// it back into a Rust waker with [`XabiWaker::to_waker`].
#[repr(C)]
#[derive(Clone, Copy)]
pub struct XabiWaker {
    /// Size of this structure in bytes.
    pub size: usize,
    /// ABI version for this structure.
    pub abi_version: u32,
    /// Opaque waker state pointer.
    pub instance: *mut c_void,
    /// Clone the waker state and return an owned `XabiWaker`.
    pub clone: unsafe extern "C" fn(*mut c_void) -> XabiWaker,
    /// Wake and consume an owned waker state.
    pub wake: unsafe extern "C" fn(*mut c_void),
    /// Wake without consuming the waker state.
    pub wake_by_ref: unsafe extern "C" fn(*mut c_void),
    /// Release an owned waker state.
    pub release: unsafe extern "C" fn(*mut c_void),
}

// The ABI waker is an opaque handle around Rust's `Waker`, which is `Send + Sync`.
// Exporters that construct custom wakers must uphold the same contract.
unsafe impl Send for XabiWaker {}
unsafe impl Sync for XabiWaker {}

impl XabiWaker {
    /// ABI version expected by this structure.
    pub const ABI_VERSION: u32 = ABI_VERSION;
    /// Minimum required size for the current waker representation.
    pub const MIN_SIZE: usize = std::mem::offset_of!(XabiWaker, release)
        + std::mem::size_of::<unsafe extern "C" fn(*mut c_void)>();
    /// Full size of this waker representation.
    pub const FULL_SIZE: usize = std::mem::size_of::<Self>();

    /// Validate the waker layout and required fields.
    ///
    /// ```
    /// unsafe extern "C" fn clone(_: *mut std::ffi::c_void) -> xabi::XabiWaker {
    ///     unreachable!()
    /// }
    ///
    /// unsafe extern "C" fn noop(_: *mut std::ffi::c_void) {}
    ///
    /// let waker = xabi::XabiWaker {
    ///     size: 0,
    ///     abi_version: xabi::XabiWaker::ABI_VERSION,
    ///     instance: std::ptr::null_mut(),
    ///     clone,
    ///     wake: noop,
    ///     wake_by_ref: noop,
    ///     release: noop,
    /// };
    /// assert!(waker.validate().is_err());
    /// ```
    pub fn validate(&self) -> Result<()> {
        validate_size(self.size, Self::MIN_SIZE, "XabiWaker")?;
        validate_abi_version(self.abi_version, Self::ABI_VERSION, "XabiWaker")?;
        if self.instance.is_null() {
            return Err(Error::NullPointer("XabiWaker::instance"));
        }
        Ok(())
    }

    /// Borrow a Rust [`Waker`] as an ABI waker for one poll call.
    ///
    /// ```
    /// use std::sync::Arc;
    /// use std::task::{Wake, Waker};
    ///
    /// struct Noop;
    /// impl Wake for Noop {
    ///     fn wake(self: Arc<Self>) {}
    /// }
    ///
    /// let rust_waker = Waker::from(Arc::new(Noop));
    /// let waker = xabi::XabiWaker::from_waker_ref(&rust_waker);
    /// waker.validate().unwrap();
    /// ```
    pub fn from_waker_ref(waker: &Waker) -> Self {
        Self {
            size: std::mem::size_of::<Self>(),
            abi_version: ABI_VERSION,
            instance: waker as *const Waker as *mut c_void,
            clone: clone_borrowed_waker,
            wake: wake_borrowed_waker,
            wake_by_ref: wake_borrowed_waker,
            release: release_borrowed_waker,
        }
    }

    /// Convert this ABI waker into an owned Rust [`Waker`].
    ///
    /// # Safety
    ///
    /// The waker must follow the xabi waker ownership contract. The returned Rust
    /// waker owns a cloned xabi waker and will release it when dropped.
    pub unsafe fn to_waker(&self) -> Result<Waker> {
        self.validate()?;
        let owned = unsafe { (self.clone)(self.instance) };
        owned.validate()?;
        let boxed = Box::new(owned);
        let raw = RawWaker::new(Box::into_raw(boxed) as *const (), &XABI_WAKER_VTABLE);
        Ok(unsafe { Waker::from_raw(raw) })
    }
}

unsafe extern "C" fn clone_borrowed_waker(instance: *mut c_void) -> XabiWaker {
    let waker = unsafe { &*(instance as *const Waker) };
    let owned = Box::new(waker.clone());
    XabiWaker {
        size: std::mem::size_of::<XabiWaker>(),
        abi_version: ABI_VERSION,
        instance: Box::into_raw(owned) as *mut c_void,
        clone: clone_owned_waker,
        wake: wake_owned_waker,
        wake_by_ref: wake_by_ref_owned_waker,
        release: release_owned_waker,
    }
}

unsafe extern "C" fn wake_borrowed_waker(instance: *mut c_void) {
    let waker = unsafe { &*(instance as *const Waker) };
    waker.wake_by_ref();
}

unsafe extern "C" fn release_borrowed_waker(_instance: *mut c_void) {}

unsafe extern "C" fn clone_owned_waker(instance: *mut c_void) -> XabiWaker {
    let waker = unsafe { &*(instance as *const Waker) };
    let owned = Box::new(waker.clone());
    XabiWaker {
        size: std::mem::size_of::<XabiWaker>(),
        abi_version: ABI_VERSION,
        instance: Box::into_raw(owned) as *mut c_void,
        clone: clone_owned_waker,
        wake: wake_owned_waker,
        wake_by_ref: wake_by_ref_owned_waker,
        release: release_owned_waker,
    }
}

unsafe extern "C" fn wake_owned_waker(instance: *mut c_void) {
    let waker = unsafe { &*(instance as *const Waker) };
    waker.wake_by_ref();
}

unsafe extern "C" fn wake_by_ref_owned_waker(instance: *mut c_void) {
    let waker = unsafe { &*(instance as *const Waker) };
    waker.wake_by_ref();
}

unsafe extern "C" fn release_owned_waker(instance: *mut c_void) {
    if !instance.is_null() {
        drop(unsafe { Box::from_raw(instance as *mut Waker) });
    }
}

static XABI_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(
    raw_waker_clone,
    raw_waker_wake,
    raw_waker_wake_by_ref,
    raw_waker_drop,
);

unsafe fn raw_waker_clone(data: *const ()) -> RawWaker {
    let waker = unsafe { &*(data as *const XabiWaker) };
    let cloned = unsafe { (waker.clone)(waker.instance) };
    RawWaker::new(
        Box::into_raw(Box::new(cloned)) as *const (),
        &XABI_WAKER_VTABLE,
    )
}

unsafe fn raw_waker_wake(data: *const ()) {
    let waker = unsafe { Box::from_raw(data as *mut XabiWaker) };
    unsafe {
        (waker.wake)(waker.instance);
        (waker.release)(waker.instance);
    }
}

unsafe fn raw_waker_wake_by_ref(data: *const ()) {
    let waker = unsafe { &*(data as *const XabiWaker) };
    unsafe { (waker.wake_by_ref)(waker.instance) };
}

unsafe fn raw_waker_drop(data: *const ()) {
    let waker = unsafe { Box::from_raw(data as *mut XabiWaker) };
    unsafe { (waker.release)(waker.instance) };
}

/// Future handle returned by async xabi vtable methods.
///
/// Hosts poll this handle through [`XabiFutureHandle`]. Exporters can construct a
/// handle from a Rust future with [`XabiFuture::from_result_bytes`].
#[repr(C)]
pub struct XabiFuture {
    /// Size of this structure in bytes.
    pub size: usize,
    /// ABI version for this structure.
    pub abi_version: u32,
    /// Opaque future state pointer.
    pub instance: *mut c_void,
    /// Poll the future.
    pub poll: unsafe extern "C" fn(*mut c_void, *const XabiWaker, *mut XabiResult) -> i32,
    /// Release the future state.
    pub release: unsafe extern "C" fn(*mut c_void),
}

// The async ABI allows hosts to move foreign futures across executor threads.
// `from_result_bytes` enforces `Send` for Rust futures created by xabi.
unsafe impl Send for XabiFuture {}

impl XabiFuture {
    /// ABI version expected by this structure.
    pub const ABI_VERSION: u32 = ABI_VERSION;
    /// Minimum required size for the current future representation.
    pub const MIN_SIZE: usize = std::mem::offset_of!(XabiFuture, release)
        + std::mem::size_of::<unsafe extern "C" fn(*mut c_void)>();
    /// Full size of this future representation.
    pub const FULL_SIZE: usize = std::mem::size_of::<Self>();

    /// Create an empty invalid future placeholder.
    ///
    /// ```
    /// let future = xabi::XabiFuture::empty();
    /// assert!(future.validate().is_err());
    /// ```
    pub fn empty() -> Self {
        Self {
            size: std::mem::size_of::<Self>(),
            abi_version: ABI_VERSION,
            instance: std::ptr::null_mut(),
            poll: poll_missing_future,
            release: release_missing_future,
        }
    }

    /// Validate the future layout and required fields.
    ///
    /// ```
    /// let future = xabi::XabiFuture::from_result_bytes(async {
    ///     Ok::<_, xabi::Error>(b"ready".to_vec())
    /// });
    /// future.validate().unwrap();
    /// unsafe { (future.release)(future.instance) };
    /// ```
    pub fn validate(&self) -> Result<()> {
        validate_size(self.size, Self::MIN_SIZE, "XabiFuture")?;
        validate_abi_version(self.abi_version, Self::ABI_VERSION, "XabiFuture")?;
        if self.instance.is_null() {
            return Err(Error::NullPointer("XabiFuture::instance"));
        }
        Ok(())
    }

    /// Convert a Rust future returning bytes into an xabi future handle.
    ///
    /// The future must be `Send` so host executors may move the foreign future
    /// between worker threads.
    ///
    /// ```
    /// use std::future::Future;
    /// use std::pin::pin;
    /// use std::sync::Arc;
    /// use std::task::{Context, Poll, Wake, Waker};
    ///
    /// struct Noop;
    /// impl Wake for Noop {
    ///     fn wake(self: Arc<Self>) {}
    /// }
    ///
    /// let future = xabi::XabiFuture::from_result_bytes(async {
    ///     Ok::<_, xabi::Error>(b"hello".to_vec())
    /// });
    /// let mut future = pin!(xabi::XabiFutureHandle::new(future).unwrap());
    /// let waker = Waker::from(Arc::new(Noop));
    /// let mut cx = Context::from_waker(&waker);
    ///
    /// match Future::poll(future.as_mut(), &mut cx) {
    ///     Poll::Ready(Ok(bytes)) => assert_eq!(bytes, b"hello"),
    ///     other => panic!("unexpected poll result: {other:?}"),
    /// }
    /// ```
    pub fn from_result_bytes<F, E>(future: F) -> Self
    where
        F: Future<Output = std::result::Result<Vec<u8>, E>> + Send + 'static,
        E: XabiType + 'static,
    {
        let state = Box::new(XabiFutureState {
            future: Some(Box::pin(future)),
        });
        Self {
            size: std::mem::size_of::<Self>(),
            abi_version: ABI_VERSION,
            instance: Box::into_raw(state) as *mut c_void,
            poll: poll_result_bytes_future::<F, E>,
            release: release_result_bytes_future::<F, E>,
        }
    }

    /// Convert a Rust future returning an xabi value into an ABI future handle.
    ///
    /// The success value is encoded with [`XabiType::into_payload`].
    pub fn from_result_value<F, T, E>(future: F) -> Self
    where
        F: Future<Output = std::result::Result<T, E>> + Send + 'static,
        T: XabiType + 'static,
        E: XabiType + 'static,
    {
        let state = Box::new(XabiFutureState {
            future: Some(Box::pin(future)),
        });
        Self {
            size: std::mem::size_of::<Self>(),
            abi_version: ABI_VERSION,
            instance: Box::into_raw(state) as *mut c_void,
            poll: poll_result_value_future::<F, T, E>,
            release: release_result_value_future::<F, T, E>,
        }
    }
}

unsafe extern "C" fn poll_missing_future(
    _instance: *mut c_void,
    _waker: *const XabiWaker,
    _out: *mut XabiResult,
) -> i32 {
    ERR_INVALID_ARGUMENT
}

unsafe extern "C" fn release_missing_future(_instance: *mut c_void) {}

struct XabiFutureState<F> {
    future: Option<Pin<Box<F>>>,
}

unsafe extern "C" fn poll_result_bytes_future<F, E>(
    instance: *mut c_void,
    waker: *const XabiWaker,
    out: *mut XabiResult,
) -> i32
where
    F: Future<Output = std::result::Result<Vec<u8>, E>> + Send + 'static,
    E: XabiType + 'static,
{
    catch_unwind_code(|| {
        let Some(state) = (unsafe { (instance as *mut XabiFutureState<F>).as_mut() }) else {
            return ERR_INVALID_ARGUMENT;
        };
        let Some(out) = (unsafe { out.as_mut() }) else {
            return ERR_INVALID_ARGUMENT;
        };
        let Some(waker) = (unsafe { waker.as_ref() }) else {
            return ERR_INVALID_ARGUMENT;
        };
        let rust_waker = match unsafe { waker.to_waker() } {
            Ok(waker) => waker,
            Err(_) => return ERR_INVALID_ARGUMENT,
        };
        let mut cx = Context::from_waker(&rust_waker);
        let Some(future) = state.future.as_mut() else {
            return ERR_INVALID_ARGUMENT;
        };

        match future.as_mut().poll(&mut cx) {
            Poll::Pending => POLL_PENDING,
            Poll::Ready(Ok(bytes)) => {
                state.future = None;
                *out = XabiResult::ok(XabiOwnedBytes::from_vec(bytes));
                POLL_READY
            }
            Poll::Ready(Err(err)) => {
                state.future = None;
                *out = XabiResult {
                    code: ERR_EXPORT,
                    payload: err.into_payload(),
                };
                POLL_READY
            }
        }
    })
}

unsafe extern "C" fn release_result_bytes_future<F, E>(instance: *mut c_void)
where
    F: Future<Output = std::result::Result<Vec<u8>, E>> + Send + 'static,
    E: XabiType + 'static,
{
    if !instance.is_null() {
        drop(unsafe { Box::from_raw(instance as *mut XabiFutureState<F>) });
    }
}

unsafe extern "C" fn poll_result_value_future<F, T, E>(
    instance: *mut c_void,
    waker: *const XabiWaker,
    out: *mut XabiResult,
) -> i32
where
    F: Future<Output = std::result::Result<T, E>> + Send + 'static,
    T: XabiType + 'static,
    E: XabiType + 'static,
{
    catch_unwind_code(|| {
        let Some(state) = (unsafe { (instance as *mut XabiFutureState<F>).as_mut() }) else {
            return ERR_INVALID_ARGUMENT;
        };
        let Some(out) = (unsafe { out.as_mut() }) else {
            return ERR_INVALID_ARGUMENT;
        };
        let Some(waker) = (unsafe { waker.as_ref() }) else {
            return ERR_INVALID_ARGUMENT;
        };
        let rust_waker = match unsafe { waker.to_waker() } {
            Ok(waker) => waker,
            Err(_) => return ERR_INVALID_ARGUMENT,
        };
        let mut cx = Context::from_waker(&rust_waker);
        let Some(future) = state.future.as_mut() else {
            return ERR_INVALID_ARGUMENT;
        };

        match future.as_mut().poll(&mut cx) {
            Poll::Pending => POLL_PENDING,
            Poll::Ready(Ok(value)) => {
                state.future = None;
                *out = XabiResult::ok(value.into_payload());
                POLL_READY
            }
            Poll::Ready(Err(err)) => {
                state.future = None;
                *out = XabiResult {
                    code: ERR_EXPORT,
                    payload: err.into_payload(),
                };
                POLL_READY
            }
        }
    })
}

unsafe extern "C" fn release_result_value_future<F, T, E>(instance: *mut c_void)
where
    F: Future<Output = std::result::Result<T, E>> + Send + 'static,
    T: XabiType + 'static,
    E: XabiType + 'static,
{
    if !instance.is_null() {
        drop(unsafe { Box::from_raw(instance as *mut XabiFutureState<F>) });
    }
}

/// Rust [`Future`] wrapper around a foreign [`XabiFuture`].
///
/// ```
/// use std::future::Future;
/// use std::pin::pin;
/// use std::sync::Arc;
/// use std::task::{Context, Poll, Wake, Waker};
///
/// struct Noop;
/// impl Wake for Noop {
///     fn wake(self: Arc<Self>) {}
/// }
///
/// let future = xabi::XabiFuture::from_result_bytes(async {
///     Ok::<_, xabi::Error>(b"ok".to_vec())
/// });
/// let mut future = pin!(xabi::XabiFutureHandle::new(future).unwrap());
/// let waker = Waker::from(Arc::new(Noop));
/// let mut cx = Context::from_waker(&waker);
///
/// assert!(matches!(
///     Future::poll(future.as_mut(), &mut cx),
///     Poll::Ready(Ok(bytes)) if bytes == b"ok"
/// ));
/// ```
pub struct XabiFutureHandle {
    future: XabiFuture,
}

/// Rust [`Future`] wrapper that decodes typed values and export errors.
///
/// `T` defaults to `Vec<u8>` for callers that need the original copying byte
/// conversion. Generated value-return paths set `T` to the declared
/// [`XabiType`] so ownership-aware values can be decoded without an intermediate
/// byte copy.
pub struct XabiTypedFuture<E, T = Vec<u8>> {
    future: XabiFuture,
    module: Option<std::sync::Arc<crate::ModuleHandle>>,
    _marker: std::marker::PhantomData<(E, T)>,
}

impl<E, T> Unpin for XabiTypedFuture<E, T> {}

impl<E, T> XabiTypedFuture<E, T> {
    /// Validate and wrap an [`XabiFuture`].
    pub fn new(future: XabiFuture) -> Result<Self> {
        future.validate()?;
        Ok(Self {
            future,
            module: None,
            _marker: std::marker::PhantomData,
        })
    }

    /// Validate and wrap an [`XabiFuture`] while retaining its producer module.
    #[doc(hidden)]
    pub fn new_with_module(
        future: XabiFuture,
        module: std::sync::Arc<crate::ModuleHandle>,
    ) -> Result<Self> {
        future.validate()?;
        Ok(Self {
            future,
            module: Some(module),
            _marker: std::marker::PhantomData,
        })
    }
}

impl<E, T> Future for XabiTypedFuture<E, T>
where
    E: XabiType,
    T: XabiType,
{
    type Output = std::result::Result<T, XabiCallError<E>>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        let waker = XabiWaker::from_waker_ref(cx.waker());
        let mut out = XabiResult::empty();
        let code = unsafe { (this.future.poll)(this.future.instance, &waker, &mut out) };
        match code {
            POLL_PENDING => {
                discard_owned_payload(out.payload);
                Poll::Pending
            }
            POLL_READY => {
                if out.code == OK {
                    Poll::Ready(match unsafe { T::from_payload(out.payload) } {
                        Ok(mut value) => {
                            if let Some(module) = &this.module {
                                T::retain_module(&mut value, module);
                            }
                            Ok(value)
                        }
                        Err(err) => Err(XabiCallError::Runtime(err)),
                    })
                } else if out.code == ERR_EXPORT {
                    Poll::Ready(match unsafe { E::from_payload(out.payload) } {
                        Ok(mut err) => {
                            if let Some(module) = &this.module {
                                E::retain_module(&mut err, module);
                            }
                            Err(XabiCallError::Export(err))
                        }
                        Err(err) => Err(XabiCallError::Runtime(err)),
                    })
                } else {
                    discard_owned_payload(out.payload);
                    Poll::Ready(Err(XabiCallError::Runtime(Error::Export(format!(
                        "future completed with xabi code {}",
                        out.code
                    )))))
                }
            }
            ERR_PANIC => {
                discard_owned_payload(out.payload);
                Poll::Ready(Err(XabiCallError::Runtime(Error::Export(
                    "future poll panicked across xabi boundary".to_string(),
                ))))
            }
            other => {
                discard_owned_payload(out.payload);
                Poll::Ready(Err(XabiCallError::Runtime(Error::Export(format!(
                    "future poll returned xabi code {other}"
                )))))
            }
        }
    }
}

impl<E, T> Drop for XabiTypedFuture<E, T> {
    fn drop(&mut self) {
        unsafe { (self.future.release)(self.future.instance) };
    }
}

impl XabiFutureHandle {
    /// Validate and wrap an [`XabiFuture`].
    ///
    /// ```
    /// let future = xabi::XabiFuture::empty();
    /// assert!(xabi::XabiFutureHandle::new(future).is_err());
    /// ```
    pub fn new(future: XabiFuture) -> Result<Self> {
        future.validate()?;
        Ok(Self { future })
    }
}

impl Future for XabiFutureHandle {
    type Output = Result<Vec<u8>>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        let waker = XabiWaker::from_waker_ref(cx.waker());
        let mut out = XabiResult::empty();
        let code = unsafe { (this.future.poll)(this.future.instance, &waker, &mut out) };
        match code {
            POLL_PENDING => {
                discard_owned_payload(out.payload);
                Poll::Pending
            }
            POLL_READY => {
                if out.code == OK {
                    Poll::Ready(unsafe { out.payload.to_vec_and_free() })
                } else {
                    Poll::Ready(match unsafe { Error::from_payload(out.payload) } {
                        Ok(err) => Err(err),
                        Err(err) => Err(err),
                    })
                }
            }
            ERR_PANIC => {
                discard_owned_payload(out.payload);
                Poll::Ready(Err(Error::Export(
                    "future poll panicked across xabi boundary".to_string(),
                )))
            }
            other => {
                discard_owned_payload(out.payload);
                Poll::Ready(Err(Error::Export(format!(
                    "future poll returned xabi code {other}"
                ))))
            }
        }
    }
}

impl Drop for XabiFutureHandle {
    fn drop(&mut self) {
        unsafe { (self.future.release)(self.future.instance) };
    }
}

fn discard_owned_payload(payload: XabiOwnedBytes) {
    drop(unsafe { XabiOwnedBytesOwner::from_raw(payload) });
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::future::Future;
    use std::sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    };
    use std::task::{Wake, Waker};

    struct CountingWaker(Arc<AtomicUsize>);

    impl Wake for CountingWaker {
        fn wake(self: Arc<Self>) {
            self.0.fetch_add(1, Ordering::SeqCst);
        }

        fn wake_by_ref(self: &Arc<Self>) {
            self.0.fetch_add(1, Ordering::SeqCst);
        }
    }

    fn context() -> (Arc<AtomicUsize>, Waker) {
        let count = Arc::new(AtomicUsize::new(0));
        let waker = Waker::from(Arc::new(CountingWaker(Arc::clone(&count))));
        (count, waker)
    }

    #[test]
    fn xabi_waker_roundtrips_to_rust_waker() {
        let (count, rust_waker) = context();
        let waker = XabiWaker::from_waker_ref(&rust_waker);
        let rust_waker = unsafe { waker.to_waker() }.unwrap();

        rust_waker.wake_by_ref();

        assert_eq!(count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn xabi_future_handle_returns_ready_bytes() {
        let future = XabiFuture::from_result_bytes(async { Ok::<_, Error>(b"ready".to_vec()) });
        let mut future = Box::pin(XabiFutureHandle::new(future).unwrap());
        let (_count, waker) = context();
        let mut cx = Context::from_waker(&waker);

        match Future::poll(future.as_mut(), &mut cx) {
            Poll::Ready(Ok(bytes)) => assert_eq!(bytes, b"ready"),
            other => panic!("unexpected poll result: {other:?}"),
        }
    }

    #[test]
    fn xabi_future_handle_returns_export_error_payload() {
        let future = XabiFuture::from_result_bytes(async {
            Err::<Vec<u8>, _>(Error::Export("failed".to_string()))
        });
        let mut future = Box::pin(XabiFutureHandle::new(future).unwrap());
        let (_count, waker) = context();
        let mut cx = Context::from_waker(&waker);

        match Future::poll(future.as_mut(), &mut cx) {
            Poll::Ready(Err(err)) => assert_eq!(err.to_string(), "failed"),
            other => panic!("unexpected poll result: {other:?}"),
        }
    }

    #[test]
    fn raw_future_poll_rejects_null_arguments() {
        let future = XabiFuture::from_result_bytes(async { Ok::<_, Error>(Vec::new()) });

        let code = unsafe {
            (future.poll)(
                future.instance,
                std::ptr::null(),
                std::ptr::null_mut::<XabiResult>(),
            )
        };
        unsafe { (future.release)(future.instance) };

        assert_eq!(code, ERR_INVALID_ARGUMENT);
    }
}