broadcast-common 13.0.0

Foundation for the rust-broadcast crates: symmetric Parse/Serialize traits, CRC-32/MPEG-2, BCD + MJD time codecs, bit I/O, 33-bit/PCR clock arithmetic, checked field widths, container-mux and Stage traits. no_std + alloc.
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
//! [`Stage`] — the incremental-drive contract every streaming stage in the
//! workspace adopts (media-plane migration step 1), plus the [`Timestamp`]
//! clock it is driven on.
//!
//! # Why
//!
//! The streaming families in the workspace grew "keep me fed" APIs, each
//! shaped differently: a `feed` returning `()` with output pulled through a
//! separate accessor, a `feed` returning only a `Result`, a `push` returning
//! the completed segment inline, and segmenters splitting draining into several
//! `take_*` methods. None of them carry a clock, which blocks deadline-driven
//! work (rate-scheduled SI emission, RTCP timeout, segment-boundary timers)
//! from sharing a driver loop with the byte-shovelling stages. `Stage` unifies
//! the shape: push input in with
//! [`Stage::feed`], pull typed output out with [`Stage::poll`] (repeatable,
//! decoupled from `feed`), signal end-of-input with [`Stage::finish`], and let
//! time-driven work happen via [`Stage::next_deadline`] / [`Stage::on_deadline`]
//! — all without requiring a full media IR or any concrete codec type.
//!
//! # `In`: a per-implementor input type, not hardcoded bytes
//!
//! The container-demux family's real input is bytes (`&[u8]`), but a
//! sample-consuming stage's real input is a typed `(track_id, Sample)` — there
//! is no useful byte encoding of a `Sample` that any caller wants, so forcing
//! `feed(&[u8], _)` on a segmenter would mean either inventing a fake wire
//! format nobody consumes or silently discarding real structure. [`Stage::In`]
//! is a generic associated type precisely so each implementor states its own
//! honest input shape — `&'a [u8]` for byte-stream stages, `(u32, Sample)` for
//! the segmenters — while [`Stage::Out`]/[`Stage::Error`] stay per-implementor
//! too. This is what lets one driver loop, generic only over `S: Stage`, span
//! both families (see `transmux/tests/it/stage.rs`'s `drive` helper).
//!
//! This module defines the trait plus its two small supporting types. The
//! media-plane byte stages implement it; see
//! `docs/superpowers/specs/2026-07-26-media-plane-architecture.md` for the
//! migration it shapes.
//!
//! # Clock: why a clock parameter at all
//!
//! A clockless `Stage` would only fit the container-demux family. Several
//! drive loops already take a clock and cannot be expressed without one:
//!
//! - `dvb_conformance::ConformanceMonitor::feed(pkt, t: Duration)` — TR 101 290
//!   timing indicators need packet arrival time.
//! - `mpeg_ts::mux::SiMux::poll_into(now: Timestamp, out)` — PSI/SI re-emission
//!   is rate-scheduled, not event-driven.
//! - `media_doctor::WatchState::feed_datagram(payload, clock: Duration)` —
//!   datagram-loss/jitter watch state needs wall-clock deltas.
//!
//! So the clock is on the trait from the start, not bolted on later.
//!
//! # `Timestamp`, not `std::time::Instant`
//!
//! `broadcast-common` is `#![no_std]` without the `std` feature, and
//! `std::time::Instant` cannot exist in that build. [`Timestamp`] is a plain
//! `u64` microsecond count from an epoch the *driver* chooses (not the stage).
//! A driver that does have `std` can derive one from a pair of `Instant`s via
//! [`Timestamp::from_instant`].
//!
//! Arithmetic on a *reading* saturates instead of panicking, since a stage
//! must never crash on a clock that runs backwards or wraps. A *deadline* is
//! [`Timestamp::checked_add`]: an instant that does not fit the clock can
//! never be reached, so it is a timer that never fires (`None`), never a
//! saturated instant that reads as "due now" forever (the time rule in
//! `docs/API-CONVENTIONS.md`).

