arena-alligator 0.1.0

Lock-free arena allocator producing bytes::Bytes via from_owner
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
use std::fmt;
use std::future::Future;
use std::ops::Deref;
use std::pin::Pin;
use std::ptr;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering};
use std::task::{Context, Poll};

use tokio::sync::futures::OwnedNotified;

use crate::buffer::Buffer;
use crate::{BuddyArena, FixedArena};

/// Policy for how `allocate_async` waits when the arena is full.
pub enum AsyncPolicy {
    /// Wake one waiter per slot free via `tokio::sync::Notify`.
    Notify,
    /// Lock-free LIFO waiter registry with per-waiter wake targeting.
    TreiberWaiters,
}

/// Wait strategy used by async arena allocation.
pub trait Waiter: Send + Sync + 'static {
    /// Future returned when a waiter registers interest in allocation progress.
    type Registration: WaitRegistration;

    /// Register a waiter before retrying allocation.
    fn register(&self) -> Self::Registration;

    /// Wake one waiter after allocation state changes.
    fn wake_one(&self);
}

/// Wait registration used by the shared retry loop.
pub trait WaitRegistration: Future<Output = ()> {
    /// Prepare the registration before the post-registration allocation retry.
    fn prepare(self: Pin<&mut Self>);

    /// Revoke the registration when the retry succeeds immediately.
    fn revoke(self: Pin<&mut Self>);
}

pub(crate) trait WakeOne: Send + Sync {
    fn wake_one(&self);
}

impl<W: Waiter> WakeOne for W {
    fn wake_one(&self) {
        Waiter::wake_one(self);
    }
}

pub(crate) struct WakeHandle {
    inner: Arc<dyn WakeOne>,
}

impl WakeHandle {
    pub(crate) fn new<W: Waiter>(waiters: Arc<W>) -> Self {
        let inner: Arc<dyn WakeOne> = waiters;
        Self { inner }
    }

    pub(crate) fn wake(&self) {
        self.inner.wake_one();
    }
}

/// Notify-based waiter policy.
#[derive(Clone, Default)]
pub struct NotifyWaiters {
    notify: Arc<tokio::sync::Notify>,
}

impl NotifyWaiters {
    /// Create a notify-based waiter policy.
    pub fn new() -> Self {
        Self {
            notify: Arc::new(tokio::sync::Notify::new()),
        }
    }
}

impl Waiter for NotifyWaiters {
    type Registration = NotifyRegistration;

    fn register(&self) -> Self::Registration {
        NotifyRegistration {
            future: self.notify.clone().notified_owned(),
        }
    }

    fn wake_one(&self) {
        self.notify.notify_one();
    }
}

pub struct NotifyRegistration {
    future: OwnedNotified,
}

impl WaitRegistration for NotifyRegistration {
    fn prepare(self: Pin<&mut Self>) {
        let _ = self.project_future().enable();
    }

    fn revoke(self: Pin<&mut Self>) {}
}

impl Future for NotifyRegistration {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.project_future().poll(cx)
    }
}

impl NotifyRegistration {
    fn project_future(self: Pin<&mut Self>) -> Pin<&mut OwnedNotified> {
        // SAFETY: pinning `NotifyRegistration` also pins its `future` field.
        unsafe { self.map_unchecked_mut(|this| &mut this.future) }
    }
}

struct WaiterNode {
    next: AtomicPtr<WaiterNode>,
    notify: Arc<tokio::sync::Notify>,
    revoked: AtomicBool,
}

struct TreiberStack {
    head: AtomicPtr<WaiterNode>,
}

// SAFETY: WaiterNode is behind Arc and only accessed through atomic operations.
// AtomicPtr and AtomicBool are Send+Sync; tokio::sync::Notify is Send+Sync.
unsafe impl Send for TreiberStack {}
unsafe impl Sync for TreiberStack {}

impl TreiberStack {
    fn new() -> Self {
        Self {
            head: AtomicPtr::new(ptr::null_mut()),
        }
    }

    /// Push a waiter node onto the stack.
    /// `raw` must come from `Arc::into_raw`.
    fn push(&self, raw: *const WaiterNode) {
        let node = raw as *mut WaiterNode;
        loop {
            let head = self.head.load(Ordering::Relaxed);
            // SAFETY: node is valid (Arc keeps it alive) and no concurrent writer
            // touches next until the node is linked into the stack via CAS.
            unsafe {
                (*node).next.store(head, Ordering::Relaxed);
            }
            if self
                .head
                .compare_exchange_weak(head, node, Ordering::Release, Ordering::Relaxed)
                .is_ok()
            {
                break;
            }
        }
    }

