broadcast-core 0.1.0

Frozen wire-format contract for the rust-broadcast crates: symmetric Parse/Serialize traits, checked field-width helpers, MSB-first bit I/O, reserved-bit fields, media timescales, the shared error kinds and the CENC scheme identity. 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
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
//! Wire field I/O shared by every parser and serializer (audit r04-O5): one
//! bounds check, so the per-width readers cannot drift apart. Every addition
//! is checked (no wrap on a hostile cursor).
//!
//! # Convention
//!
//! Every read and write is **checked** and returns a typed error; none
//! panics on short input:
//!
//! - [`Reader`] is a cursor over a borrowed byte slice: big-endian
//!   (`u16`, `u24`, `i32`, …, the wire default), little-endian (`u16_le`,
//!   `i24_le`, …), signed and 24/48-bit forms, sub-slices, fixed arrays and
//!   four-character codes, each a [`BufferTooShort`] naming the field when
//!   the input ends;
//! - [`Writer`] is the matching cursor over a caller-sized output buffer,
//!   each write an [`OutputBufferTooSmall`] when it does not fit, and a
//!   24-bit write a [`FieldOverflow`] for a value wider than the field;
//! - [`field`] borrows a fixed-size array at an absolute offset, so a header
//!   read once and then picked apart with constant indices is bounds-checked
//!   by its type.
//!
//! The checked forms return the shared error kinds, so a caller converts
//! them into its own error type through the `#[from]` wrapper every wire
//! crate declares.

use crate::error::{BufferTooShort, FieldOverflow, OutputBufferTooSmall};

/// Byte width of the 24-bit fields (ISO/IEC 14496-12:2026 `size` prefixes,
/// `esds` lengths).
pub const U24_LEN: usize = 3;
/// Byte width of the 48-bit `hvcC` `general_constraint_indicator_flags`.
const U48_LEN: usize = 6;

/// Take the next `n` bytes at `*cursor`, advancing it. `BufferTooShort` (with the
/// byte count needed) if fewer remain.
fn take<'a>(
    bytes: &'a [u8],
    cursor: &mut usize,
    n: usize,
    what: &'static str,
) -> Result<&'a [u8], BufferTooShort> {
    let end = cursor.saturating_add(n);
    let slice = bytes.get(*cursor..end).ok_or(BufferTooShort {
        need: end,
        have: bytes.len(),
        what,
    })?;
    *cursor = end;
    Ok(slice)
}

/// Byte width of a four-character code (an ISOBMFF box type, a CENC
/// `schm.scheme_type`).
pub const FOURCC_LEN: usize = core::mem::size_of::<u32>();
/// Bits a 24-bit field is shifted up by to put its sign bit at bit 31.
const I24_SIGN_SHIFT: u32 = u32::BITS - (U24_LEN as u32 * u8::BITS);

/// The `N` bytes at absolute offset `off` of `bytes`, as a fixed-size array.
///
/// # Errors
/// [`BufferTooShort`] naming `what` when fewer than `N` bytes remain at
/// `off` (`need` is `off + N`, saturating).
pub fn field<'a, const N: usize>(
    bytes: &'a [u8],
    off: usize,
    what: &'static str,
) -> Result<&'a [u8; N], BufferTooShort> {
    Reader::at(bytes, off).array::<N>(what)
}

/// A checked cursor over a borrowed byte slice.
///
/// Every read advances the cursor on success and leaves it unchanged on
/// failure; a read past the end is a [`BufferTooShort`] whose `need` is the
/// absolute end of the field (saturating) and whose `have` is the slice
/// length.
#[derive(Debug, Clone)]
pub struct Reader<'a> {
    bytes: &'a [u8],
    pos: usize,
}

impl<'a> Reader<'a> {
    /// A cursor at the first byte of `bytes`.
    #[must_use]
    pub const fn new(bytes: &'a [u8]) -> Self {
        Self { bytes, pos: 0 }
    }

    /// A cursor at absolute offset `pos` of `bytes`. A `pos` past the end is
    /// allowed: the first read reports it.
    #[must_use]
    pub const fn at(bytes: &'a [u8], pos: usize) -> Self {
        Self { bytes, pos }
    }

    /// The absolute offset of the next byte read.
    #[must_use]
    pub const fn position(&self) -> usize {
        self.pos
    }

    /// Bytes left after the cursor (zero once it is at or past the end).
    #[must_use]
    pub const fn remaining(&self) -> usize {
        self.bytes.len().saturating_sub(self.pos)
    }