use core::time::Duration;

use crate::units::{MICROS_PER_MILLI, NANOS_PER_MICRO};

/// Monotonic microseconds from an arbitrary epoch chosen by the driver.
///
/// Microseconds, not nanoseconds: this is a host's monotonic "now" and the
/// wall clock read beside it, never a media clock (those are
/// [`crate::clock33`]'s 90 kHz / 27 MHz values), and a microsecond resolves
/// every use here — a deadline, a reconnect instant, an inactivity timeout.
/// The epoch (what `0` means) is entirely up to whatever is driving the
/// [`Stage`] — stages must treat `Timestamp` as an opaque, monotonically
/// non-decreasing counter and never assume it relates to wall-clock time.
///
/// The microsecond count is private: one spelling of one thing
/// ([`from_micros`](Self::from_micros), [`from_nanos`](Self::from_nanos),
/// [`from_millis`](Self::from_millis), each rounding toward the later instant),
/// so a raw count cannot slip in beside them with different rounding.
///
/// Arithmetic on a reading saturates rather than panicking: a [`Stage`] must
/// not crash because a driver's clock underflowed or overflowed. A deadline is
/// [`checked_add`](Self::checked_add) instead, which reports "never fires".
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Default)]
pub struct Timestamp(u64);

impl Timestamp {
    /// The zero timestamp — whatever epoch the driver has chosen.
    pub const ZERO: Timestamp = Timestamp(0);

    /// Construct from a raw nanosecond count: the whole microsecond the
    /// reading falls in, rounded **up**, so the result never precedes the
    /// instant it names (the same rounding [`saturating_add_nanos`](Self::saturating_add_nanos)
    /// and [`from_instant`](Self::from_instant) use).
    pub const fn from_nanos(nanos: u64) -> Self {
        Timestamp(nanos.div_ceil(NANOS_PER_MICRO))
    }

    /// Construct from a whole-microsecond count.
    pub const fn from_micros(micros: u64) -> Self {
        Timestamp(micros)
    }

    /// The raw nanosecond count, from the whole microseconds this holds.
    ///
    /// Saturates at `u64::MAX` for a reading past 584 942 years; no host
    /// clock gets there.
    pub const fn as_nanos(self) -> u64 {
        if self.0 > u64::MAX / NANOS_PER_MICRO {
            u64::MAX
        } else {
            self.0 * NANOS_PER_MICRO
        }
    }

    /// Construct from a whole-millisecond count, saturating at `u64::MAX`
    /// microseconds.
    pub const fn from_millis(millis: u64) -> Self {
        Timestamp(millis.saturating_mul(MICROS_PER_MILLI))
    }

    /// The raw microsecond count since the driver's chosen epoch.
    pub const fn as_micros(self) -> u64 {
        self.0
    }

    /// The raw microsecond count in whole milliseconds, rounded down.
    pub const fn as_millis(self) -> u64 {
        self.0 / MICROS_PER_MILLI
    }

    /// `self - other`, saturating at zero instead of underflowing.
    pub const fn saturating_sub(self, other: Timestamp) -> Duration {
        Duration::from_micros(self.0.saturating_sub(other.0))
    }

    /// `self + nanos`, in nanoseconds: the result is the whole microsecond
    /// the nanosecond reading falls in (rounded up), saturating at `u64::MAX`.
    pub const fn saturating_add_nanos(self, nanos: u64) -> Self {
        let micros = nanos.div_ceil(NANOS_PER_MICRO);
        Timestamp(self.0.saturating_add(micros))
    }

    /// `self + span`, rounded up to the whole microsecond the span ends in (a
    /// 100 ms timeout added to microsecond `t` is the deadline at which
    /// `now - t >= 100 ms` first holds), or `None` when that instant does not
    /// fit in the clock.
    ///
    /// This is how a deadline is computed: an instant that does not fit can
    /// never be reached, which is a timer that never fires, not one that fires
    /// at the largest value the type can hold (see the time rule in
    /// `docs/API-CONVENTIONS.md`). Use [`saturating_add`](Self::saturating_add)
    /// only to clamp an instant to the end of the clock, never to make a
    /// deadline.
    pub fn checked_add(self, span: Duration) -> Option<Self> {
        let micros = u64::try_from(span.as_nanos().div_ceil(u128::from(NANOS_PER_MICRO))).ok()?;
        self.0.checked_add(micros).map(Timestamp)
    }

