strede 0.1.1

Async, zero-alloc, pull-based deserialization for Rust
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
use core::{
    cell::Cell,
    future::Future,
    pin::Pin,
    task::{Context, Poll},
};
use pin_project::pin_project;

/// Result of a type-dispatch probe.
///
/// Returned inside `Result<Probe<T>, E>` by all [`Entry`](crate::Entry) probe methods and
/// [`Deserialize::deserialize`](crate::Deserialize::deserialize).
///
/// - `Hit(value)` - token matched; `value` is `(Claim, T)` or an access type.
/// - `Miss` - token did not match this probe's expected type; stream was **not**
///   consumed. Other probes racing via [`select_probe!`](crate::select_probe) can still win.
///
/// Fatal format errors are the outer `Err(e)` and propagate normally with `?`.
/// `Pending` on a probe future means *only* "no data available yet."
#[derive(Debug, PartialEq)]
pub enum Probe<T> {
    Hit(T),
    Miss,
}

impl<T> Probe<T> {
    /// Unwrap a `Hit`, panicking on `Miss`.
    #[inline(always)]
    pub fn unwrap(self) -> T {
        match self {
            Probe::Hit(v) => v,
            Probe::Miss => panic!("called Probe::unwrap() on a Miss value"),
        }
    }

    /// Convert to `Result`, treating `Miss` as an error via the provided closure.
    #[inline(always)]
    pub fn require<E>(self, on_miss: impl FnOnce() -> E) -> Result<T, E> {
        match self {
            Probe::Hit(v) => Ok(v),
            Probe::Miss => Err(on_miss()),
        }
    }

    #[inline(always)]
    pub fn is_miss(&self) -> bool {
        matches!(self, Probe::Miss)
    }
    #[inline(always)]
    pub fn is_hit(&self) -> bool {
        matches!(self, Probe::Hit(_))
    }

    /// Map the inner value of a `Hit`, leaving `Miss` unchanged.
    #[inline(always)]
    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Probe<U> {
        match self {
            Probe::Hit(v) => Probe::Hit(f(v)),
            Probe::Miss => Probe::Miss,
        }
    }
}

/// Propagates `Err` and `Ok(Probe::Miss)` from the enclosing function;
/// unwraps `Ok(Probe::Hit(v))` to `v`.
///
/// The enclosing function must return `Result<Probe<_>, E>`.
///
/// # Example
/// ```rust,ignore
/// let mut map = hit!(e.deserialize_map().await);
/// let (claim, val) = hit!(e.deserialize_bool().await);
/// ```
#[macro_export]
macro_rules! hit {
    ($e:expr) => {
        match $e? {
            $crate::Probe::Hit(v) => v,
            $crate::Probe::Miss => return ::core::result::Result::Ok($crate::Probe::Miss),
        }
    };
}

/// Unwraps an `Option`, returning `Ok(Probe::Miss)` from the enclosing
/// function on `None`.
///
/// # Example
/// ```rust,ignore
/// let v = or_miss!(some_option);
/// ```
#[macro_export]
macro_rules! or_miss {
    ($e:expr) => {
        match $e {
            ::core::option::Option::Some(v) => v,
            ::core::option::Option::None => return ::core::result::Result::Ok($crate::Probe::Miss),
        }
    };
}