    /// The next `n` bytes.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than `n` remain.
    pub fn bytes(&mut self, n: usize, what: &'static str) -> Result<&'a [u8], BufferTooShort> {
        take(self.bytes, &mut self.pos, n, what)
    }

    /// The next `N` bytes as a fixed-size array.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than `N` remain.
    pub fn array<const N: usize>(
        &mut self,
        what: &'static str,
    ) -> Result<&'a [u8; N], BufferTooShort> {
        let slice = self.bytes(N, what)?;
        slice.first_chunk::<N>().ok_or(BufferTooShort {
            need: self.pos,
            have: self.bytes.len(),
            what,
        })
    }

    /// Advance past `n` bytes.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than `n` remain.
    pub fn skip(&mut self, n: usize, what: &'static str) -> Result<(), BufferTooShort> {
        self.bytes(n, what).map(|_| ())
    }

    /// Every byte after the cursor (empty at or past the end); the cursor
    /// moves to the end.
    pub fn rest(&mut self) -> &'a [u8] {
        let rest = self.bytes.get(self.pos..).unwrap_or_default();
        self.pos = self.pos.max(self.bytes.len());
        rest
    }

    /// A four-character code (the raw four bytes, not a number).
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than four bytes remain.
    pub fn fourcc(&mut self, what: &'static str) -> Result<[u8; FOURCC_LEN], BufferTooShort> {
        self.array::<FOURCC_LEN>(what).copied()
    }

    /// An unsigned byte.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` at the end of the input.
    pub fn u8(&mut self, what: &'static str) -> Result<u8, BufferTooShort> {
        self.array::<1>(what).map(|&[b]| b)
    }

    /// A signed byte.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` at the end of the input.
    pub fn i8(&mut self, what: &'static str) -> Result<i8, BufferTooShort> {
        self.array::<1>(what).map(|b| i8::from_be_bytes(*b))
    }

    /// A big-endian `u16`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than two bytes remain.
    pub fn u16(&mut self, what: &'static str) -> Result<u16, BufferTooShort> {
        self.array(what).map(|b| u16::from_be_bytes(*b))
    }

    /// A big-endian 24-bit unsigned value, widened to `u32`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than three bytes remain.
    pub fn u24(&mut self, what: &'static str) -> Result<u32, BufferTooShort> {
        self.array::<U24_LEN>(what)
            .map(|&[b0, b1, b2]| u32::from_be_bytes([0, b0, b1, b2]))
    }

    /// A big-endian `u32`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than four bytes remain.
    pub fn u32(&mut self, what: &'static str) -> Result<u32, BufferTooShort> {
        self.array(what).map(|b| u32::from_be_bytes(*b))
    }

    /// A big-endian 48-bit unsigned value, widened to `u64`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than six bytes remain.
    pub fn u48(&mut self, what: &'static str) -> Result<u64, BufferTooShort> {
        self.array::<U48_LEN>(what).map(|b| {
            b.iter()
                .fold(0u64, |acc, &x| (acc << u8::BITS) | u64::from(x))
        })
    }

    /// A big-endian `u64`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than eight bytes remain.
    pub fn u64(&mut self, what: &'static str) -> Result<u64, BufferTooShort> {
        self.array(what).map(|b| u64::from_be_bytes(*b))
    }

    /// A big-endian `i16`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than two bytes remain.
    pub fn i16(&mut self, what: &'static str) -> Result<i16, BufferTooShort> {
        self.array(what).map(|b| i16::from_be_bytes(*b))
    }

    /// A big-endian two's-complement 24-bit value, sign-extended to `i32`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than three bytes remain.
    pub fn i24(&mut self, what: &'static str) -> Result<i32, BufferTooShort> {
        self.u24(what).map(sign_extend_24)
    }

    /// A big-endian `i32`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than four bytes remain.
    pub fn i32(&mut self, what: &'static str) -> Result<i32, BufferTooShort> {
        self.array(what).map(|b| i32::from_be_bytes(*b))
    }

    /// A big-endian `i64`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than eight bytes remain.
    pub fn i64(&mut self, what: &'static str) -> Result<i64, BufferTooShort> {
        self.array(what).map(|b| i64::from_be_bytes(*b))
    }

    /// A little-endian `u16`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than two bytes remain.
    pub fn u16_le(&mut self, what: &'static str) -> Result<u16, BufferTooShort> {
        self.array(what).map(|b| u16::from_le_bytes(*b))
    }

    /// A little-endian 24-bit unsigned value, widened to `u32`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than three bytes remain.
    pub fn u24_le(&mut self, what: &'static str) -> Result<u32, BufferTooShort> {
        self.array::<U24_LEN>(what)
            .map(|&[b0, b1, b2]| u32::from_le_bytes([b0, b1, b2, 0]))
    }

    /// A little-endian `u32`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than four bytes remain.
    pub fn u32_le(&mut self, what: &'static str) -> Result<u32, BufferTooShort> {
        self.array(what).map(|b| u32::from_le_bytes(*b))
    }

    /// A little-endian `u64`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than eight bytes remain.
    pub fn u64_le(&mut self, what: &'static str) -> Result<u64, BufferTooShort> {
        self.array(what).map(|b| u64::from_le_bytes(*b))
    }

    /// A little-endian `i16`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than two bytes remain.
    pub fn i16_le(&mut self, what: &'static str) -> Result<i16, BufferTooShort> {
        self.array(what).map(|b| i16::from_le_bytes(*b))
    }

    /// A little-endian two's-complement 24-bit value, sign-extended to `i32`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than three bytes remain.
    pub fn i24_le(&mut self, what: &'static str) -> Result<i32, BufferTooShort> {
        self.u24_le(what).map(sign_extend_24)
    }

    /// A little-endian `i32`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than four bytes remain.
    pub fn i32_le(&mut self, what: &'static str) -> Result<i32, BufferTooShort> {
        self.array(what).map(|b| i32::from_le_bytes(*b))
    }

    /// A little-endian `i64`.
    ///
    /// # Errors
    /// [`BufferTooShort`] naming `what` when fewer than eight bytes remain.
    pub fn i64_le(&mut self, what: &'static str) -> Result<i64, BufferTooShort> {
        self.array(what).map(|b| i64::from_le_bytes(*b))
    }
}