    /// Pop and wake the first non-revoked waiter. Skips tombstones.
    fn wake_one(&self) {
        loop {
            let head = self.head.load(Ordering::Acquire);
            if head.is_null() {
                return;
            }

            // SAFETY: head was pushed via Arc::into_raw and is valid while in the stack.
            let next = unsafe { (*head).next.load(Ordering::Relaxed) };
            if self
                .head
                .compare_exchange_weak(head, next, Ordering::AcqRel, Ordering::Acquire)
                .is_ok()
            {
                // SAFETY: reconstitute the Arc that was stored via Arc::into_raw.
                // Exactly one reconstitution per into_raw call.
                let node = unsafe { Arc::from_raw(head as *const WaiterNode) };
                if node.revoked.load(Ordering::Acquire) {
                    continue;
                }
                node.notify.notify_one();
                return;
            }
        }
    }
}

impl Drop for TreiberStack {
    fn drop(&mut self) {
        let mut current = *self.head.get_mut();
        while !current.is_null() {
            // SAFETY: each node was pushed via Arc::into_raw
            let node = unsafe { Arc::from_raw(current as *const WaiterNode) };
            current = node.next.load(Ordering::Relaxed);
        }
    }
}

/// Lock-free LIFO waiter policy with per-waiter wake targeting.
pub struct TreiberWaiters {
    stack: Arc<TreiberStack>,
}

impl TreiberWaiters {
    /// Create a Treiber-based waiter policy.
    pub fn new() -> Self {
        Self {
            stack: Arc::new(TreiberStack::new()),
        }
    }
}

impl Default for TreiberWaiters {
    fn default() -> Self {
        Self::new()
    }
}

impl Waiter for TreiberWaiters {
    type Registration = TreiberRegistration;

    fn register(&self) -> Self::Registration {
        let node = Arc::new(WaiterNode {
            next: AtomicPtr::new(ptr::null_mut()),
            notify: Arc::new(tokio::sync::Notify::new()),
            revoked: AtomicBool::new(false),
        });

        TreiberRegistration {
            node: Arc::clone(&node),
            stack: Arc::clone(&self.stack),
            future: node.notify.clone().notified_owned(),
            published: false,
        }
    }

    fn wake_one(&self) {
        self.stack.wake_one();
    }
}

pub struct TreiberRegistration {
    node: Arc<WaiterNode>,
    stack: Arc<TreiberStack>,
    future: OwnedNotified,
    published: bool,
}

impl WaitRegistration for TreiberRegistration {
    fn prepare(mut self: Pin<&mut Self>) {
        let _ = self.as_mut().project_future().enable();
        // SAFETY: updating `published` does not move the pinned future field.
        let this = unsafe { self.as_mut().get_unchecked_mut() };
        if !this.published {
            this.stack.push(Arc::into_raw(Arc::clone(&this.node)));
            this.published = true;
        }
    }

    fn revoke(self: Pin<&mut Self>) {
        self.node.revoked.store(true, Ordering::Release);
    }
}

impl Future for TreiberRegistration {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.project_future().poll(cx)
    }
}

impl TreiberRegistration {
    fn project_future(self: Pin<&mut Self>) -> Pin<&mut OwnedNotified> {
        // SAFETY: pinning `TreiberRegistration` also pins its `future` field.
        unsafe { self.map_unchecked_mut(|this| &mut this.future) }
    }
}

#[doc(hidden)]
pub enum BuiltInWaiters {
    Notify(NotifyWaiters),
    Treiber(TreiberWaiters),
}

impl Waiter for BuiltInWaiters {
    type Registration = BuiltInRegistration;

    fn register(&self) -> Self::Registration {
        match self {
            Self::Notify(waiters) => BuiltInRegistration::Notify(waiters.register()),
            Self::Treiber(waiters) => BuiltInRegistration::Treiber(waiters.register()),
        }
    }

    fn wake_one(&self) {
        match self {
            Self::Notify(waiters) => Waiter::wake_one(waiters),
            Self::Treiber(waiters) => Waiter::wake_one(waiters),
        }
    }
}

#[doc(hidden)]
pub enum BuiltInRegistration {
    Notify(NotifyRegistration),
    Treiber(TreiberRegistration),
}