    /// `self + duration`, rounded up to the whole microsecond the span ends
    /// in, saturating at `u64::MAX`.
    ///
    /// Not for deadlines: a saturated deadline reads as "due now" forever. Use
    /// [`checked_add`](Self::checked_add) for those. This stays for clamping a
    /// clock reading to the end of the value range.
    pub fn saturating_add(self, duration: Duration) -> Self {
        let micros = u64::try_from(duration.as_nanos().div_ceil(u128::from(NANOS_PER_MICRO)))
            .unwrap_or(u64::MAX);
        Timestamp(self.0.saturating_add(micros))
    }
}

#[cfg(feature = "std")]
impl Timestamp {
    /// Derive a [`Timestamp`] from a `std::time::Instant` pair: `now - base`,
    /// expressed as microseconds since `base`, rounded up so two different
    /// instants never collapse onto the same reading.
    ///
    /// `base` is whatever fixed instant the driver picked as its epoch (e.g.
    /// "when this stage was constructed"); every subsequent call converts an
    /// `Instant` to a `Timestamp` on the same epoch. This is a `std`-only
    /// convenience so `std` callers are not forced to hand-roll the
    /// subtraction; `no_std` drivers construct `Timestamp` directly.
    pub fn from_instant(base: std::time::Instant, now: std::time::Instant) -> Self {
        let elapsed = now.saturating_duration_since(base);
        let micros = u64::try_from(elapsed.as_nanos().div_ceil(u128::from(NANOS_PER_MICRO)))
            .unwrap_or(u64::MAX);
        Timestamp(micros)
    }
}

/// A stage's hint about how much more input it can usefully accept right now.
///
/// This is advisory backpressure, not enforcement: a driver may call
/// [`Stage::feed`] with more than `want_bytes`, or while `saturated` is `true`,
/// and a well-behaved stage must still handle it correctly (buffering,
/// erroring, or blocking as its own contract dictates) — `Demand` only lets a
/// cooperative driver avoid doing so needlessly.
#[non_exhaustive]
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
pub struct Demand {
    /// How many more bytes this stage would like handed to [`Stage::feed`]
    /// before it is called again. `0` carries no meaning beyond "no
    /// particular preference"; it is not a demand for zero bytes.
    pub want_bytes: usize,
    /// `true` if the stage is currently full and would prefer not to receive
    /// more input until it has been polled / has had time to drain.
    pub saturated: bool,
}

impl Demand {
    /// Build a [`Demand`] requesting `want_bytes` more input, not saturated.
    pub const fn new(want_bytes: usize) -> Self {
        Demand {
            want_bytes,
            saturated: false,
        }
    }

    /// A [`Demand`] indicating the stage currently wants no more input.
    pub const fn saturated() -> Self {
        Demand {
            want_bytes: 0,
            saturated: true,
        }
    }

    /// [`Demand::saturated`] when `full`, otherwise the "no preference"
    /// [`Demand::default`].
    pub const fn saturated_if(full: bool) -> Self {
        if full {
            Self::saturated()
        } else {
            Demand::new(0)
        }
    }
}