/// Race multiple probe futures, returning the first `Hit`.
///
/// Each arm is an expression that evaluates to a future returning
/// `Result<Probe<T>, E>`. Arms can be bare probe calls
/// (`e.deserialize_i64()`) or `async move { ... }` blocks for logic that
/// needs `.await` or value transformation.
///
/// ```rust,ignore
/// let val = select_probe! {
///     e1.deserialize_bool(),
///     async move { hit!(e2.deserialize_i64().await); Ok(Probe::Hit((c, v as bool))) },
///     @miss => Ok(Probe::Miss),
/// }
/// .await?;
/// ```
///
/// # Behavior
///
/// - Arms are polled in declaration order on every wake-up.
/// - `Pending` means "waiting for I/O" - the arm stays live.
/// - `Ok(Probe::Miss)` marks an arm done; it is skipped on future polls.
/// - `Ok(Probe::Hit(_))` - first hit in declaration order wins.
/// - `Err(e)` short-circuits immediately.
/// - When all arms have returned `Miss`, the optional `miss => body` arm fires;
///   without it the macro produces `Ok(Probe::Miss)`.
///
/// # Killing sibling arms
///
/// A `kill!(i)` macro is in scope inside every arm expression. Calling it
/// schedules arm `i` for cancellation: its future is dropped in place on the
/// next poll, before any arm is polled that iteration. This is useful when one
/// arm has already seen enough to know a sibling can never win.
///
/// There is no point calling `kill!(i)` immediately before returning - the
/// sibling only dies on the *next* poll, which never comes once this arm
/// returns a `Hit`. `kill!` is only meaningful when the calling arm still has
/// work to do (e.g. an `.await` point) after ruling out the sibling.
///
/// ```rust,ignore
/// select_probe! {
///     async move {
///         let (c, s) = hit!(e1.deserialize_str().await);
///         kill!(1); // chunks fallback can't win now; drop it before we await again
///         let owned = some_async_transform(s).await;
///         Ok(Probe::Hit((c, owned)))
///     },
///     async move { /* chunks fallback */ },
/// }
/// ```
/// Builds the arm list via `+` on `SelectProbeBase`.
/// `__select_probe_arms!(a, b, c)` expands to
/// `SelectProbeBase + ProbeArm(a) + ProbeArm(b) + ProbeArm(c)`.
#[doc(hidden)]
#[macro_export]
macro_rules! __select_probe_arms {
    ($($arm:expr),+) => {
        $crate::probe::SelectProbeBase $(+ $crate::probe::ProbeArm($arm))+
    };
}

#[macro_export]
macro_rules! select_probe {
    (biased; $($arm:expr),* $(, @miss => $miss:expr)? $(,)?) => {$crate::__select_probe_inner!(true; $($arm),* $(, @miss => $miss)?)};
    ($($arm:expr),* $(, @miss => $miss:expr)? $(,)?) => {$crate::__select_probe_inner!(false; $($arm),* $(, @miss => $miss)?)};
}

#[doc(hidden)]
#[macro_export]
macro_rules! __select_probe_inner {
    ($bias:literal; $($arm:expr),* $(, @miss => $miss:expr)?) => {{
        #[allow(unused_imports)]
        use $crate::probe::MissFallback as _;
        let __probe_kills = <$crate::probe::KillManager<_>>::new();
        let __probe_kills = &__probe_kills;
        #[allow(unused_macros)]
        macro_rules! kill {
            ($i:literal) => { __probe_kills.mark($i) };
        }
        let _miss = ::core::result::Result::Ok($crate::Probe::Miss);
        let _miss2: *const _ = &_miss;
        $(let _miss = $miss;)?
        let miss = || $crate::probe::MissWrapper(_miss).into_future();
        $crate::probe::align_types(_miss2, &miss);
        let __probe_futs = $crate::__select_probe_arms!($($arm),+);
        $crate::probe::select_probe($bias, __probe_kills, __probe_futs, miss).await
    }};
}

#[doc(hidden)]
pub struct MissWrapper<T>(pub T);

// Inherent method for Future types (takes priority)
impl<T: Future> MissWrapper<T> {
    #[inline(always)]
    pub fn into_future(self) -> T {
        self.0
    }
}

/// Trait method for non-Future types (fallback)
#[doc(hidden)]
pub trait MissFallback {
    type Fut: Future;
    fn into_future(self) -> Self::Fut;
}
impl<T, E> MissFallback for MissWrapper<Result<Probe<T>, E>> {
    type Fut = core::future::Ready<Result<Probe<T>, E>>;
    #[inline(always)]
    fn into_future(self) -> Self::Fut {
        core::future::ready(self.0)
    }
}

