Skip to main content

ntex_service/
inline.rs

1//! Type-erased future with inline storage.
2//!
3//! [`InlineFuture`] hides a future's concrete type, like
4//! `Pin<Box<dyn Future<Output = T>>>`, but stores small futures in an inline
5//! slot of `WORDS` machine words instead of allocating. Futures that don't fit
6//! are boxed, and the box pointer is stored in the slot.
7//!
8//! # Example
9//!
10//! ```
11//! use ntex_service::dev::InlineFuture;
12//!
13//! fn double(value: u32) -> InlineFuture<'static, u32, 4> {
14//!     InlineFuture::new(async move { value * 2 })
15//! }
16//!
17//! # async fn example() {
18//! assert_eq!(double(21).await, 42);
19//! # }
20//! ```
21use std::marker::{PhantomData, PhantomPinned};
22use std::mem::{self, ManuallyDrop, MaybeUninit};
23use std::task::{Context, Poll};
24use std::{fmt, pin::Pin, ptr};
25
26/// Type-erased future stored inline when it fits into `WORDS` machine words.
27///
28/// A future is stored inline when its size is at most `max(WORDS, 1)` words
29/// and its alignment is at most the alignment of `usize`. Other futures are
30/// boxed. The slot always holds at least one word, so `WORDS = 0` boxes every
31/// future larger than a pointer.
32///
33/// The future and its output may borrow data for `'a`. Like
34/// `Pin<Box<dyn Future>>`, `InlineFuture` is neither `Send` nor `Sync`. Unlike
35/// a box, it is not `Unpin`; pin it before polling, for example with
36/// [`std::pin::pin!`] or by awaiting it.
37pub struct InlineFuture<'a, T, const WORDS: usize> {
38    vtable: &'a VTable<T>,
39    slot: MaybeUninit<Slot<WORDS>>,
40    _t: PhantomData<Pin<Box<dyn Future<Output = T> + 'a>>>,
41    _p: PhantomPinned,
42}
43
44/// Inline storage of at least one word, the boxed path stores a pointer.
45#[repr(C)]
46union Slot<const WORDS: usize> {
47    _words: [MaybeUninit<usize>; WORDS],
48    _ptr: *mut (),
49}
50
51struct VTable<T> {
52    poll: unsafe fn(*mut (), &mut Context<'_>) -> Poll<T>,
53    drop: unsafe fn(*mut ()),
54}
55
56impl<T> VTable<T> {
57    const EMPTY: Self = VTable {
58        poll: poll_empty::<T>,
59        drop: drop_empty,
60    };
61}
62
63unsafe fn poll_empty<T>(_: *mut (), _: &mut Context<'_>) -> Poll<T> {
64    panic!("`InlineFuture` polled while empty")
65}
66
67unsafe fn drop_empty(_: *mut ()) {}
68
69struct VTableOf<F>(PhantomData<F>);
70
71impl<F: Future> VTableOf<F> {
72    const VTABLE: VTable<F::Output> = VTable {
73        poll: poll_raw::<F>,
74        drop: drop_raw::<F>,
75    };
76}
77
78unsafe fn poll_raw<F: Future>(ptr: *mut (), cx: &mut Context<'_>) -> Poll<F::Output> {
79    // SAFETY: `ptr` points to an initialized `F` that is never moved out of
80    // the pinned `InlineFuture`.
81    unsafe { Pin::new_unchecked(&mut *ptr.cast::<F>()).poll(cx) }
82}
83
84unsafe fn drop_raw<F>(ptr: *mut ()) {
85    // SAFETY: `ptr` points to an initialized `F` that is dropped only once.
86    unsafe { ptr::drop_in_place(ptr.cast::<F>()) }
87}
88
89impl<'a, T, const WORDS: usize> InlineFuture<'a, T, WORDS> {
90    /// Erases the type of `fut`, storing it inline if it fits and boxing it
91    /// otherwise.
92    pub fn new<F>(fut: F) -> Self
93    where
94        F: Future<Output = T> + 'a,
95    {
96        Self::new_with(move || fut)
97    }
98
99    /// Erases the type of the future returned by `f`, storing it inline if it
100    /// fits and boxing it otherwise.
101    ///
102    /// Unlike [`new`](Self::new), the storage is prepared before `f` runs, so
103    /// the future can be built directly in place instead of on the stack and
104    /// then copied. This matters for large futures that are boxed.
105    ///
106    /// ```
107    /// use ntex_service::dev::InlineFuture;
108    ///
109    /// fn double(value: u32) -> InlineFuture<'static, u32, 0> {
110    ///     InlineFuture::new_with(|| async move { value * 2 })
111    /// }
112    /// ```
113    #[inline]
114    pub fn new_with<F>(f: impl FnOnce() -> F) -> Self
115    where
116        F: Future<Output = T> + 'a,
117    {
118        if Self::fits::<F>() {
119            // SAFETY: `F` fits into the slot
120            unsafe { Self::new_inline(f) }
121        } else {
122            let fut = Box::<F>::new_uninit();
123            // SAFETY: a box is a single pointer, the slot holds at least one
124            unsafe { Self::new_inline(|| Box::into_pin(Box::write(fut, f()))) }
125        }
126    }
127
128    /// Creates an empty placeholder, to be filled by [`set_with`](Self::set_with)
129    /// once pinned.
130    ///
131    /// Polling an empty future panics, dropping it does nothing.
132    #[inline]
133    #[must_use]
134    pub const fn empty() -> Self {
135        InlineFuture {
136            vtable: &VTable::EMPTY,
137            slot: MaybeUninit::uninit(),
138            _t: PhantomData,
139            _p: PhantomPinned,
140        }
141    }
142
143    /// Drops the stored future and replaces it with the future returned by
144    /// `f`, storing it inline if it fits and boxing it otherwise.
145    ///
146    /// The new future is built directly in the pinned storage, so a large
147    /// future is never copied. With [`empty`](Self::empty), this lets a callee
148    /// build its future in storage owned by the caller instead of returning
149    /// it by value.
150    ///
151    /// If dropping the previous future or calling `f` panics, the future is
152    /// left empty.
153    ///
154    /// ```
155    /// use std::pin::{Pin, pin};
156    /// use ntex_service::dev::InlineFuture;
157    ///
158    /// fn double(value: u32, fut: Pin<&mut InlineFuture<'static, u32, 4>>) {
159    ///     fut.set_with(|| async move { value * 2 });
160    /// }
161    ///
162    /// # async fn example() {
163    /// let mut fut = pin!(InlineFuture::empty());
164    /// double(21, fut.as_mut());
165    /// assert_eq!(fut.await, 42);
166    /// # }
167    /// ```
168    #[inline]
169    pub fn set_with<F>(self: Pin<&mut Self>, f: impl FnOnce() -> F)
170    where
171        F: Future<Output = T> + 'a,
172    {
173        // SAFETY: the stored future is dropped and replaced in place, it is
174        // never moved
175        let this = unsafe { self.get_unchecked_mut() };
176
177        // Stay empty until the new future is written, so a panic while dropping
178        // the previous one or in `f` leaves nothing to drop twice
179        let prev = mem::replace(&mut this.vtable, &VTable::EMPTY);
180        // SAFETY: the slot holds the future described by `prev`
181        unsafe { (prev.drop)((&raw mut this.slot).cast()) };
182
183        if Self::fits::<F>() {
184            // SAFETY: `F` fits into the slot, which holds no future
185            unsafe { this.write_inline(f) }
186        } else {
187            let fut = Box::<F>::new_uninit();
188            // SAFETY: a box is a single pointer, the slot holds at least one
189            unsafe { this.write_inline(|| Box::into_pin(Box::write(fut, f()))) }
190        }
191    }
192
193    /// # Safety
194    ///
195    /// `F` must fit into the slot, and the slot must not hold a future.
196    unsafe fn write_inline<F>(&mut self, f: impl FnOnce() -> F)
197    where
198        F: Future<Output = T> + 'a,
199    {
200        debug_assert!(Self::fits::<F>());
201
202        // SAFETY: the slot is large enough and aligned for `F`
203        unsafe { (&raw mut self.slot).cast::<F>().write(f()) };
204        self.vtable = &VTableOf::<F>::VTABLE;
205    }
206
207    /// Returns `true` if a future of type `F` is stored inline.
208    pub const fn fits<F>() -> bool {
209        size_of::<F>() <= size_of::<Slot<WORDS>>() && align_of::<F>() <= align_of::<Slot<WORDS>>()
210    }
211
212    /// # Safety
213    ///
214    /// `F` must fit into the slot.
215    unsafe fn new_inline<F>(f: impl FnOnce() -> F) -> Self
216    where
217        F: Future<Output = T> + 'a,
218    {
219        debug_assert!(Self::fits::<F>());
220
221        // Not dropped if `f` panics, the slot is still uninitialized
222        let mut this = ManuallyDrop::new(InlineFuture {
223            vtable: &VTableOf::<F>::VTABLE,
224            slot: MaybeUninit::uninit(),
225            _t: PhantomData,
226            _p: PhantomPinned,
227        });
228        // SAFETY: the slot is large enough and aligned for `F`
229        unsafe { this.slot.as_mut_ptr().cast::<F>().write(f()) };
230        ManuallyDrop::into_inner(this)
231    }
232}
233
234impl<T, const WORDS: usize> Future for InlineFuture<'_, T, WORDS> {
235    type Output = T;
236
237    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
238        // SAFETY: the inline future is pinned together with `self`.
239        // The slot is accessed through a raw pointer, a `&mut` to it would
240        // invalidate self-references of the stored future.
241        unsafe {
242            let this = self.get_unchecked_mut();
243            (this.vtable.poll)((&raw mut this.slot).cast(), cx)
244        }
245    }
246}
247
248impl<T, const WORDS: usize> Drop for InlineFuture<'_, T, WORDS> {
249    fn drop(&mut self) {
250        // SAFETY: the slot holds the future described by the vtable
251        unsafe { (self.vtable.drop)((&raw mut self.slot).cast()) }
252    }
253}
254
255impl<T, const WORDS: usize> fmt::Debug for InlineFuture<'_, T, WORDS> {
256    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257        f.debug_struct("InlineFuture").finish_non_exhaustive()
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use std::panic::{AssertUnwindSafe, catch_unwind};
264    use std::{cell::Cell, future::poll_fn, pin::pin, rc::Rc};
265
266    use super::*;
267
268    const WORDS: usize = 4;
269
270    type Fut<'a, T> = InlineFuture<'a, T, WORDS>;
271
272    struct DropGuard(Rc<Cell<usize>>);
273
274    impl Drop for DropGuard {
275        fn drop(&mut self) {
276            self.0.set(self.0.get() + 1);
277        }
278    }
279
280    fn fits_of<F: Future, const W: usize>(_: &F) -> bool {
281        InlineFuture::<'_, F::Output, W>::fits::<F>()
282    }
283
284    fn complete<T, const W: usize>(fut: InlineFuture<'_, T, W>) -> T {
285        let mut fut = pin!(fut);
286        let mut cx = Context::from_waker(std::task::Waker::noop());
287        loop {
288            if let Poll::Ready(res) = fut.as_mut().poll(&mut cx) {
289                return res;
290            }
291        }
292    }
293
294    async fn yield_once() {
295        let mut yielded = false;
296        poll_fn(|cx| {
297            if yielded {
298                Poll::Ready(())
299            } else {
300                yielded = true;
301                cx.waker().wake_by_ref();
302                Poll::Pending
303            }
304        })
305        .await;
306    }
307
308    /// Ready future of `N + 1` words that checks its padding when polled.
309    struct Padded<const N: usize> {
310        pad: [usize; N],
311        _guard: Option<DropGuard>,
312    }
313
314    impl<const N: usize> Padded<N> {
315        fn new(guard: Option<DropGuard>) -> Self {
316            Self {
317                pad: [N; N],
318                _guard: guard,
319            }
320        }
321    }
322
323    impl<const N: usize> Future for Padded<N> {
324        type Output = bool;
325
326        fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<bool> {
327            Poll::Ready(self.pad.iter().all(|w| *w == N))
328        }
329    }
330
331    /// Ready future that requires 16-byte alignment.
332    #[repr(align(16))]
333    struct Aligned(u8);
334
335    impl Future for Aligned {
336        type Output = bool;
337
338        fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<bool> {
339            Poll::Ready((&raw const *self).addr().is_multiple_of(16) && self.0 == 7)
340        }
341    }
342
343    /// STATEMENT: Inline and boxed futures resolve to their output after pending polls.
344    ///
345    /// HOW:
346    /// - Build an async block that fits the 4-word slot and one holding a 1 KiB buffer
347    ///   that does not.
348    /// - Poll both through `InlineFuture` with a no-op waker past one pending poll and
349    ///   check their outputs.
350    #[test]
351    fn inline_and_boxed_futures_resolve() {
352        let small = async {
353            yield_once().await;
354            1u32
355        };
356        assert!(fits_of::<_, WORDS>(&small));
357        assert_eq!(complete(Fut::new(small)), 1);
358
359        let large = async {
360            let buf = [7u8; 1024];
361            yield_once().await;
362            u32::from(buf[1023])
363        };
364        assert!(!fits_of::<_, WORDS>(&large));
365        assert_eq!(complete(Fut::new(large)), 7);
366    }
367
368    /// STATEMENT: Futures up to `WORDS` words are stored inline and larger ones are boxed.
369    ///
370    /// HOW:
371    /// - Check that a `WORDS`-word `Padded` future fits the slot and a `WORDS + 1`-word
372    ///   one does not.
373    /// - Resolve both through `InlineFuture` and check that each sees its padding intact.
374    #[test]
375    fn slot_size_boundary() {
376        assert_eq!(size_of::<Padded<3>>(), WORDS * size_of::<usize>());
377        assert!(Fut::<bool>::fits::<Padded<3>>());
378        assert!(!Fut::<bool>::fits::<Padded<4>>());
379
380        assert!(complete(Fut::new(Padded::<3>::new(None))));
381        assert!(complete(Fut::new(Padded::<4>::new(None))));
382    }
383
384    /// STATEMENT: A zero-word slot still holds one word, so only pointer-sized futures
385    /// stay inline.
386    ///
387    /// HOW:
388    /// - Check that `InlineFuture<_, 0>` is two words: the vtable and a one-word slot.
389    /// - Check that a one-word `Padded<0>` fits and a two-word `Padded<1>` does not.
390    /// - Resolve both and check that each sees its padding intact.
391    #[test]
392    fn zero_word_slot_holds_one_word() {
393        type Zero = InlineFuture<'static, bool, 0>;
394
395        assert_eq!(size_of::<Zero>(), 2 * size_of::<usize>());
396        assert!(Zero::fits::<Padded<0>>());
397        assert!(!Zero::fits::<Padded<1>>());
398
399        assert!(complete(Zero::new(Padded::<0>::new(None))));
400        assert!(complete(Zero::new(Padded::<1>::new(None))));
401    }
402
403    /// STATEMENT: Small futures aligned above `usize` are boxed rather than stored inline.
404    ///
405    /// HOW:
406    /// - Check that a 16-byte-aligned `Aligned` future, smaller than the slot, does not fit.
407    /// - Resolve it through `InlineFuture` and check that it was polled at an aligned
408    ///   address with its value intact.
409    #[test]
410    fn over_aligned_futures_are_boxed() {
411        assert!(size_of::<Aligned>() < WORDS * size_of::<usize>());
412        assert!(align_of::<Aligned>() > align_of::<usize>());
413        assert!(!Fut::<bool>::fits::<Aligned>());
414
415        assert!(complete(Fut::new(Aligned(7))));
416    }
417
418    /// STATEMENT: Dropping a pending or unpolled future runs its destructors exactly once.
419    ///
420    /// HOW:
421    /// - Capture a drop-counting guard in inline and boxed async blocks.
422    /// - Drop one of each unpolled and another after a pending poll.
423    /// - Check that the counter grows by one for every dropped future.
424    #[test]
425    fn dropping_runs_destructor_once() {
426        fn make(cnt: &Rc<Cell<usize>>, large: bool) -> Fut<'static, ()> {
427            let guard = DropGuard(cnt.clone());
428            if large {
429                let fut = async move {
430                    let buf = [0u8; 1024];
431                    yield_once().await;
432                    drop((guard, buf));
433                    unreachable!()
434                };
435                assert!(!fits_of::<_, WORDS>(&fut));
436                Fut::new(fut)
437            } else {
438                let fut = async move {
439                    yield_once().await;
440                    drop(guard);
441                    unreachable!()
442                };
443                assert!(fits_of::<_, WORDS>(&fut));
444                Fut::new(fut)
445            }
446        }
447
448        let cnt = Rc::new(Cell::new(0));
449        let mut cx = Context::from_waker(std::task::Waker::noop());
450
451        for (idx, large) in [false, true].into_iter().enumerate() {
452            drop(make(&cnt, large));
453            assert_eq!(cnt.get(), idx * 2 + 1);
454
455            let mut fut = Box::pin(make(&cnt, large));
456            assert!(fut.as_mut().poll(&mut cx).is_pending());
457            assert_eq!(cnt.get(), idx * 2 + 1);
458            drop(fut);
459            assert_eq!(cnt.get(), idx * 2 + 2);
460        }
461    }
462
463    /// STATEMENT: A completed future is dropped once, when the `InlineFuture` is dropped.
464    ///
465    /// HOW:
466    /// - Wrap inline and boxed `Padded` futures holding drop-counting guards.
467    /// - Poll each to `Ready` and check that its guard is still alive.
468    /// - Drop each `InlineFuture` and check that the counter grows by exactly one.
469    #[test]
470    fn dropping_after_ready_runs_destructor_once() {
471        let cnt = Rc::new(Cell::new(0));
472        let mut cx = Context::from_waker(std::task::Waker::noop());
473
474        let mut inline = Box::pin(Fut::new(Padded::<3>::new(Some(DropGuard(cnt.clone())))));
475        let mut boxed = Box::pin(Fut::new(Padded::<4>::new(Some(DropGuard(cnt.clone())))));
476        for fut in [&mut inline, &mut boxed] {
477            assert_eq!(fut.as_mut().poll(&mut cx), Poll::Ready(true));
478        }
479        assert_eq!(cnt.get(), 0);
480
481        drop(inline);
482        assert_eq!(cnt.get(), 1);
483        drop(boxed);
484        assert_eq!(cnt.get(), 2);
485    }
486
487    /// STATEMENT: A panic while `new_with` builds the future leaves no destructor
488    /// running on the uninitialized slot.
489    ///
490    /// HOW:
491    /// - Call `new_with` for an inline `Padded<3>` and a boxed `Padded<4>` with a closure
492    ///   that panics, inside `catch_unwind`.
493    /// - Check that the panic propagates; under Miri, a drop of the uninitialized slot
494    ///   is reported as UB.
495    #[test]
496    fn panic_in_new_with_drops_nothing() {
497        for large in [false, true] {
498            let res = std::panic::catch_unwind(|| {
499                if large {
500                    Fut::new_with(|| -> Padded<4> { panic!("build") })
501                } else {
502                    Fut::new_with(|| -> Padded<3> { panic!("build") })
503                }
504            });
505            assert!(res.is_err());
506        }
507    }
508
509    /// STATEMENT: `set_with` drops the stored future once and builds the new one in place.
510    ///
511    /// HOW:
512    /// - Pin an empty `InlineFuture`, `set_with` an inline future holding a drop-counting
513    ///   guard, and poll it to `Pending`.
514    /// - `set_with` a boxed future holding another guard and check that only the first
515    ///   guard was dropped.
516    /// - Poll the new future to its output, check that the second guard was dropped on
517    ///   completion, then drop the `InlineFuture` and check that nothing more is dropped.
518    #[test]
519    fn set_with_replaces_future_in_place() {
520        let cnt = Rc::new(Cell::new(0));
521        let mut cx = Context::from_waker(std::task::Waker::noop());
522        let mut fut = Box::pin(Fut::<u32>::empty());
523
524        let guard = DropGuard(cnt.clone());
525        fut.as_mut().set_with(|| async move {
526            yield_once().await;
527            drop(guard);
528            unreachable!()
529        });
530        assert!(fut.as_mut().poll(&mut cx).is_pending());
531        assert_eq!(cnt.get(), 0);
532
533        let guard = DropGuard(cnt.clone());
534        let large = async move {
535            let buf = [9u8; 1024];
536            yield_once().await;
537            let _guard = &guard;
538            u32::from(buf[1023])
539        };
540        assert!(!fits_of::<_, WORDS>(&large));
541        fut.as_mut().set_with(|| large);
542        assert_eq!(cnt.get(), 1);
543
544        assert!(fut.as_mut().poll(&mut cx).is_pending());
545        assert_eq!(fut.as_mut().poll(&mut cx), Poll::Ready(9));
546        assert_eq!(cnt.get(), 2);
547        drop(fut);
548        assert_eq!(cnt.get(), 2);
549    }
550
551    /// STATEMENT: A panic while `set_with` builds the future leaves an empty future, the
552    /// previous future is dropped once and polling panics.
553    ///
554    /// HOW:
555    /// - Store an inline `Padded<3>` future holding a drop-counting guard.
556    /// - Call `set_with` with a closure that panics while building an inline `Padded<3>`
557    ///   or a boxed `Padded<4>`, inside `catch_unwind`, and check the guard count is 1.
558    /// - Check that polling panics with the empty-future message and that dropping the
559    ///   `InlineFuture` drops nothing more.
560    #[test]
561    fn panic_in_set_with_leaves_empty_future() {
562        let mut cx = Context::from_waker(std::task::Waker::noop());
563
564        for large in [false, true] {
565            let cnt = Rc::new(Cell::new(0));
566            let mut fut = Box::pin(Fut::<bool>::empty());
567            fut.as_mut()
568                .set_with(|| Padded::<3>::new(Some(DropGuard(cnt.clone()))));
569
570            let res = catch_unwind(AssertUnwindSafe(|| {
571                if large {
572                    fut.as_mut().set_with(|| -> Padded<4> { panic!("build") });
573                } else {
574                    fut.as_mut().set_with(|| -> Padded<3> { panic!("build") });
575                }
576            }));
577            assert!(res.is_err());
578            assert_eq!(cnt.get(), 1);
579
580            let err = catch_unwind(AssertUnwindSafe(|| fut.as_mut().poll(&mut cx))).unwrap_err();
581            assert_eq!(
582                err.downcast_ref::<&str>(),
583                Some(&"`InlineFuture` polled while empty")
584            );
585            drop(fut);
586            assert_eq!(cnt.get(), 1);
587        }
588    }
589
590    /// STATEMENT: An inline future that borrows its own state stays valid across polls.
591    ///
592    /// HOW:
593    /// - Build an async block that keeps a reference to its local array across two
594    ///   pending polls, and check that it fits a 16-word slot.
595    /// - Pin it inside `InlineFuture`, resolve it, and check that reads through the
596    ///   reference see the array's values (run under Miri to detect invalidation).
597    #[test]
598    fn self_referential_future_stays_valid() {
599        let fut = async {
600            let data = [3u8, 4];
601            let r = &data;
602            yield_once().await;
603            let first = r[0];
604            yield_once().await;
605            u32::from(first) + u32::from(r[1])
606        };
607        assert!(fits_of::<_, 16>(&fut));
608        assert_eq!(complete(InlineFuture::<'_, u32, 16>::new(fut)), 7);
609    }
610
611    /// STATEMENT: Futures borrowing non-`'static` data can be erased.
612    ///
613    /// HOW:
614    /// - Erase inline and boxed async blocks that update a stack-local `Cell`
615    ///   across a pending poll.
616    /// - Resolve both and check their outputs and the `Cell` value.
617    #[test]
618    fn futures_borrowing_local_data() {
619        let cell = Cell::new(1u32);
620        let small: Fut<'_, u32> = Fut::new(async {
621            yield_once().await;
622            cell.set(cell.get() + 1);
623            cell.get()
624        });
625        let large: Fut<'_, u32> = Fut::new(async {
626            let buf = [5u8; 1024];
627            yield_once().await;
628            cell.set(cell.get() + u32::from(buf[1023]));
629            cell.get()
630        });
631
632        assert_eq!(complete(small), 2);
633        assert_eq!(complete(large), 7);
634        assert_eq!(cell.get(), 7);
635    }
636
637    /// STATEMENT: The output may borrow non-`'static` data.
638    ///
639    /// HOW:
640    /// - Erase inline and boxed async blocks whose output is a `&str` borrowed
641    ///   from a stack-local `String`, across a pending poll.
642    /// - Resolve both and check that the outputs point into that `String`.
643    #[test]
644    fn output_borrowing_local_data() {
645        let data = String::from("inline");
646        let small = async {
647            yield_once().await;
648            &data[..2]
649        };
650        let large = async {
651            let buf = [0u8; 1024];
652            yield_once().await;
653            &data[usize::from(buf[1023])..]
654        };
655        assert!(fits_of::<_, WORDS>(&small));
656        assert!(!fits_of::<_, WORDS>(&large));
657
658        assert_eq!(complete::<&str, WORDS>(Fut::new(small)), "in");
659        assert_eq!(
660            complete::<&str, WORDS>(Fut::new(large)).as_ptr(),
661            data.as_ptr()
662        );
663    }
664}