/// The incremental-drive shape every streaming stage in the workspace adopts.
///
/// A `Stage` consumes input via [`feed`](Stage::feed) (the shape of that input
/// is [`In`](Stage::In), chosen per implementor — see the [module docs](self)),
/// produces typed output via repeated [`poll`](Stage::poll) calls (decoupled
/// from `feed` — a single `feed` may unlock zero, one, or many outputs), is
/// told there is no more input via [`finish`](Stage::finish), and may need to
/// act purely on the passage of time via [`next_deadline`](Stage::next_deadline)
/// / [`on_deadline`](Stage::on_deadline) (e.g. rate-scheduled re-emission with
/// no new input at all). [`demand`](Stage::demand) lets a driver ask before
/// feeding more.
///
/// See the [module docs](self) for the four divergent APIs this contract
/// unifies and the reasoning behind the `Timestamp` clock parameter.
///
/// # Drive loop
///
/// A typical driver loop:
///
/// ```
/// use broadcast_common::stage::{Demand, Stage, Timestamp};
/// use std::collections::VecDeque;
///
/// /// A stage that reverses each fed chunk and hands it back on poll.
/// struct Reverser {
///     queue: VecDeque<Vec<u8>>,
/// }
///
/// impl Stage for Reverser {
///     type In<'a> = &'a [u8];
///     type Out = Vec<u8>;
///     type Error = core::convert::Infallible;
///
///     fn feed(&mut self, input: &[u8], _now: Timestamp) -> Result<(), Self::Error> {
///         let mut chunk = input.to_vec();
///         chunk.reverse();
///         self.queue.push_back(chunk);
///         Ok(())
///     }
///
///     fn poll(&mut self) -> Option<Self::Out> {
///         self.queue.pop_front()
///     }
///
///     fn finish(&mut self) -> Result<(), Self::Error> {
///         Ok(())
///     }
///
///     fn next_deadline(&self) -> Option<Timestamp> {
///         None
///     }
///
///     fn on_deadline(&mut self, _now: Timestamp) {}
///
///     fn demand(&self) -> Demand {
///         Demand::new(4096)
///     }
/// }
///
/// let mut stage = Reverser { queue: Default::default() };
/// let mut outputs = Vec::new();
///
/// // feed → drain everything poll() currently has ready → repeat.
/// stage.feed(b"abc", Timestamp::from_nanos(0)).unwrap();
/// stage.feed(b"de", Timestamp::from_nanos(1_000)).unwrap();
/// while let Some(out) = stage.poll() {
///     outputs.push(out);
/// }
///
/// // No more input: flush anything the stage was holding back.
/// stage.finish().unwrap();
/// while let Some(out) = stage.poll() {
///     outputs.push(out);
/// }
///
/// assert_eq!(outputs, vec![vec![b'c', b'b', b'a'], vec![b'e', b'd']]);
/// ```
pub trait Stage {
    /// The shape of input this stage consumes via [`feed`](Stage::feed).
    ///
    /// A generic associated type, not a hardcoded `&[u8]`, so each
    /// implementor states its own honest input: byte-stream stages use
    /// `&'a [u8]`; sample-consuming stages (e.g. a segmenter) use an owned
    /// typed input such as `(u32, Sample)` that does not need to borrow
    /// anything, and can simply not use the `'a` parameter. See the
    /// [module docs](self) for why this is a GAT rather than a second
    /// `feed`-like method or an invented byte encoding.
    type In<'a>;
    /// The type of output this stage produces, pulled via [`poll`](Stage::poll).
    type Out;
    /// The error type this stage returns from [`feed`](Stage::feed) and
    /// [`finish`](Stage::finish).
    type Error;