#[doc(hidden)]
pub trait SelectProbeKillFlag {
    const SIZE: usize;
    fn new() -> Self;
    fn is_marked(&self, i: usize) -> bool;
    fn mark(&self, i: usize);
}

impl SelectProbeKillFlag for () {
    const SIZE: usize = 0;
    #[inline(always)]
    fn new() -> Self {}
    #[inline(always)]
    fn is_marked(&self, _i: usize) -> bool {
        unreachable!()
    }
    #[inline(always)]
    fn mark(&self, _i: usize) {
        unreachable!()
    }
}

impl<T: SelectProbeKillFlag> SelectProbeKillFlag for (T, Cell<bool>) {
    const SIZE: usize = T::SIZE + 1;
    #[inline(always)]
    fn new() -> Self {
        (T::new(), Cell::new(false))
    }
    #[inline(always)]
    fn is_marked(&self, i: usize) -> bool {
        debug_assert!(i < Self::SIZE);
        if i == Self::SIZE - 1 {
            self.1.get()
        } else {
            self.0.is_marked(i)
        }
    }
    #[inline(always)]
    fn mark(&self, i: usize) {
        debug_assert!(i < Self::SIZE);
        if i == Self::SIZE - 1 {
            self.1.set(true);
        } else {
            self.0.mark(i)
        }
    }
}

#[doc(hidden)]
pub struct KillManager<T: SelectProbeKillFlag> {
    flags: T,
    new_kills: Cell<bool>,
}

impl<T: SelectProbeKillFlag> Default for KillManager<T> {
    #[inline(always)]
    fn default() -> Self {
        Self::new()
    }
}

impl<T: SelectProbeKillFlag> KillManager<T> {
    #[inline(always)]
    pub fn new() -> Self {
        Self {
            flags: T::new(),
            new_kills: Cell::new(false),
        }
    }
    #[inline(always)]
    pub fn mark(&self, i: usize) {
        self.flags.mark(i);
        self.new_kills.set(true);
    }
    #[inline(always)]
    fn take_new_kills(&self) -> bool {
        self.new_kills.replace(false)
    }
}

/// Wrapper that marks a future as one arm of a [`select_probe!`](crate::select_probe) call.
///
/// Used with `+` on [`SelectProbeBase`] to build the arm list without recursive macros:
/// `SelectProbeBase + ProbeArm(f1) + ProbeArm(f2) + ...`
#[doc(hidden)]
pub struct ProbeArm<F>(pub F);

/// Marker type used as the seed of the `ProbeArm` addition chain.
#[doc(hidden)]
pub struct SelectProbeBase;

// SelectProbeBase + ProbeArm(f) → SP1
impl<F> core::ops::Add<ProbeArm<F>> for SelectProbeBase {
    type Output = SP1<F>;
    #[inline(always)]
    fn add(self, rhs: ProbeArm<F>) -> SP1<F> {
        SP1(Some(rhs.0))
    }
}