impl WaitRegistration for BuiltInRegistration {
    fn prepare(self: Pin<&mut Self>) {
        // SAFETY: pinning the enum pins the active registration variant in place.
        unsafe {
            match self.get_unchecked_mut() {
                Self::Notify(registration) => Pin::new_unchecked(registration).prepare(),
                Self::Treiber(registration) => Pin::new_unchecked(registration).prepare(),
            }
        }
    }

    fn revoke(self: Pin<&mut Self>) {
        // SAFETY: pinning the enum pins the active registration variant in place.
        unsafe {
            match self.get_unchecked_mut() {
                Self::Notify(registration) => Pin::new_unchecked(registration).revoke(),
                Self::Treiber(registration) => Pin::new_unchecked(registration).revoke(),
            }
        }
    }
}

impl Future for BuiltInRegistration {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // SAFETY: pinning the enum pins the active registration variant in place.
        unsafe {
            match self.get_unchecked_mut() {
                Self::Notify(registration) => Pin::new_unchecked(registration).poll(cx),
                Self::Treiber(registration) => Pin::new_unchecked(registration).poll(cx),
            }
        }
    }
}

async fn allocate_with_waiter<W, T, F>(waiters: &W, mut try_allocate: F) -> T
where
    W: Waiter,
    F: FnMut() -> Option<T>,
{
    loop {
        let registration = waiters.register();
        tokio::pin!(registration);
        registration.as_mut().prepare();
        if let Some(value) = try_allocate() {
            registration.as_mut().revoke();
            return value;
        }
        registration.await;
    }
}

/// Async-capable wrapper around [`FixedArena`].
///
/// Created via [`FixedArenaBuilder::build_async()`]. Provides
/// [`allocate_async()`](AsyncFixedArena::allocate_async) which parks
/// until a slot becomes available, while sync methods remain accessible
/// through `Deref<Target = FixedArena>`.
#[derive(Clone)]
pub struct AsyncFixedArena<W = BuiltInWaiters> {
    inner: FixedArena,
    waiters: Arc<W>,
}

impl<W> AsyncFixedArena<W> {
    pub(crate) fn new(inner: FixedArena, waiters: Arc<W>) -> Self {
        Self { inner, waiters }
    }
}

impl<W: Waiter> AsyncFixedArena<W> {
    /// Allocate a buffer, waiting asynchronously if the arena is full.
    ///
    /// Returns once a slot becomes available. The bitmap is the source
    /// of truth; notifications are hints to retry.
    pub async fn allocate_async(&self) -> Buffer {
        allocate_with_waiter(self.waiters.as_ref(), || self.inner.allocate().ok()).await
    }
}

impl<W> Deref for AsyncFixedArena<W> {
    type Target = FixedArena;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<W> fmt::Debug for AsyncFixedArena<W> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AsyncFixedArena")
            .field("inner", &self.inner)
            .finish()
    }
}

/// Async-capable wrapper around [`BuddyArena`].
///
/// Created via [`BuddyArenaBuilder::build_async()`]. Provides
/// [`allocate_async()`](AsyncBuddyArena::allocate_async) which parks
/// until a large-enough block becomes available, while sync methods remain
/// accessible through `Deref<Target = BuddyArena>`.
#[derive(Clone)]
pub struct AsyncBuddyArena<W = NotifyWaiters> {
    inner: BuddyArena,
    waiters: Arc<W>,
}

impl<W> AsyncBuddyArena<W> {
    pub(crate) fn new(inner: BuddyArena, waiters: Arc<W>) -> Self {
        Self { inner, waiters }
    }
}

impl<W: Waiter> AsyncBuddyArena<W> {
    /// Allocate a buffer, waiting asynchronously if the arena is full.
    ///
    /// The buddy bitmaps remain the source of truth; notifications are hints
    /// to retry after free or coalesce publishes a usable block.
    pub async fn allocate_async(&self, len: std::num::NonZeroUsize) -> Buffer {
        allocate_with_waiter(self.waiters.as_ref(), || self.inner.allocate(len).ok()).await
    }
}