    /// Feed more input into the stage at time `now`.
    ///
    /// May unlock output retrievable via subsequent [`poll`](Stage::poll)
    /// calls; a single `feed` call does not itself return output.
    fn feed(&mut self, input: Self::In<'_>, now: Timestamp) -> Result<(), Self::Error>;

    /// Pull one unit of ready output, if any is available.
    ///
    /// Callers should drain this in a `while let Some(_) = poll()` loop after
    /// every [`feed`](Stage::feed)/[`finish`](Stage::finish)/
    /// [`on_deadline`](Stage::on_deadline) call, since any of them may unlock
    /// more than one output.
    fn poll(&mut self) -> Option<Self::Out>;

    /// Signal that no more input will ever be fed.
    ///
    /// Lets the stage flush any output it was withholding (e.g. waiting for a
    /// boundary that will now never arrive). Idempotent: calling it more than
    /// once must not error or reprocess.
    fn finish(&mut self) -> Result<(), Self::Error>;

    /// The next point in time (on the same clock as [`feed`](Stage::feed)'s
    /// `now`) at which this stage has time-driven work to do, if any.
    ///
    /// A driver should call [`on_deadline`](Stage::on_deadline) once `now` has
    /// reached this value, even if no new input has arrived. `None` means the
    /// stage has nothing scheduled and only reacts to `feed`/`finish`, which
    /// is the default.
    fn next_deadline(&self) -> Option<Timestamp> {
        None
    }

    /// Let the stage act purely on the passage of time (no new bytes), e.g. a
    /// rate-scheduled re-emission or a timeout.
    ///
    /// May unlock output retrievable via subsequent [`poll`](Stage::poll)
    /// calls, exactly like [`feed`](Stage::feed). The default does nothing, for
    /// a stage whose [`next_deadline`](Stage::next_deadline) is always `None`.
    fn on_deadline(&mut self, _now: Timestamp) {}

    /// A hint about how much more input this stage would like right now.
    ///
    /// Advisory only — see [`Demand`]'s docs for what a driver may and may not
    /// assume from it. The default is [`Demand::default`], no preference.
    fn demand(&self) -> Demand {
        Demand::default()
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn the_clock_conversions_round_up_at_the_microsecond() {
        // `from_nanos` rounds up: the reading lands on the first microsecond at or after it, so a
        // converted instant is never earlier than the one it names (the property a wake depends
        // on: a wake computed from a deadline can never fire before it).
        assert_eq!(Timestamp::from_nanos(1_999), Timestamp::from_micros(2));
        assert_eq!(
            Timestamp::from_nanos(1_999_999),
            Timestamp::from_micros(2_000)
        );
        assert_eq!(Timestamp::from_nanos(1), Timestamp::from_micros(1));
        assert_eq!(Timestamp::from_nanos(1_000), Timestamp::from_micros(1));
        assert_eq!(
            Timestamp::from_nanos(u64::MAX),
            Timestamp::from_micros(u64::MAX / NANOS_PER_MICRO + 1)
        );
        // `saturating_add` rounds the span up: the deadline is the first microsecond at which
        // the whole span has passed, so `now - start >= span` holds there.
        assert_eq!(
            Timestamp::from_micros(10).saturating_add(Duration::from_nanos(1)),
            Timestamp::from_micros(11)
        );
        assert_eq!(
            Timestamp::from_micros(10).saturating_add(Duration::from_micros(100)),
            Timestamp::from_micros(110)
        );
        assert_eq!(
            Timestamp::from_micros(10).saturating_add_nanos(2_000),
            Timestamp::from_micros(12)
        );
        assert_eq!(
            Timestamp::from_micros(10).saturating_sub(Timestamp::from_micros(4)),
            Duration::from_micros(6)
        );
        // A deadline that fits; and one that does not, which is "never", not "the last instant".
        assert_eq!(
            Timestamp::from_micros(10).checked_add(Duration::from_micros(5)),
            Some(Timestamp::from_micros(15))
        );
        assert_eq!(
            Timestamp::from_micros(10).checked_add(Duration::from_nanos(1)),
            Some(Timestamp::from_micros(11))
        );
        assert_eq!(
            Timestamp::from_micros(u64::MAX).checked_add(Duration::from_micros(1)),
            None
        );
        assert_eq!(
            Timestamp::from_micros(u64::MAX - 1).checked_add(Duration::from_secs(30)),
            None
        );
    }

    #[test]
    fn the_clock_conversions_round_trip_whole_units() {
        assert_eq!(Timestamp::from_micros(1_500).as_micros(), 1_500);
        assert_eq!(Timestamp::from_millis(1_500).as_millis(), 1_500);
        assert_eq!(
            Timestamp::from_millis(1_500).as_nanos(),
            1_500 * NANOS_PER_MICRO * 1_000
        );
        // A reading rounds up to the whole microsecond it falls in (never before its
        // instant), and then down to the coarser milliseconds.
        assert_eq!(Timestamp::from_nanos(1_999).as_micros(), 2);
        assert_eq!(Timestamp::from_nanos(1_999_999).as_millis(), 2);
        // A count that would leave `u64` nanoseconds saturates instead of wrapping.
        assert_eq!(Timestamp::from_millis(u64::MAX).as_nanos(), u64::MAX);
        assert_eq!(Timestamp::from_micros(u64::MAX).as_nanos(), u64::MAX);
    }

    #[test]
    fn saturated_if_selects_saturated_or_default() {
        assert_eq!(
            super::Demand::saturated_if(true),
            super::Demand::saturated()
        );
        assert_eq!(super::Demand::saturated_if(false), super::Demand::default());
    }

    use super::*;
    use alloc::collections::VecDeque;
    use alloc::vec::Vec;
    use core::convert::Infallible;

    // A minimal `Stage` implementor using only `core`/`alloc` (no `std`),
    // proving the trait is genuinely usable from a `no_std` crate. It counts
    // fed bytes and, once a configured threshold is crossed OR a deadline
    // fires, emits the running total.
    struct ByteCounter {
        total: u64,
        threshold: u64,
        emitted_up_to: u64,
        pending: VecDeque<u64>,
        deadline: Option<Timestamp>,
        finished: bool,
    }

    impl ByteCounter {
        fn new(threshold: u64, deadline: Option<Timestamp>) -> Self {
            ByteCounter {
                total: 0,
                threshold,
                emitted_up_to: 0,
                pending: VecDeque::new(),
                deadline,
                finished: false,
            }
        }

        fn maybe_emit(&mut self) {
            if self.total.saturating_sub(self.emitted_up_to) >= self.threshold {
                self.pending.push_back(self.total);
                self.emitted_up_to = self.total;
            }
        }
    }

    impl Stage for ByteCounter {
        type In<'a> = &'a [u8];
        type Out = u64;
        type Error = Infallible;

        fn feed(&mut self, input: &[u8], _now: Timestamp) -> Result<(), Self::Error> {
            self.total += input.len() as u64;
            self.maybe_emit();
            Ok(())
        }

        fn poll(&mut self) -> Option<Self::Out> {
            self.pending.pop_front()
        }

        fn finish(&mut self) -> Result<(), Self::Error> {
            if !self.finished && self.total > self.emitted_up_to {
                self.pending.push_back(self.total);
                self.emitted_up_to = self.total;
            }
            self.finished = true;
            Ok(())
        }

        fn next_deadline(&self) -> Option<Timestamp> {
            self.deadline
        }

        fn on_deadline(&mut self, now: Timestamp) {
            if Some(now) >= self.deadline && self.total > self.emitted_up_to {
                self.pending.push_back(self.total);
                self.emitted_up_to = self.total;
                self.deadline = None;
            }
        }

        fn demand(&self) -> Demand {
            if self.total.saturating_sub(self.emitted_up_to) >= self.threshold {
                Demand::saturated()
            } else {
                Demand::new(self.threshold as usize)
            }
        }
    }

    #[test]
    fn no_std_implementor_drives_via_feed_poll() {
        let mut stage = ByteCounter::new(4, None);
        let mut outs: Vec<u64> = Vec::new();

        stage.feed(&[1, 2], Timestamp::from_nanos(0)).unwrap();
        assert_eq!(stage.poll(), None); // below threshold, nothing yet

        stage
            .feed(&[3, 4, 5], Timestamp::from_nanos(1_000))
            .unwrap();
        while let Some(out) = stage.poll() {
            outs.push(out);
        }
        assert_eq!(outs, alloc::vec![5]); // crossed threshold at total=5

        stage.finish().unwrap();
        // Nothing left unflushed since the last emission caught everything.
        assert_eq!(stage.poll(), None);
    }

    #[test]
    fn no_std_implementor_finish_flushes_remainder() {
        let mut stage = ByteCounter::new(100, None);
        stage.feed(&[1, 2, 3], Timestamp::from_nanos(0)).unwrap();
        assert_eq!(stage.poll(), None); // well below threshold

        stage.finish().unwrap();
        assert_eq!(stage.poll(), Some(3));
        assert_eq!(stage.poll(), None);
    }

    #[test]
    fn no_std_implementor_on_deadline_fires_without_new_input() {
        let deadline = Timestamp::from_nanos(5_000);
        let mut stage = ByteCounter::new(100, Some(deadline));
        stage.feed(&[1, 2, 3], Timestamp::from_nanos(0)).unwrap();
        assert_eq!(stage.next_deadline(), Some(deadline));
        assert_eq!(stage.poll(), None);

        stage.on_deadline(deadline);
        assert_eq!(stage.poll(), Some(3));
        assert_eq!(stage.next_deadline(), None);
    }

    #[test]
    fn demand_default_and_constructors() {
        let d = Demand::default();
        assert_eq!(d.want_bytes, 0);
        assert!(!d.saturated);

        let want = Demand::new(1024);
        assert_eq!(want.want_bytes, 1024);
        assert!(!want.saturated);

        let full = Demand::saturated();
        assert_eq!(full.want_bytes, 0);
        assert!(full.saturated);
    }

    #[test]
    fn timestamp_arithmetic_saturates_instead_of_panicking() {
        let zero = Timestamp::ZERO;
        let small = Timestamp::from_micros(5);
        let big = Timestamp::from_micros(u64::MAX);

        // Subtracting a larger timestamp from a smaller one saturates to 0,
        // never underflows/panics.
        assert_eq!(
            small.saturating_sub(Timestamp::from_micros(100)),
            Duration::from_micros(0)
        );
        assert_eq!(
            Timestamp::from_micros(100).saturating_sub(small),
            Duration::from_micros(95)
        );

        // Adding past u64::MAX saturates rather than wrapping/panicking.
        assert_eq!(
            big.saturating_add_nanos(10),
            Timestamp::from_micros(u64::MAX)
        );
        assert_eq!(zero.saturating_add_nanos(10), Timestamp::from_micros(1));

        // Duration-based saturating_add, including a Duration whose
        // nanoseconds exceed u64::MAX.
        assert_eq!(
            zero.saturating_add(Duration::from_nanos(10)),
            Timestamp::from_micros(1)
        );
        assert_eq!(
            big.saturating_add(Duration::from_secs(1)),
            Timestamp::from_micros(u64::MAX)
        );
        let huge = Duration::from_secs(u64::MAX);
        assert_eq!(zero.saturating_add(huge), Timestamp::from_micros(u64::MAX));
    }

    /// One spelling of one thing: a reading is built only by a constructor
    /// that rounds toward the later instant, and comes back out as the whole
    /// microsecond it holds.
    #[test]
    fn a_reading_is_built_only_by_the_rounding_constructors() {
        assert_eq!(Timestamp::from_micros(7).as_micros(), 7);
        assert_eq!(Timestamp::from_nanos(1_999).as_micros(), 2);
        assert_eq!(Timestamp::from_millis(7).as_micros(), 7_000);
    }

    #[test]
    fn timestamp_ordering_and_default() {
        assert!(Timestamp::from_micros(1) < Timestamp::from_micros(2));
        assert_eq!(Timestamp::default(), Timestamp::ZERO);
    }

    #[cfg(feature = "std")]
    #[test]
    fn from_instant_std_convenience() {
        let base = std::time::Instant::now();
        let later = base + Duration::from_millis(5);
        let ts = Timestamp::from_instant(base, later);
        assert_eq!(ts, Timestamp::from_micros(5_000));

        // A `now` before `base` saturates to zero rather than panicking.
        let earlier = base.checked_sub(Duration::from_millis(1)).unwrap_or(base);
        let ts2 = Timestamp::from_instant(base, earlier);
        assert_eq!(ts2, Timestamp::ZERO);
    }
}