/// Flat accumulator: 1 arm.
#[doc(hidden)]
#[pin_project]
pub struct SP1<A>(#[pin] Option<A>);

/// Flat accumulator: 2 arms.
#[doc(hidden)]
#[pin_project]
pub struct SP2<A, B>(#[pin] Option<A>, #[pin] Option<B>);

/// Flat accumulator: 3 arms.
#[doc(hidden)]
#[pin_project]
pub struct SP3<A, B, C>(#[pin] Option<A>, #[pin] Option<B>, #[pin] Option<C>);

/// Flat accumulator: 4 arms.
#[doc(hidden)]
#[pin_project]
pub struct SP4<A, B, C, D>(
    #[pin] Option<A>,
    #[pin] Option<B>,
    #[pin] Option<C>,
    #[pin] Option<D>,
);

// SP1 + ProbeArm → SP2
impl<A, B> core::ops::Add<ProbeArm<B>> for SP1<A> {
    type Output = SP2<A, B>;
    #[inline(always)]
    fn add(self, rhs: ProbeArm<B>) -> SP2<A, B> {
        SP2(self.0, Some(rhs.0))
    }
}

// SP2 + ProbeArm → SP3
impl<A, B, C> core::ops::Add<ProbeArm<C>> for SP2<A, B> {
    type Output = SP3<A, B, C>;
    #[inline(always)]
    fn add(self, rhs: ProbeArm<C>) -> SP3<A, B, C> {
        SP3(self.0, self.1, Some(rhs.0))
    }
}

// SP3 + ProbeArm → SP4
impl<A, B, C, D> core::ops::Add<ProbeArm<D>> for SP3<A, B, C> {
    type Output = SP4<A, B, C, D>;
    #[inline(always)]
    fn add(self, rhs: ProbeArm<D>) -> SP4<A, B, C, D> {
        SP4(self.0, self.1, self.2, Some(rhs.0))
    }
}

// SP4 + ProbeArm → overflow into left-nested SelectProbeSlot chain
impl<A, B, C, D, E> core::ops::Add<ProbeArm<E>> for SP4<A, B, C, D> {
    type Output = SelectProbeSlot<SP4<A, B, C, D>, E>;
    #[inline(always)]
    fn add(self, rhs: ProbeArm<E>) -> SelectProbeSlot<SP4<A, B, C, D>, E> {
        SelectProbeSlot {
            rest: self,
            fut: Some(rhs.0),
        }
    }
}

// SelectProbeSlot<L, F> + ProbeArm → keep left-nesting
impl<L, F, G> core::ops::Add<ProbeArm<G>> for SelectProbeSlot<L, F> {
    type Output = SelectProbeSlot<SelectProbeSlot<L, F>, G>;
    #[inline(always)]
    fn add(self, rhs: ProbeArm<G>) -> SelectProbeSlot<SelectProbeSlot<L, F>, G> {
        SelectProbeSlot {
            rest: self,
            fut: Some(rhs.0),
        }
    }
}

/// One slot in the overflow left-nested chain (5+ arms after the flat SP4 base).
#[doc(hidden)]
#[pin_project]
pub struct SelectProbeSlot<Rest, F> {
    #[pin]
    rest: Rest,
    #[pin]
    fut: Option<F>,
}

/// Identity conversion - SP1–SP4 and SelectProbeSlot are already in slot form.
#[doc(hidden)]
pub trait IntoSelectProbeSlots {
    type Slots;
    fn into_slots(self) -> Self::Slots;
}

impl<A> IntoSelectProbeSlots for SP1<A> {
    type Slots = Self;
    #[inline(always)]
    fn into_slots(self) -> Self {
        self
    }
}
impl<A, B> IntoSelectProbeSlots for SP2<A, B> {
    type Slots = Self;
    #[inline(always)]
    fn into_slots(self) -> Self {
        self
    }
}
impl<A, B, C> IntoSelectProbeSlots for SP3<A, B, C> {
    type Slots = Self;
    #[inline(always)]
    fn into_slots(self) -> Self {
        self
    }
}
impl<A, B, C, D> IntoSelectProbeSlots for SP4<A, B, C, D> {
    type Slots = Self;
    #[inline(always)]
    fn into_slots(self) -> Self {
        self
    }
}
impl<L: IntoSelectProbeSlots, F> IntoSelectProbeSlots for SelectProbeSlot<L, F> {
    type Slots = SelectProbeSlot<L::Slots, F>;
    #[inline(always)]
    fn into_slots(self) -> Self::Slots {
        SelectProbeSlot {
            rest: self.rest.into_slots(),
            fut: self.fut,
        }
    }
}

#[doc(hidden)]
pub trait SelectProbeFutures<T, E> {
    const SIZE: usize;
    type KF: SelectProbeKillFlag;
    fn process_kills(self: Pin<&mut Self>, kill_flags: &Self::KF, active: &mut usize);
    fn poll_one(
        self: Pin<&mut Self>,
        i: usize,
        active: &mut usize,
        cx: &mut Context<'_>,
    ) -> Poll<Result<Probe<T>, E>>;
}

// Helper: poll a pinned Option<F> slot.
// Returns Poll::Ready(Some(result)) on hit/err, Poll::Pending otherwise.
// On Miss, sets slot to None and decrements *active.
#[inline(always)]
fn poll_slot<T, E, F: Future<Output = Result<Probe<T>, E>>>(
    mut slot: Pin<&mut Option<F>>,
    active: &mut usize,
    cx: &mut Context<'_>,
) -> Poll<Option<Result<Probe<T>, E>>> {
    match slot.as_mut().as_pin_mut() {
        None => Poll::Pending,
        Some(fut) => match Future::poll(fut, cx) {
            Poll::Ready(Ok(Probe::Hit(v))) => Poll::Ready(Some(Ok(Probe::Hit(v)))),
            Poll::Ready(Ok(Probe::Miss)) => {
                slot.set(None);
                *active -= 1;
                Poll::Pending
            }
            Poll::Ready(Err(e)) => Poll::Ready(Some(Err(e))),
            Poll::Pending => Poll::Pending,
        },
    }
}

/// Kill flags for flat SP1–SP4: one `Cell<bool>` per arm.
#[doc(hidden)]
pub struct FlatKillFlags<const N: usize>([Cell<bool>; N]);
impl<const N: usize> FlatKillFlags<N> {
    #[inline(always)]
    fn new() -> Self {
        Self(core::array::from_fn(|_| Cell::new(false)))
    }
}
impl<const N: usize> SelectProbeKillFlag for FlatKillFlags<N> {
    const SIZE: usize = N;
    #[inline(always)]
    fn new() -> Self {
        Self::new()
    }
    #[inline(always)]
    fn is_marked(&self, i: usize) -> bool {
        self.0[i].get()
    }
    #[inline(always)]
    fn mark(&self, i: usize) {
        self.0[i].set(true);
    }
}

// Flat SP1 impl
impl<T, E, A: Future<Output = Result<Probe<T>, E>>> SelectProbeFutures<T, E> for SP1<A> {
    const SIZE: usize = 1;
    type KF = FlatKillFlags<1>;
    #[inline(always)]
    fn process_kills(self: Pin<&mut Self>, kill_flags: &Self::KF, active: &mut usize) {
        let mut slot = self.project().0;
        if kill_flags.0[0].get() && slot.as_mut().as_pin_mut().is_some() {
            slot.set(None);
            *active -= 1;
        }
    }
    #[inline(always)]
    fn poll_one(
        self: Pin<&mut Self>,
        i: usize,
        active: &mut usize,
        cx: &mut Context<'_>,
    ) -> Poll<Result<Probe<T>, E>> {
        debug_assert_eq!(i, 0);
        match poll_slot(self.project().0, active, cx) {
            Poll::Ready(Some(r)) => Poll::Ready(r),
            _ => Poll::Pending,
        }
    }
}

// Flat SP2 impl
impl<T, E, A: Future<Output = Result<Probe<T>, E>>, B: Future<Output = Result<Probe<T>, E>>>
    SelectProbeFutures<T, E> for SP2<A, B>
{
    const SIZE: usize = 2;
    type KF = FlatKillFlags<2>;
    #[inline(always)]
    fn process_kills(self: Pin<&mut Self>, kill_flags: &Self::KF, active: &mut usize) {
        let mut p = self.project();
        if kill_flags.0[0].get() && p.0.as_mut().as_pin_mut().is_some() {
            p.0.set(None);
            *active -= 1;
        }
        if kill_flags.0[1].get() && p.1.as_mut().as_pin_mut().is_some() {
            p.1.set(None);
            *active -= 1;
        }
    }
    #[inline(always)]
    fn poll_one(
        self: Pin<&mut Self>,
        i: usize,
        active: &mut usize,
        cx: &mut Context<'_>,
    ) -> Poll<Result<Probe<T>, E>> {
        debug_assert!(i < 2);
        let p = self.project();
        match i {
            0 => match poll_slot(p.0, active, cx) {
                Poll::Ready(Some(r)) => Poll::Ready(r),
                _ => Poll::Pending,
            },
            _ => match poll_slot(p.1, active, cx) {
                Poll::Ready(Some(r)) => Poll::Ready(r),
                _ => Poll::Pending,
            },
        }
    }
}

// Flat SP3 impl
impl<
    T,
    E,
    A: Future<Output = Result<Probe<T>, E>>,
    B: Future<Output = Result<Probe<T>, E>>,
    C: Future<Output = Result<Probe<T>, E>>,
> SelectProbeFutures<T, E> for SP3<A, B, C>
{
    const SIZE: usize = 3;
    type KF = FlatKillFlags<3>;
    #[inline(always)]
    fn process_kills(self: Pin<&mut Self>, kill_flags: &Self::KF, active: &mut usize) {
        let mut p = self.project();
        if kill_flags.0[0].get() && p.0.as_mut().as_pin_mut().is_some() {
            p.0.set(None);
            *active -= 1;
        }
        if kill_flags.0[1].get() && p.1.as_mut().as_pin_mut().is_some() {
            p.1.set(None);
            *active -= 1;
        }
        if kill_flags.0[2].get() && p.2.as_mut().as_pin_mut().is_some() {
            p.2.set(None);
            *active -= 1;
        }
    }
    #[inline(always)]
    fn poll_one(
        self: Pin<&mut Self>,
        i: usize,
        active: &mut usize,
        cx: &mut Context<'_>,
    ) -> Poll<Result<Probe<T>, E>> {
        debug_assert!(i < 3);
        let p = self.project();
        match i {
            0 => match poll_slot(p.0, active, cx) {
                Poll::Ready(Some(r)) => Poll::Ready(r),
                _ => Poll::Pending,
            },
            1 => match poll_slot(p.1, active, cx) {
                Poll::Ready(Some(r)) => Poll::Ready(r),
                _ => Poll::Pending,
            },
            _ => match poll_slot(p.2, active, cx) {
                Poll::Ready(Some(r)) => Poll::Ready(r),
                _ => Poll::Pending,
            },
        }
    }
}

// Flat SP4 impl
impl<
    T,
    E,
    A: Future<Output = Result<Probe<T>, E>>,
    B: Future<Output = Result<Probe<T>, E>>,
    C: Future<Output = Result<Probe<T>, E>>,
    D: Future<Output = Result<Probe<T>, E>>,
> SelectProbeFutures<T, E> for SP4<A, B, C, D>
{
    const SIZE: usize = 4;
    type KF = FlatKillFlags<4>;
    #[inline(always)]
    fn process_kills(self: Pin<&mut Self>, kill_flags: &Self::KF, active: &mut usize) {
        let mut p = self.project();
        if kill_flags.0[0].get() && p.0.as_mut().as_pin_mut().is_some() {
            p.0.set(None);
            *active -= 1;
        }
        if kill_flags.0[1].get() && p.1.as_mut().as_pin_mut().is_some() {
            p.1.set(None);
            *active -= 1;
        }
        if kill_flags.0[2].get() && p.2.as_mut().as_pin_mut().is_some() {
            p.2.set(None);
            *active -= 1;
        }
        if kill_flags.0[3].get() && p.3.as_mut().as_pin_mut().is_some() {
            p.3.set(None);
            *active -= 1;
        }
    }
    #[inline(always)]
    fn poll_one(
        self: Pin<&mut Self>,
        i: usize,
        active: &mut usize,
        cx: &mut Context<'_>,
    ) -> Poll<Result<Probe<T>, E>> {
        debug_assert!(i < 4);
        let p = self.project();
        match i {
            0 => match poll_slot(p.0, active, cx) {
                Poll::Ready(Some(r)) => Poll::Ready(r),
                _ => Poll::Pending,
            },
            1 => match poll_slot(p.1, active, cx) {
                Poll::Ready(Some(r)) => Poll::Ready(r),
                _ => Poll::Pending,
            },
            2 => match poll_slot(p.2, active, cx) {
                Poll::Ready(Some(r)) => Poll::Ready(r),
                _ => Poll::Pending,
            },
            _ => match poll_slot(p.3, active, cx) {
                Poll::Ready(Some(r)) => Poll::Ready(r),
                _ => Poll::Pending,
            },
        }
    }
}

// Overflow: SelectProbeSlot left-nesting for 5+ arms (Rest must be SP4 or another SelectProbeSlot)
impl<T, E, F: Future<Output = Result<Probe<T>, E>>, Rest: SelectProbeFutures<T, E>>
    SelectProbeFutures<T, E> for SelectProbeSlot<Rest, F>
{
    const SIZE: usize = Rest::SIZE + 1;
    type KF = (Rest::KF, Cell<bool>);
    #[inline(always)]
    fn process_kills(self: Pin<&mut Self>, kill_flags: &Self::KF, active: &mut usize) {
        let mut this = self.project();
        this.rest.process_kills(&kill_flags.0, active);
        if kill_flags.1.get() && this.fut.as_mut().as_pin_mut().is_some() {
            this.fut.set(None);
            *active -= 1;
        }
    }
    #[inline(always)]
    fn poll_one(
        self: Pin<&mut Self>,
        i: usize,
        active: &mut usize,
        cx: &mut Context<'_>,
    ) -> Poll<Result<Probe<T>, E>> {
        debug_assert!(i < Self::SIZE);
        if i == Self::SIZE - 1 {
            match poll_slot(self.project().fut, active, cx) {
                Poll::Ready(Some(r)) => Poll::Ready(r),
                _ => Poll::Pending,
            }
        } else {
            self.project().rest.poll_one(i, active, cx)
        }
    }
}

#[doc(hidden)]
#[inline(always)]
pub const fn align_types<T, E, M, Fut>(_: *const Result<Probe<T>, E>, _: *const M)
where
    M: FnOnce() -> Fut,
    Fut: Future<Output = Result<Probe<T>, E>>,
{
}

/// Runs select_probe polling. Takes bare futures via `IntoSelectProbeSlots`,
/// pins them internally.
#[inline(always)]
pub async fn select_probe<T, E, Raw, M, Fut>(
    biased: bool,
    kills: &KillManager<<Raw::Slots as SelectProbeFutures<T, E>>::KF>,
    futures: Raw,
    miss: M,
) -> Result<Probe<T>, E>
where
    Raw: IntoSelectProbeSlots,
    Raw::Slots: SelectProbeFutures<T, E>,
    M: FnOnce() -> Fut,
    Fut: Future<Output = Result<Probe<T>, E>>,
{
    let mut slots = core::pin::pin!(futures.into_slots());
    let mut active = <Raw::Slots as SelectProbeFutures<T, E>>::SIZE;
    let v = core::future::poll_fn(move |cx| {
        for i in 0..<Raw::Slots as SelectProbeFutures<T, E>>::SIZE {
            if kills.take_new_kills() {
                slots.as_mut().process_kills(&kills.flags, &mut active);
            }
            match slots.as_mut().poll_one(i, &mut active, cx) {
                Poll::Ready(Ok(Probe::Hit(val))) if biased => {
                    // Re-poll arms 0..i to see if a higher-priority arm is
                    // also ready. If so, prefer it over arm i.
                    for j in 0..i {
                        if kills.take_new_kills() {
                            slots.as_mut().process_kills(&kills.flags, &mut active);
                        }
                        match slots.as_mut().poll_one(j, &mut active, cx) {
                            Poll::Ready(Ok(Probe::Hit(earlier_val))) => {
                                drop(val);
                                return Poll::Ready(Some(Ok(Probe::Hit(earlier_val))));
                            }
                            Poll::Ready(Ok(Probe::Miss)) => {}
                            Poll::Ready(Err(e)) => {
                                drop(val);
                                return Poll::Ready(Some(Err(e)));
                            }
                            Poll::Pending => {}
                        }
                    }
                    return Poll::Ready(Some(Ok(Probe::Hit(val))));
                }
                Poll::Ready(result) => return Poll::Ready(Some(result)),
                Poll::Pending => {}
            }
        }
        if active == 0 {
            return Poll::Ready(None);
        }
        Poll::Pending
    })
    .await;
    if let Some(v) = v {
        return v;
    }
    miss().await
}

/// Yielded by streaming accessors ([`StrAccess::next_str`](crate::StrAccess::next_str),
/// [`BytesAccess::next_bytes`](crate::BytesAccess::next_bytes),
/// [`MapAccess::next_kv`](crate::MapAccess::next_kv),
/// [`SeqAccess::next`](crate::SeqAccess::next)).
///
/// - `Data(item)` - another item of data.
/// - `Done(claim)` - the stream is exhausted; thread `claim` back to the
///   outer [`Deserializer::entry`](crate::Deserializer::entry) as proof-of-consumption.
pub enum Chunk<Data, Done> {
    Data(Data),
    Done(Done),
}

impl<Data, Done> Chunk<Data, Done> {
    #[inline(always)]
    pub fn data(self) -> Option<Data> {
        match self {
            Self::Data(d) => Some(d),
            _ => None,
        }
    }
    #[inline(always)]
    pub fn done(self) -> Option<Done> {
        match self {
            Self::Done(d) => Some(d),
            _ => None,
        }
    }

    #[inline(always)]
    pub fn map_data<Data2>(self, f: impl FnOnce(Data) -> Data2) -> Chunk<Data2, Done> {
        match self {
            Self::Data(d) => Chunk::Data(f(d)),
            Self::Done(d) => Chunk::Done(d),
        }
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use core::future::Future;
    use core::pin::Pin;
    use core::sync::atomic::{AtomicBool, Ordering};
    use core::task::{Context, Poll};

    fn poll_once<F: Future>(f: Pin<&mut F>) -> Poll<F::Output> {
        let w = strede_test_util::noop_waker();
        let mut cx = Context::from_waker(&w);
        f.poll(&mut cx)
    }

    #[test]
    fn kill_drops_future() {
        static DROPPED: AtomicBool = AtomicBool::new(false);

        struct SetOnDrop;
        impl Drop for SetOnDrop {
            fn drop(&mut self) {
                DROPPED.store(true, Ordering::SeqCst);
            }
        }

        let _guard = SetOnDrop;
        // arm 0: kills arm 1, returns Miss
        // arm 1: holds a SetOnDrop; once killed its future should be dropped
        // arm 2: checks DROPPED is true, returns Hit
        let fut = async {
            crate::select_probe! {
                async move {
                    kill!(1);
                    Ok(Probe::Miss)
                },
                async move {
                    let _guard = _guard;
                    core::future::pending::<Result<Probe<u32>, ()>>().await
                },
                async move {
                    assert!(DROPPED.load(Ordering::SeqCst), "arm 1 was not dropped");
                    Ok(Probe::Hit(42u32))
                },
            }
        };
        let mut fut = core::pin::pin!(fut);
        // Two polls: first lets all arms run once (arm 0 kills arm 1, arm 2 sees the drop)
        loop {
            match poll_once(fut.as_mut()) {
                Poll::Ready(result) => {
                    assert_eq!(result, Ok(Probe::Hit(42u32)));
                    break;
                }
                Poll::Pending => {}
            }
        }
    }
}