impl<W> Deref for AsyncBuddyArena<W> {
    type Target = BuddyArena;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<W> fmt::Debug for AsyncBuddyArena<W> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AsyncBuddyArena")
            .field("inner", &self.inner)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use std::num::NonZeroUsize;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};

    use bytes::BufMut;
    use tokio::time::{Duration, timeout};

    use crate::BuddyArena;
    use crate::FixedArena;

    use super::*;

    fn nz(n: usize) -> NonZeroUsize {
        NonZeroUsize::new(n).unwrap()
    }

    #[derive(Clone)]
    struct CountingWaiters {
        inner: NotifyWaiters,
        registrations: Arc<AtomicUsize>,
        wakes: Arc<AtomicUsize>,
    }

    impl CountingWaiters {
        fn new() -> Self {
            Self {
                inner: NotifyWaiters::new(),
                registrations: Arc::new(AtomicUsize::new(0)),
                wakes: Arc::new(AtomicUsize::new(0)),
            }
        }

        fn registrations(&self) -> usize {
            self.registrations.load(AtomicOrdering::Relaxed)
        }

        fn wakes(&self) -> usize {
            self.wakes.load(AtomicOrdering::Relaxed)
        }
    }

    struct CountingRegistration {
        inner: NotifyRegistration,
    }

    impl Waiter for CountingWaiters {
        type Registration = CountingRegistration;

        fn register(&self) -> Self::Registration {
            self.registrations.fetch_add(1, AtomicOrdering::Relaxed);
            CountingRegistration {
                inner: self.inner.register(),
            }
        }

        fn wake_one(&self) {
            self.wakes.fetch_add(1, AtomicOrdering::Relaxed);
            Waiter::wake_one(&self.inner);
        }
    }

    impl WaitRegistration for CountingRegistration {
        fn prepare(self: Pin<&mut Self>) {
            self.project_inner().prepare();
        }

        fn revoke(self: Pin<&mut Self>) {
            self.project_inner().revoke();
        }
    }

    impl Future for CountingRegistration {
        type Output = ();

        fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
            self.project_inner().poll(cx)
        }
    }

    impl CountingRegistration {
        fn project_inner(self: Pin<&mut Self>) -> Pin<&mut NotifyRegistration> {
            // SAFETY: pinning `CountingRegistration` also pins its inner registration.
            unsafe { self.map_unchecked_mut(|this| &mut this.inner) }
        }
    }

    #[tokio::test]
    async fn allocate_async_basic() {
        let arena = FixedArena::builder(nz(1), nz(32))
            .build_async(AsyncPolicy::Notify)
            .unwrap();
        let mut buf = arena.allocate_async().await;
        buf.put_slice(b"data");
        let bytes = buf.freeze();
        drop(bytes);
        let _buf2 = arena.allocate_async().await;
    }

    #[tokio::test]
    async fn allocate_async_waits_then_succeeds() {
        let arena = Arc::new(
            FixedArena::builder(nz(1), nz(32))
                .build_async(AsyncPolicy::Notify)
                .unwrap(),
        );
        let mut buf = arena.allocate_async().await;
        buf.put_slice(b"blocking");
        let bytes = buf.freeze();
        let arena2 = Arc::clone(&arena);
        let handle = tokio::spawn(async move {
            let buf = arena2.allocate_async().await;
            buf.capacity()
        });
        tokio::time::sleep(Duration::from_millis(50)).await;
        drop(bytes);
        let cap = timeout(Duration::from_secs(2), handle)
            .await
            .expect("should not timeout")
            .expect("task should not panic");
        assert_eq!(cap, 32);
    }

    #[tokio::test]
    async fn sync_allocate_still_fast_fails() {
        let arena = FixedArena::builder(nz(1), nz(32))
            .build_async(AsyncPolicy::Notify)
            .unwrap();
        let _buf = arena.allocate().unwrap();
        let err = arena.allocate().unwrap_err();
        assert_eq!(err, crate::AllocError::ArenaFull);
    }

    #[tokio::test]
    async fn multiple_waiters_all_served() {
        let arena = Arc::new(
            FixedArena::builder(nz(2), nz(32))
                .build_async(AsyncPolicy::Notify)
                .unwrap(),
        );
        let buf1 = arena.allocate().unwrap();
        let buf2 = arena.allocate().unwrap();
        let a1 = Arc::clone(&arena);
        let h1 = tokio::spawn(async move { a1.allocate_async().await.capacity() });
        let a2 = Arc::clone(&arena);
        let h2 = tokio::spawn(async move { a2.allocate_async().await.capacity() });
        tokio::time::sleep(Duration::from_millis(50)).await;
        drop(buf1);
        drop(buf2);
        let (r1, r2) = tokio::join!(
            timeout(Duration::from_secs(2), h1),
            timeout(Duration::from_secs(2), h2),
        );
        assert_eq!(r1.unwrap().unwrap(), 32);
        assert_eq!(r2.unwrap().unwrap(), 32);
    }

    #[tokio::test]
    async fn deref_exposes_sync_methods() {
        let arena = FixedArena::builder(nz(4), nz(64))
            .build_async(AsyncPolicy::Notify)
            .unwrap();
        assert_eq!(arena.slot_count(), 4);
        assert_eq!(arena.slot_capacity(), 64);
    }

    #[tokio::test]
    async fn treiber_allocate_async_basic() {
        let arena = FixedArena::builder(nz(1), nz(32))
            .build_async(AsyncPolicy::TreiberWaiters)
            .unwrap();
        let mut buf = arena.allocate_async().await;
        buf.put_slice(b"data");
        let bytes = buf.freeze();
        drop(bytes);
        let _buf2 = arena.allocate_async().await;
    }

    #[tokio::test]
    async fn treiber_waits_then_succeeds() {
        let arena = Arc::new(
            FixedArena::builder(nz(1), nz(32))
                .build_async(AsyncPolicy::TreiberWaiters)
                .unwrap(),
        );
        let mut buf = arena.allocate_async().await;
        buf.put_slice(b"blocking");
        let bytes = buf.freeze();
        let arena2 = Arc::clone(&arena);
        let handle = tokio::spawn(async move {
            let buf = arena2.allocate_async().await;
            buf.capacity()
        });
        tokio::time::sleep(Duration::from_millis(50)).await;
        drop(bytes);
        let cap = timeout(Duration::from_secs(2), handle)
            .await
            .expect("should not timeout")
            .expect("task should not panic");
        assert_eq!(cap, 32);
    }

    #[tokio::test]
    async fn treiber_multiple_waiters() {
        let arena = Arc::new(
            FixedArena::builder(nz(2), nz(32))
                .build_async(AsyncPolicy::TreiberWaiters)
                .unwrap(),
        );
        let buf1 = arena.allocate().unwrap();
        let buf2 = arena.allocate().unwrap();
        let a1 = Arc::clone(&arena);
        let h1 = tokio::spawn(async move { a1.allocate_async().await.capacity() });
        let a2 = Arc::clone(&arena);
        let h2 = tokio::spawn(async move { a2.allocate_async().await.capacity() });
        tokio::time::sleep(Duration::from_millis(50)).await;
        drop(buf1);
        drop(buf2);
        let (r1, r2) = tokio::join!(
            timeout(Duration::from_secs(2), h1),
            timeout(Duration::from_secs(2), h2),
        );
        assert_eq!(r1.unwrap().unwrap(), 32);
        assert_eq!(r2.unwrap().unwrap(), 32);
    }

    #[tokio::test]
    async fn treiber_cancellation_no_leak() {
        let arena = Arc::new(
            FixedArena::builder(nz(1), nz(32))
                .build_async(AsyncPolicy::TreiberWaiters)
                .unwrap(),
        );
        let buf = arena.allocate().unwrap();

        let arena2 = Arc::clone(&arena);
        let handle = tokio::spawn(async move { arena2.allocate_async().await });
        tokio::time::sleep(Duration::from_millis(50)).await;
        handle.abort();
        let _ = handle.await;

        drop(buf);

        let _buf2 = arena.allocate().unwrap();
    }

    #[tokio::test]
    async fn treiber_sync_still_fast_fails() {
        let arena = FixedArena::builder(nz(1), nz(32))
            .build_async(AsyncPolicy::TreiberWaiters)
            .unwrap();
        let _buf = arena.allocate().unwrap();
        let err = arena.allocate().unwrap_err();
        assert_eq!(err, crate::AllocError::ArenaFull);
    }

    #[tokio::test]
    async fn buddy_allocate_async_waits_then_succeeds() {
        let arena = Arc::new(
            BuddyArena::builder(nz(4096), nz(512))
                .build_async()
                .unwrap(),
        );
        let buf = arena.allocate(nz(2048)).unwrap();

        let arena2 = Arc::clone(&arena);
        let handle = tokio::spawn(async move {
            let buf = arena2.allocate_async(nz(2048)).await;
            buf.capacity()
        });

        tokio::time::sleep(Duration::from_millis(50)).await;
        drop(buf);

        let cap = timeout(Duration::from_secs(2), handle)
            .await
            .expect("should not timeout")
            .expect("task should not panic");
        assert_eq!(cap, 2048);
    }

    #[tokio::test]
    async fn buddy_multiple_waiters_all_served() {
        let arena = Arc::new(
            BuddyArena::builder(nz(4096), nz(512))
                .build_async()
                .unwrap(),
        );
        let buf1 = arena.allocate(nz(2048)).unwrap();
        let buf2 = arena.allocate(nz(2048)).unwrap();

        let a1 = Arc::clone(&arena);
        let h1 = tokio::spawn(async move { a1.allocate_async(nz(2048)).await.capacity() });
        let a2 = Arc::clone(&arena);
        let h2 = tokio::spawn(async move { a2.allocate_async(nz(2048)).await.capacity() });

        tokio::time::sleep(Duration::from_millis(50)).await;
        drop(buf1);
        drop(buf2);

        let (r1, r2) = tokio::join!(
            timeout(Duration::from_secs(2), h1),
            timeout(Duration::from_secs(2), h2),
        );
        assert_eq!(r1.unwrap().unwrap(), 2048);
        assert_eq!(r2.unwrap().unwrap(), 2048);
    }

    #[tokio::test]
    async fn buddy_large_request_unblocks_after_coalesce() {
        let arena = Arc::new(
            BuddyArena::builder(nz(4096), nz(512))
                .build_async()
                .unwrap(),
        );
        let buf1 = arena.allocate(nz(2048)).unwrap();
        let buf2 = arena.allocate(nz(2048)).unwrap();

        let arena2 = Arc::clone(&arena);
        let handle = tokio::spawn(async move {
            let buf = arena2.allocate_async(nz(4096)).await;
            buf.capacity()
        });

        tokio::time::sleep(Duration::from_millis(50)).await;
        drop(buf1);
        tokio::time::sleep(Duration::from_millis(25)).await;
        assert!(!handle.is_finished());
        drop(buf2);

        let cap = timeout(Duration::from_secs(2), handle)
            .await
            .expect("should not timeout")
            .expect("task should not panic");
        assert_eq!(cap, 4096);
    }

    #[tokio::test]
    async fn buddy_cancellation_does_not_leak() {
        let arena = Arc::new(
            BuddyArena::builder(nz(4096), nz(512))
                .build_async()
                .unwrap(),
        );
        let buf = arena.allocate(nz(4096)).unwrap();

        let arena2 = Arc::clone(&arena);
        let handle = tokio::spawn(async move { arena2.allocate_async(nz(512)).await });
        tokio::time::sleep(Duration::from_millis(50)).await;
        handle.abort();
        let _ = handle.await;

        drop(buf);

        let _buf2 = arena.allocate(nz(4096)).unwrap();
    }

    #[tokio::test]
    async fn fixed_custom_waiter_supported() {
        let waiters = CountingWaiters::new();
        let arena = Arc::new(
            FixedArena::builder(nz(1), nz(32))
                .build_async_with(waiters.clone())
                .unwrap(),
        );
        let buf = arena.allocate().unwrap();

        let arena2 = Arc::clone(&arena);
        let handle = tokio::spawn(async move { arena2.allocate_async().await.capacity() });
        tokio::time::sleep(Duration::from_millis(50)).await;
        drop(buf);

        let cap = timeout(Duration::from_secs(2), handle)
            .await
            .expect("should not timeout")
            .expect("task should not panic");
        assert_eq!(cap, 32);
        assert!(waiters.registrations() >= 1);
        assert!(waiters.wakes() >= 1);
    }

    #[tokio::test]
    async fn buddy_custom_waiter_supported() {
        let waiters = CountingWaiters::new();
        let arena = Arc::new(
            BuddyArena::builder(nz(4096), nz(512))
                .build_async_with(waiters.clone())
                .unwrap(),
        );
        let buf = arena.allocate(nz(2048)).unwrap();

        let arena2 = Arc::clone(&arena);
        let handle = tokio::spawn(async move { arena2.allocate_async(nz(2048)).await.capacity() });
        tokio::time::sleep(Duration::from_millis(50)).await;
        drop(buf);

        let cap = timeout(Duration::from_secs(2), handle)
            .await
            .expect("should not timeout")
            .expect("task should not panic");
        assert_eq!(cap, 2048);
        assert!(waiters.registrations() >= 1);
        assert!(waiters.wakes() >= 1);
    }
}