/// The low 24 bits of `raw` as a two's-complement value.
const fn sign_extend_24(raw: u32) -> i32 {
    (raw << I24_SIGN_SHIFT).cast_signed() >> I24_SIGN_SHIFT
}

/// The three low bytes of `value`, after checking it fits an unsigned 24-bit
/// field.
fn u24_bytes(value: u32, field: &'static str) -> Result<[u8; U24_LEN], FieldOverflow> {
    let fitted = crate::len::fit_bits(u64::from(value), U24_LEN as u32 * u8::BITS, field)?;
    let [.., b0, b1, b2] = fitted.to_be_bytes();
    Ok([b0, b1, b2])
}

/// The three low bytes of `value`, after checking it fits a signed 24-bit
/// field (`-2^23 ..= 2^23 - 1`); an out-of-range value is a [`FieldOverflow`]
/// carrying its magnitude and the field's positive maximum.
fn i24_bytes(value: i32, field: &'static str) -> Result<[u8; U24_LEN], FieldOverflow> {
    if sign_extend_24(value.cast_unsigned()) != value {
        return Err(FieldOverflow {
            field,
            value: u64::from(value.unsigned_abs()),
            max: u64::from(I24_MAX),
        });
    }
    let [_, b0, b1, b2] = value.to_be_bytes();
    Ok([b0, b1, b2])
}

/// The largest value of a signed 24-bit field.
const I24_MAX: u32 = u32::MAX >> (I24_SIGN_SHIFT + 1);

/// A checked cursor over a caller-sized output buffer.
///
/// Every write advances the cursor on success and leaves the buffer and the
/// cursor unchanged on failure; a write past the end is an
/// [`OutputBufferTooSmall`] whose `need` is the absolute end of the field
/// (saturating) and whose `have` is the buffer length.
#[derive(Debug)]
pub struct Writer<'a> {
    buf: &'a mut [u8],
    pos: usize,
}

impl<'a> Writer<'a> {
    /// A cursor at the first byte of `buf`.
    #[must_use]
    pub const fn new(buf: &'a mut [u8]) -> Self {
        Self { buf, pos: 0 }
    }

    /// A cursor at absolute offset `pos` of `buf`. A `pos` past the end is
    /// allowed: the first write reports it.
    #[must_use]
    pub const fn at(buf: &'a mut [u8], pos: usize) -> Self {
        Self { buf, pos }
    }

    /// The absolute offset of the next byte written.
    #[must_use]
    pub const fn position(&self) -> usize {
        self.pos
    }

    /// Bytes left after the cursor (zero once it is at or past the end).
    #[must_use]
    pub const fn remaining(&self) -> usize {
        self.buf.len().saturating_sub(self.pos)
    }

    /// Copy `bytes` at the cursor; `what` names the field in the error.
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] when fewer than `bytes.len()` bytes remain.
    pub fn bytes(&mut self, bytes: &[u8], what: &'static str) -> Result<(), OutputBufferTooSmall> {
        let end = self.pos.saturating_add(bytes.len());
        let have = self.buf.len();
        let slot = self
            .buf
            .get_mut(self.pos..end)
            .ok_or(OutputBufferTooSmall {
                need: end,
                have,
                what,
            })?;
        slot.copy_from_slice(bytes);
        self.pos = end;
        Ok(())
    }

    /// `n` zero bytes, the explicit form of a run of reserved or padding
    /// bytes the specification fixes at zero.
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] when fewer than `n` bytes remain.
    pub fn zeros(&mut self, n: usize, what: &'static str) -> Result<(), OutputBufferTooSmall> {
        let end = self.pos.saturating_add(n);
        let have = self.buf.len();
        let slot = self
            .buf
            .get_mut(self.pos..end)
            .ok_or(OutputBufferTooSmall::new(end, have, what))?;
        slot.fill(0);
        self.pos = end;
        Ok(())
    }

    /// A four-character code (the raw four bytes).
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] when fewer than four bytes remain.
    pub fn fourcc(
        &mut self,
        code: [u8; FOURCC_LEN],
        what: &'static str,
    ) -> Result<(), OutputBufferTooSmall> {
        self.bytes(&code, what)
    }

    /// An unsigned byte.
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] at the end of the buffer.
    pub fn u8(&mut self, value: u8, what: &'static str) -> Result<(), OutputBufferTooSmall> {
        self.bytes(&[value], what)
    }

    /// A signed byte.
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] at the end of the buffer.
    pub fn i8(&mut self, value: i8, what: &'static str) -> Result<(), OutputBufferTooSmall> {
        self.bytes(&value.to_be_bytes(), what)
    }

    /// A big-endian `u16`.
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] when fewer than two bytes remain.
    pub fn u16(&mut self, value: u16, what: &'static str) -> Result<(), OutputBufferTooSmall> {
        self.bytes(&value.to_be_bytes(), what)
    }

    /// A big-endian 24-bit unsigned field; `field` also names it in an
    /// [`OutputBufferTooSmall`].
    ///
    /// # Errors
    /// [`FieldOverflow`] naming `field` when `value` needs more than 24 bits;
    /// [`OutputBufferTooSmall`] when fewer than three bytes remain.
    pub fn u24<E>(&mut self, value: u32, field: &'static str) -> Result<(), E>
    where
        E: From<FieldOverflow> + From<OutputBufferTooSmall>,
    {
        let bytes = u24_bytes(value, field)?;
        Ok(self.bytes(&bytes, field)?)
    }

    /// A big-endian `u32`.
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] when fewer than four bytes remain.
    pub fn u32(&mut self, value: u32, what: &'static str) -> Result<(), OutputBufferTooSmall> {
        self.bytes(&value.to_be_bytes(), what)
    }

    /// A big-endian 48-bit unsigned field; `field` also names it in an
    /// [`OutputBufferTooSmall`].
    ///
    /// # Errors
    /// [`FieldOverflow`] naming `field` when `value` needs more than 48 bits;
    /// [`OutputBufferTooSmall`] when fewer than six bytes remain.
    pub fn u48<E>(&mut self, value: u64, field: &'static str) -> Result<(), E>
    where
        E: From<FieldOverflow> + From<OutputBufferTooSmall>,
    {
        let fitted = crate::len::fit_bits(value, U48_LEN as u32 * u8::BITS, field)?;
        let wide = fitted.to_be_bytes();
        Ok(self.bytes(&wide[wide.len() - U48_LEN..], field)?)
    }

    /// A big-endian `u64`.
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] when fewer than eight bytes remain.
    pub fn u64(&mut self, value: u64, what: &'static str) -> Result<(), OutputBufferTooSmall> {
        self.bytes(&value.to_be_bytes(), what)
    }

    /// A big-endian `i16`.
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] when fewer than two bytes remain.
    pub fn i16(&mut self, value: i16, what: &'static str) -> Result<(), OutputBufferTooSmall> {
        self.bytes(&value.to_be_bytes(), what)
    }

    /// A big-endian two's-complement 24-bit field.
    ///
    /// # Errors
    /// [`FieldOverflow`] naming `field` when `value` is outside
    /// `-2^23 ..= 2^23 - 1`; [`OutputBufferTooSmall`] when fewer than three
    /// bytes remain.
    pub fn i24<E>(&mut self, value: i32, field: &'static str) -> Result<(), E>
    where
        E: From<FieldOverflow> + From<OutputBufferTooSmall>,
    {
        let bytes = i24_bytes(value, field)?;
        Ok(self.bytes(&bytes, field)?)
    }

    /// A big-endian `i32`.
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] when fewer than four bytes remain.
    pub fn i32(&mut self, value: i32, what: &'static str) -> Result<(), OutputBufferTooSmall> {
        self.bytes(&value.to_be_bytes(), what)
    }

    /// A big-endian `i64`.
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] when fewer than eight bytes remain.
    pub fn i64(&mut self, value: i64, what: &'static str) -> Result<(), OutputBufferTooSmall> {
        self.bytes(&value.to_be_bytes(), what)
    }

    /// A little-endian `u16`.
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] when fewer than two bytes remain.
    pub fn u16_le(&mut self, value: u16, what: &'static str) -> Result<(), OutputBufferTooSmall> {
        self.bytes(&value.to_le_bytes(), what)
    }

    /// A little-endian 24-bit unsigned field.
    ///
    /// # Errors
    /// [`FieldOverflow`] naming `field` when `value` needs more than 24 bits;
    /// [`OutputBufferTooSmall`] when fewer than three bytes remain.
    pub fn u24_le<E>(&mut self, value: u32, field: &'static str) -> Result<(), E>
    where
        E: From<FieldOverflow> + From<OutputBufferTooSmall>,
    {
        let mut bytes = u24_bytes(value, field)?;
        bytes.reverse();
        Ok(self.bytes(&bytes, field)?)
    }

    /// A little-endian two's-complement 24-bit field.
    ///
    /// # Errors
    /// [`FieldOverflow`] naming `field` when `value` is outside
    /// `-2^23 ..= 2^23 - 1`; [`OutputBufferTooSmall`] when fewer than three
    /// bytes remain.
    pub fn i24_le<E>(&mut self, value: i32, field: &'static str) -> Result<(), E>
    where
        E: From<FieldOverflow> + From<OutputBufferTooSmall>,
    {
        let mut bytes = i24_bytes(value, field)?;
        bytes.reverse();
        Ok(self.bytes(&bytes, field)?)
    }

    /// A little-endian `u32`.
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] when fewer than four bytes remain.
    pub fn u32_le(&mut self, value: u32, what: &'static str) -> Result<(), OutputBufferTooSmall> {
        self.bytes(&value.to_le_bytes(), what)
    }

    /// A little-endian `u64`.
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] when fewer than eight bytes remain.
    pub fn u64_le(&mut self, value: u64, what: &'static str) -> Result<(), OutputBufferTooSmall> {
        self.bytes(&value.to_le_bytes(), what)
    }

    /// A little-endian `i16`.
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] when fewer than two bytes remain.
    pub fn i16_le(&mut self, value: i16, what: &'static str) -> Result<(), OutputBufferTooSmall> {
        self.bytes(&value.to_le_bytes(), what)
    }

    /// A little-endian `i32`.
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] when fewer than four bytes remain.
    pub fn i32_le(&mut self, value: i32, what: &'static str) -> Result<(), OutputBufferTooSmall> {
        self.bytes(&value.to_le_bytes(), what)
    }

    /// A little-endian `i64`.
    ///
    /// # Errors
    /// [`OutputBufferTooSmall`] when fewer than eight bytes remain.
    pub fn i64_le(&mut self, value: i64, what: &'static str) -> Result<(), OutputBufferTooSmall> {
        self.bytes(&value.to_le_bytes(), what)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn exact_ok_short_err() {
        let b = [0u8, 0, 1, 2, 3, 4, 5, 6, 7, 8];
        assert_eq!(Reader::at(&b, 2).u64("t").unwrap(), 0x0102_0304_0506_0708);
        assert!(matches!(
            Reader::at(&b, 3).u64("t"),
            Err(BufferTooShort {
                need: 11,
                have: 10,
                what: "t"
            })
        ));
        assert!(matches!(
            Reader::at(&b, usize::MAX).u64("t"),
            Err(BufferTooShort {
                need: usize::MAX,
                ..
            })
        ));
    }

    #[test]
    fn readers_read_at_their_offsets() {
        let b = [0x12, 0x34, 0x56, 0x78];
        assert_eq!(Reader::at(&b, 0).u16("t").unwrap(), 0x1234);
        assert_eq!(Reader::at(&b, 0).u32("t").unwrap(), 0x1234_5678);
        assert_eq!(Reader::at(&b, 2).u16("t").unwrap(), 0x5678);
        assert_eq!(Reader::at(&b, 1).u24("t").unwrap(), 0x0034_5678);
        assert_eq!(Reader::at(&b, 0).u32("t").unwrap(), 0x1234_5678);
        assert_eq!(
            Reader::at(&b, 0).fourcc("t").unwrap(),
            [0x12, 0x34, 0x56, 0x78]
        );
    }

    #[test]
    fn short_slice_reports_need_and_have() {
        assert!(matches!(
            Reader::at(&[0u8; 3], 0).u32("t"),
            Err(BufferTooShort {
                need: 4,
                have: 3,
                what: "t"
            })
        ));
    }

    fn short(need: usize, have: usize, what: &'static str) -> BufferTooShort {
        BufferTooShort { need, have, what }
    }

    #[test]
    fn reader_reads_every_width_and_endianness() {
        let b = [0x80, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07];
        assert_eq!(Reader::new(&b).u8("t"), Ok(0x80));
        assert_eq!(Reader::new(&b).i8("t"), Ok(-128));
        assert_eq!(Reader::new(&b).u16("t"), Ok(0x8001));
        assert_eq!(Reader::new(&b).i16("t"), Ok(-32767));
        assert_eq!(Reader::new(&b).u24("t"), Ok(0x80_0102));
        assert_eq!(Reader::new(&b).i24("t"), Ok(-0x7F_FEFE));
        assert_eq!(Reader::new(&b).u32("t"), Ok(0x8001_0203));
        assert_eq!(Reader::new(&b).i32("t"), Ok(0x8001_0203_u32.cast_signed()));
        assert_eq!(Reader::new(&b).u48("t"), Ok(0x8001_0203_0405));
        assert_eq!(Reader::new(&b).u64("t"), Ok(0x8001_0203_0405_0607));
        assert_eq!(
            Reader::new(&b).i64("t"),
            Ok(0x8001_0203_0405_0607_u64.cast_signed())
        );
        assert_eq!(Reader::new(&b).u16_le("t"), Ok(0x0180));
        assert_eq!(Reader::new(&b).i16_le("t"), Ok(0x0180));
        assert_eq!(Reader::new(&b).u24_le("t"), Ok(0x02_0180));
        assert_eq!(Reader::new(&b).i24_le("t"), Ok(0x02_0180));
        assert_eq!(Reader::new(&b).u32_le("t"), Ok(0x0302_0180));
        assert_eq!(Reader::new(&b).i32_le("t"), Ok(0x0302_0180));
        assert_eq!(Reader::new(&b).u64_le("t"), Ok(0x0706_0504_0302_0180));
        assert_eq!(Reader::new(&b).i64_le("t"), Ok(0x0706_0504_0302_0180));
        assert_eq!(Reader::new(&b).fourcc("t"), Ok([0x80, 0x01, 0x02, 0x03]));
    }

    #[test]
    fn signed_24_bit_reads_cover_the_sign_boundary() {
        assert_eq!(Reader::new(&[0x7F, 0xFF, 0xFF]).i24("t"), Ok(0x7F_FFFF));
        assert_eq!(Reader::new(&[0x80, 0x00, 0x00]).i24("t"), Ok(-0x80_0000));
        assert_eq!(Reader::new(&[0xFF, 0xFF, 0xFF]).i24("t"), Ok(-1));
        assert_eq!(Reader::new(&[0, 0, 0]).i24("t"), Ok(0));
        assert_eq!(Reader::new(&[0xFF, 0xFF, 0xFF]).u24("t"), Ok(0xFF_FFFF));
        assert_eq!(Reader::new(&[0x00, 0x00, 0x80]).i24_le("t"), Ok(-0x80_0000));
    }

    #[test]
    fn reader_advances_and_reports_the_field_one_byte_short() {
        let b = [1, 2, 3, 4, 5];
        let mut r = Reader::new(&b);
        assert_eq!(r.u16("a"), Ok(0x0102));
        assert_eq!(r.position(), 2);
        assert_eq!(r.remaining(), 3);
        assert_eq!(r.u32("b"), Err(short(6, 5, "b")));
        assert_eq!(r.position(), 2, "a failed read leaves the cursor alone");
        assert_eq!(r.u24("c"), Ok(0x03_0405));
        assert_eq!(r.remaining(), 0);
        assert_eq!(r.u8("d"), Err(short(6, 5, "d")));
        assert_eq!(r.rest(), &[] as &[u8]);
    }

    #[test]
    fn reader_on_empty_input_and_past_the_end() {
        assert_eq!(Reader::new(&[]).u8("e"), Err(short(1, 0, "e")));
        assert_eq!(Reader::new(&[]).bytes(0, "e"), Ok(&[] as &[u8]));
        let mut far = Reader::at(&[1, 2], 9);
        assert_eq!(far.remaining(), 0);
        assert_eq!(far.rest(), &[] as &[u8]);
        assert_eq!(far.position(), 9);
        assert_eq!(
            Reader::at(&[1, 2], usize::MAX).u16("m"),
            Err(short(usize::MAX, 2, "m"))
        );
    }

    #[test]
    fn reader_slices_skips_and_takes_the_rest() {
        let b = [9, 8, 7, 6];
        let mut r = Reader::new(&b);
        assert_eq!(r.bytes(1, "x"), Ok(&[9][..]));
        assert_eq!(r.skip(1, "x"), Ok(()));
        assert_eq!(r.array::<1>("x"), Ok(&[7]));
        assert_eq!(r.skip(2, "x"), Err(short(5, 4, "x")));
        assert_eq!(r.rest(), &[6]);
        assert_eq!(r.remaining(), 0);
    }

    #[test]
    fn field_borrows_a_fixed_array_or_names_the_shortfall() {
        let b = [1, 2, 3, 4];
        assert_eq!(field::<2>(&b, 2, "f"), Ok(&[3, 4]));
        assert_eq!(field::<0>(&b, 4, "f"), Ok(&[]));
        assert_eq!(field::<2>(&b, 3, "f"), Err(short(5, 4, "f")));
        assert_eq!(
            field::<1>(&b, usize::MAX, "f"),
            Err(short(usize::MAX, 4, "f"))
        );
    }

    #[derive(Debug, PartialEq, Eq)]
    enum WriteErr {
        Small(OutputBufferTooSmall),
        Wide(FieldOverflow),
    }
    impl From<OutputBufferTooSmall> for WriteErr {
        fn from(e: OutputBufferTooSmall) -> Self {
            WriteErr::Small(e)
        }
    }
    impl From<FieldOverflow> for WriteErr {
        fn from(e: FieldOverflow) -> Self {
            WriteErr::Wide(e)
        }
    }

    #[test]
    fn writer_round_trips_through_the_reader() {
        let mut buf = [0u8; 80];
        let mut w = Writer::new(&mut buf);
        w.u8(0xAB, "t").unwrap();
        w.i8(-2, "t").unwrap();
        w.u16(0x1234, "t").unwrap();
        w.i16(-3, "t").unwrap();
        w.u24::<WriteErr>(0xFF_FFFF, "u24").unwrap();
        w.i24::<WriteErr>(-0x80_0000, "i24").unwrap();
        w.u32(0xDEAD_BEEF, "t").unwrap();
        w.i32(-4, "t").unwrap();
        w.u64(u64::MAX, "t").unwrap();
        w.i64(i64::MIN, "t").unwrap();
        w.u16_le(0x1234, "t").unwrap();
        w.i16_le(-5, "t").unwrap();
        w.u32_le(0x0102_0304, "t").unwrap();
        w.i32_le(-6, "t").unwrap();
        w.u64_le(7, "t").unwrap();
        w.i64_le(-8, "t").unwrap();
        w.fourcc(*b"moov", "t").unwrap();
        let end = w.position();
        let mut r = Reader::new(&buf[..end]);
        assert_eq!(r.u8("t"), Ok(0xAB));
        assert_eq!(r.i8("t"), Ok(-2));
        assert_eq!(r.u16("t"), Ok(0x1234));
        assert_eq!(r.i16("t"), Ok(-3));
        assert_eq!(r.u24("t"), Ok(0xFF_FFFF));
        assert_eq!(r.i24("t"), Ok(-0x80_0000));
        assert_eq!(r.u32("t"), Ok(0xDEAD_BEEF));
        assert_eq!(r.i32("t"), Ok(-4));
        assert_eq!(r.u64("t"), Ok(u64::MAX));
        assert_eq!(r.i64("t"), Ok(i64::MIN));
        assert_eq!(r.u16_le("t"), Ok(0x1234));
        assert_eq!(r.i16_le("t"), Ok(-5));
        assert_eq!(r.u32_le("t"), Ok(0x0102_0304));
        assert_eq!(r.i32_le("t"), Ok(-6));
        assert_eq!(r.u64_le("t"), Ok(7));
        assert_eq!(r.i64_le("t"), Ok(-8));
        assert_eq!(r.fourcc("t"), Ok(*b"moov"));
        assert_eq!(r.remaining(), 0);
    }

    #[test]
    fn writer_refuses_a_field_one_byte_too_long_and_keeps_its_cursor() {
        let mut buf = [0xEEu8; 3];
        let mut w = Writer::new(&mut buf);
        assert_eq!(w.u16(0x0102, "a"), Ok(()));
        assert_eq!(
            w.u16(0x0304, "b"),
            Err(OutputBufferTooSmall {
                need: 4,
                have: 3,
                what: "b"
            })
        );
        assert_eq!(w.position(), 2);
        assert_eq!(w.remaining(), 1);
        assert_eq!(w.u8(5, "c"), Ok(()));
        assert_eq!(
            w.u8(6, "d"),
            Err(OutputBufferTooSmall {
                need: 4,
                have: 3,
                what: "d"
            })
        );
        assert_eq!(buf, [1, 2, 5]);
        let mut empty = [0u8; 0];
        assert_eq!(
            Writer::new(&mut empty).u8(1, "e"),
            Err(OutputBufferTooSmall {
                need: 1,
                have: 0,
                what: "e"
            })
        );
        assert_eq!(
            Writer::at(&mut buf, usize::MAX).u8(1, "m"),
            Err(OutputBufferTooSmall {
                need: usize::MAX,
                have: 3,
                what: "m"
            })
        );
    }

    #[test]
    fn writer_24_bit_fields_refuse_values_outside_the_field() {
        let mut buf = [0u8; 3];
        let mut w = Writer::new(&mut buf);
        assert_eq!(
            w.u24::<WriteErr>(0x100_0000, "len"),
            Err(WriteErr::Wide(FieldOverflow {
                field: "len",
                value: 0x100_0000,
                max: 0xFF_FFFF
            }))
        );
        assert_eq!(
            w.i24::<WriteErr>(0x80_0000, "cts"),
            Err(WriteErr::Wide(FieldOverflow {
                field: "cts",
                value: 0x80_0000,
                max: 0x7F_FFFF
            }))
        );
        assert_eq!(
            w.i24::<WriteErr>(-0x80_0001, "cts"),
            Err(WriteErr::Wide(FieldOverflow {
                field: "cts",
                value: 0x80_0001,
                max: 0x7F_FFFF
            }))
        );
        assert_eq!(w.i24::<WriteErr>(0x7F_FFFF, "cts"), Ok(()));
        assert_eq!(buf, [0x7F, 0xFF, 0xFF]);
        let mut two = [0u8; 2];
        assert_eq!(
            Writer::new(&mut two).u24::<WriteErr>(0, "len"),
            Err(WriteErr::Small(OutputBufferTooSmall {
                need: 3,
                have: 2,
                what: "len"
            }))
        );
    }

    #[test]
    fn writer_widths_mirror_the_reader() {
        let mut buf = [0xAAu8; 15];
        let mut w = Writer::new(&mut buf);
        assert_eq!(w.u48::<WriteErr>(0x0102_0304_0506, "u48"), Ok(()));
        assert_eq!(w.u24_le::<WriteErr>(0x07_0809, "u24le"), Ok(()));
        assert_eq!(w.i24_le::<WriteErr>(-2, "i24le"), Ok(()));
        assert_eq!(w.zeros(3, "pad"), Ok(()));
        assert_eq!(w.remaining(), 0);
        let mut r = Reader::new(&buf);
        assert_eq!(r.u48("u48"), Ok(0x0102_0304_0506));
        assert_eq!(r.u24_le("u24le"), Ok(0x07_0809));
        assert_eq!(r.i24_le("i24le"), Ok(-2));
        assert_eq!(r.rest(), [0, 0, 0]);
        let mut six = [0u8; 6];
        assert_eq!(
            Writer::new(&mut six).u48::<WriteErr>(1 << 48, "u48"),
            Err(WriteErr::Wide(FieldOverflow::new(
                "u48",
                1 << 48,
                (1 << 48) - 1
            )))
        );
        let mut two = [0u8; 2];
        assert_eq!(
            Writer::new(&mut two).zeros(3, "pad"),
            Err(OutputBufferTooSmall::new(3, 2, "pad"))
        );
        assert_eq!(two, [0, 0]);
    }
}