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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
//! Big-endian, MSB-first bit reader/writer for dense sub-byte wire fields.
//!
//! DVB physical-layer signalling (e.g. the EN 302 755 ยง7.2 L1-pre / L1-post
//! tables) packs many fields that are not byte-aligned โ€” 1-bit flags, 3-bit
//! codes, 18-bit sizes โ€” back-to-back with no padding. [`BitReader`] and
//! [`BitWriter`] walk such a stream a field at a time, most-significant bit
//! first within each field and within each byte, which is the bit order used
//! throughout the DVB/MPEG specifications.
//!
//! Both sides are symmetric: bits written by [`BitWriter::write_bits`] read
//! back identically through [`BitReader::read_bits`]. The writer sets *and*
//! clears each target bit, so the destination buffer need not be pre-zeroed.
//!
//! ```
//! use broadcast_core::bits::{BitReader, BitWriter};
//!
//! let mut buf = [0u8; 2];
//! let mut w = BitWriter::new(&mut buf);
//! w.write_bits(0b101, 3, "flags").unwrap();   // 3-bit field
//! w.write_bits(0x1FF, 9, "size").unwrap();   // 9-bit field โ€” crosses the byte boundary
//! assert_eq!(w.bits_written(), 12);
//!
//! let mut r = BitReader::new(&buf);
//! assert_eq!(r.read_bits(3, "flags").unwrap(), 0b101);
//! assert_eq!(r.read_bits(9, "size").unwrap(), 0x1FF);
//! ```

use alloc::vec::Vec;

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

/// Bits in one byte: the unit every `BufferTooShort` count is expressed in.
const BITS_PER_BYTE: usize = 8;
/// Index of the most-significant bit within a byte (MSB-first order).
const BYTE_MSB_INDEX: usize = BITS_PER_BYTE - 1;
/// The `what` of a bit-position failure ([`BitReader::starting_at`],
/// [`BitWriter::starting_at`]).
const START_POSITION: &str = "bit start position";
/// The `what` of the zero padding [`BitWriter::align_to_byte`] writes.
const ALIGN_PADDING: &str = "byte alignment padding";
/// Largest field a single read/write call accepts (`u64` width).
const MAX_FIELD_BITS: u32 = u64::BITS;

/// Error from a [`BitReader`] / [`BitWriter`] / [`BitBuf`] operation, one
/// shared kind per failure.
///
/// A read past the end is [`BufferTooShort`] and a write past the end
/// [`OutputBufferTooSmall`], both counted in whole bytes: `need` is the larger
/// of the bits needed and the bits left, rounded up to a byte, and `have` the
/// smaller, rounded down, so a partial byte never counts as a whole one
/// available. A width outside `0..=64` is [`InvalidValue`]; a value wider than
/// its field is [`FieldOverflow`].
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BitError {
    /// A read needed more bits than the buffer holds.
    BufferTooShort(BufferTooShort),
    /// A write needed more bits than the buffer can hold.
    OutputBufferTooSmall(OutputBufferTooSmall),
    /// A field width outside `0..=64`, or a whole-byte write off a byte
    /// boundary.
    InvalidValue(InvalidValue),
    /// A value has bits set above its field width.
    FieldOverflow(FieldOverflow),
}

impl core::fmt::Display for BitError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            BitError::BufferTooShort(e) => e.fmt(f),
            BitError::OutputBufferTooSmall(e) => e.fmt(f),
            BitError::InvalidValue(e) => e.fmt(f),
            BitError::FieldOverflow(e) => e.fmt(f),
        }
    }
}
impl core::error::Error for BitError {}

impl From<BitError> for WireError {
    fn from(e: BitError) -> Self {
        match e {
            BitError::BufferTooShort(e) => e.into(),
            BitError::OutputBufferTooSmall(e) => e.into(),
            BitError::InvalidValue(e) => e.into(),
            BitError::FieldOverflow(e) => e.into(),
        }
    }
}

impl BitError {
    /// Convert into a crate's own error through the shared kinds, without
    /// loss. A crate whose `Error` wraps the four kinds with `#[from]` gets
    /// this with no code of its own: `.map_err(BitError::into_error)`.
    pub fn into_error<E>(self) -> E
    where
        E: From<BufferTooShort>
            + From<OutputBufferTooSmall>
            + From<InvalidValue>
            + From<FieldOverflow>,
    {
        match self {
            BitError::BufferTooShort(e) => E::from(e),
            BitError::OutputBufferTooSmall(e) => E::from(e),
            BitError::InvalidValue(e) => E::from(e),
            BitError::FieldOverflow(e) => E::from(e),
        }
    }
}

/// The byte counts of a bit shortfall: the larger of the two bit counts
/// rounded up, the smaller rounded down.
const fn shortfall_bytes(needed_bits: usize, remaining_bits: usize) -> (usize, usize) {
    let (more, less) = if needed_bits > remaining_bits {
        (needed_bits, remaining_bits)
    } else {
        (remaining_bits, needed_bits)
    };
    (more.div_ceil(BITS_PER_BYTE), less / BITS_PER_BYTE)
}

/// A read of `needed_bits` with `remaining_bits` left.
const fn read_short(what: &'static str, needed_bits: usize, remaining_bits: usize) -> BitError {
    let (need, have) = shortfall_bytes(needed_bits, remaining_bits);
    BitError::BufferTooShort(BufferTooShort::new(need, have, what))
}

/// A write of `needed_bits` with `remaining_bits` of room.
const fn write_short(
    what: &'static str,
    needed_bits: usize,
    remaining_bits: usize,
) -> OutputBufferTooSmall {
    let (need, have) = shortfall_bytes(needed_bits, remaining_bits);
    OutputBufferTooSmall::new(need, have, what)
}

/// A requested width outside `0..=64`.
const fn too_many_bits(what: &'static str, requested: u32) -> BitError {
    BitError::InvalidValue(InvalidValue::new(
        what,
        requested as u64,
        "field wider than 64 bits",
    ))
}

/// Whole bytes a buffer must hold for `n` more bits starting at bit
/// `bit_pos`: `ceil((bit_pos + n) / 8)`, saturating instead of wrapping.
///
/// This is the `need` of a [`BufferTooShort`] reported against the whole
/// buffer (with `have` its length), the form a bit-field parser uses when it
/// names the absolute size a read would fit in rather than the shortfall.
#[must_use]
pub const fn bytes_needed(bit_pos: usize, n: usize) -> usize {
    bit_pos.saturating_add(n).div_ceil(BITS_PER_BYTE)
}

/// Reads fields MSB-first from a borrowed byte slice.
#[derive(Debug, Clone)]
pub struct BitReader<'a> {
    data: &'a [u8],
    /// Absolute bit cursor from the start of `data` (0 = MSB of byte 0).
    bit_pos: usize,
}

impl<'a> BitReader<'a> {
    /// Create a reader positioned at the first bit of `data`.
    #[must_use]
    pub fn new(data: &'a [u8]) -> Self {
        Self { data, bit_pos: 0 }
    }

    /// Create a reader positioned `bit_pos` bits into `data`.
    ///
    /// # Errors
    /// [`BitError::BufferTooShort`] if `bit_pos` is past the end of `data`.
    pub fn starting_at(data: &'a [u8], bit_pos: usize) -> Result<Self, BitError> {
        let mut reader = Self::new(data);
        reader.skip_bits(bit_pos, START_POSITION)?;
        Ok(reader)
    }

    /// Total bits in the backing buffer.
    #[must_use]
    pub fn total_bits(&self) -> usize {
        self.data.len() * BITS_PER_BYTE
    }

    /// Bits already consumed.
    #[must_use]
    pub fn bits_read(&self) -> usize {
        self.bit_pos
    }

    /// Bits not yet consumed.
    #[must_use]
    pub fn bits_remaining(&self) -> usize {
        self.total_bits() - self.bit_pos
    }

    /// `true` if the cursor sits on a byte boundary.
    #[must_use]
    pub fn is_byte_aligned(&self) -> bool {
        self.bit_pos.is_multiple_of(BITS_PER_BYTE)
    }

    /// Read `n` bits (`0..=64`) MSB-first into the low bits of a `u64`.
    ///
    /// `read_bits(0)` returns `0` and consumes nothing.
    ///
    /// # Errors
    /// [`BitError::InvalidValue`] if `n > 64`; [`BitError::BufferTooShort`] if
    /// fewer than `n` bits remain.
    pub fn read_bits(&mut self, n: u32, what: &'static str) -> Result<u64, BitError> {
        if n > MAX_FIELD_BITS {
            return Err(too_many_bits(what, n));
        }
        if n == 0 {
            return Ok(0);
        }
        let need = n as usize;
        let remaining = self.bits_remaining();
        if need > remaining {
            return Err(read_short(what, need, remaining));
        }
        let mut value: u64 = 0;
        for _ in 0..n {
            let byte = self.data[self.bit_pos / BITS_PER_BYTE];
            let bit_index = BYTE_MSB_INDEX - (self.bit_pos % BITS_PER_BYTE); // MSB first within the byte
            let bit = (byte >> bit_index) & 1;
            value = (value << 1) | u64::from(bit);
            self.bit_pos += 1;
        }
        Ok(value)
    }

    /// Read a single bit as a `bool` (`1` โ†’ `true`).
    ///
    /// # Errors
    /// [`BitError::BufferTooShort`] if no bits remain.
    pub fn read_bool(&mut self, what: &'static str) -> Result<bool, BitError> {
        Ok(self.read_bits(1, what)? != 0)
    }

    /// Skip `n` bits without interpreting them.
    ///
    /// # Errors
    /// [`BitError::BufferTooShort`] if fewer than `n` bits remain. The cursor is
    /// then left at the end of the buffer, never past it, so `bits_remaining`
    /// stays a real count after a failed skip.
    pub fn skip_bits(&mut self, n: usize, what: &'static str) -> Result<(), BitError> {
        let remaining = self.bits_remaining();
        if n > remaining {
            self.bit_pos = self.total_bits();
            return Err(read_short(what, n, remaining));
        }
        self.bit_pos += n;
        Ok(())
    }

    /// Advance to the next byte boundary (no-op if already aligned).
    pub fn align_to_byte(&mut self) {
        let rem = self.bit_pos % BITS_PER_BYTE;
        if rem != 0 {
            self.bit_pos += BITS_PER_BYTE - rem;
        }
    }
}

/// Writes fields MSB-first into a borrowed mutable byte slice.
///
/// Each bit is explicitly set or cleared, so `buf` need not be zeroed first.
#[derive(Debug)]
pub struct BitWriter<'a> {
    data: &'a mut [u8],
    bit_pos: usize,
}

impl<'a> BitWriter<'a> {
    /// Create a writer positioned at the first bit of `data`.
    #[must_use]
    pub fn new(data: &'a mut [u8]) -> Self {
        Self { data, bit_pos: 0 }
    }

    /// Create a writer positioned `bit_pos` bits into `data`.
    ///
    /// # Errors
    /// [`BitError::OutputBufferTooSmall`] if `bit_pos` is past the end of `data`.
    pub fn starting_at(data: &'a mut [u8], bit_pos: usize) -> Result<Self, BitError> {
        let capacity = data.len() * BITS_PER_BYTE;
        if bit_pos > capacity {
            return Err(BitError::OutputBufferTooSmall(write_short(
                START_POSITION,
                bit_pos,
                capacity,
            )));
        }
        Ok(Self { data, bit_pos })
    }

    /// Total bits the backing buffer can hold.
    #[must_use]
    pub fn capacity_bits(&self) -> usize {
        self.data.len() * BITS_PER_BYTE
    }

    /// Bits written so far.
    #[must_use]
    pub fn bits_written(&self) -> usize {
        self.bit_pos
    }

    /// `true` if the cursor sits on a byte boundary.
    #[must_use]
    pub fn is_byte_aligned(&self) -> bool {
        self.bit_pos.is_multiple_of(BITS_PER_BYTE)
    }

    /// Write the low `n` bits (`0..=64`) of `value`, MSB-first.
    ///
    /// `write_bits(_, 0)` writes nothing.
    ///
    /// # Errors
    /// [`BitError::InvalidValue`] if `n > 64`; [`BitError::FieldOverflow`] if
    /// `value` has bits set above bit `n-1`; [`BitError::OutputBufferTooSmall`]
    /// if the buffer cannot hold `n` more bits.
    pub fn write_bits(&mut self, value: u64, n: u32, what: &'static str) -> Result<(), BitError> {
        if n > MAX_FIELD_BITS {
            return Err(too_many_bits(what, n));
        }
        if n < MAX_FIELD_BITS && value >= (1u64 << n) {
            return Err(BitError::FieldOverflow(FieldOverflow::new(
                what,
                value,
                (1u64 << n) - 1,
            )));
        }
        self.put(value, n, what)
            .map_err(BitError::OutputBufferTooSmall)
    }

    /// Write the low `n` bits of `value` (already checked to fit, `n <= 64`).
    fn put(&mut self, value: u64, n: u32, what: &'static str) -> Result<(), OutputBufferTooSmall> {
        let need = n as usize;
        let remaining = self.capacity_bits() - self.bit_pos;
        if need > remaining {
            return Err(write_short(what, need, remaining));
        }
        for i in (0..n).rev() {
            let bit = ((value >> i) & 1) as u8;
            let byte_idx = self.bit_pos / BITS_PER_BYTE;
            let bit_index = BYTE_MSB_INDEX - (self.bit_pos % BITS_PER_BYTE);
            if bit == 1 {
                self.data[byte_idx] |= 1 << bit_index;
            } else {
                self.data[byte_idx] &= !(1u8 << bit_index);
            }
            self.bit_pos += 1;
        }
        Ok(())
    }

    /// Write a single bit from a `bool`.
    ///
    /// # Errors
    /// [`BitError::OutputBufferTooSmall`] if the buffer is full.
    pub fn write_bool(&mut self, value: bool, what: &'static str) -> Result<(), BitError> {
        self.write_bits(u64::from(value), 1, what)
    }

    /// Write `value` into an `n`-bit spec field named `field`, with the
    /// failure in a crate's own error through the shared kinds.
    ///
    /// The range check is [`fit_bits`](crate::len::fit_bits), so a value that
    /// does not fit (or a width of 0 or above 64) is a [`FieldOverflow`]
    /// naming the field and its maximum; a full buffer is the
    /// [`OutputBufferTooSmall`].
    ///
    /// # Errors
    /// [`FieldOverflow`] for a value or width the field cannot hold;
    /// [`OutputBufferTooSmall`] when fewer than `n` bits of the buffer remain.
    pub fn write_field<E>(&mut self, value: u64, n: u32, field: &'static str) -> Result<(), E>
    where
        E: From<FieldOverflow> + From<OutputBufferTooSmall>,
    {
        let value = crate::len::fit_bits(value, n, field)?;
        Ok(self.put(value, n, field)?)
    }

    /// Pad with zero bits up to the next byte boundary (no-op if aligned).
    ///
    /// # Errors
    /// [`BitError::OutputBufferTooSmall`] if the buffer cannot hold the padding.
    pub fn align_to_byte(&mut self) -> Result<(), BitError> {
        let rem = self.bit_pos % BITS_PER_BYTE;
        if rem != 0 {
            self.write_bits(0, (BITS_PER_BYTE - rem) as u32, ALIGN_PADDING)?;
        }
        Ok(())
    }
}

/// A growable MSB-first bit writer that owns its bytes.
///
/// The write side of [`BitWriter`] for callers that do not know the output
/// size up front: every field goes through [`BitWriter::write_bits`] over the
/// bytes written so far plus room for the new field, so range and width
/// checks, and bit order, are the slice writer's own.
#[derive(Debug, Clone, Default)]
pub struct BitBuf {
    data: Vec<u8>,
    bit_len: usize,
}

impl BitBuf {
    /// An empty buffer.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Bits written so far.
    #[must_use]
    pub fn bits_written(&self) -> usize {
        self.bit_len
    }

    /// `true` if the cursor sits on a byte boundary.
    #[must_use]
    pub fn is_byte_aligned(&self) -> bool {
        self.bit_len.is_multiple_of(BITS_PER_BYTE)
    }

    /// Append the low `n` bits (`0..=64`) of `value`, MSB-first.
    ///
    /// # Errors
    /// [`BitError::InvalidValue`] if `n > 64`; [`BitError::FieldOverflow`] if
    /// `value` has bits set above bit `n-1`. The buffer is unchanged on error.
    pub fn write_bits(&mut self, value: u64, n: u32, what: &'static str) -> Result<(), BitError> {
        if n > MAX_FIELD_BITS {
            return Err(too_many_bits(what, n));
        }
        let grown = (self.bit_len + n as usize).div_ceil(BITS_PER_BYTE);
        let previous = self.data.len();
        self.data.resize(grown, 0);
        let written = BitWriter::starting_at(&mut self.data, self.bit_len)
            .and_then(|mut writer| writer.write_bits(value, n, what));
        if written.is_err() {
            self.data.truncate(previous);
            return written;
        }
        self.bit_len += n as usize;
        Ok(())
    }

    /// Append `value` into an `n`-bit spec field named `field`, with the
    /// failure in a crate's own error through the shared kinds, as
    /// [`BitWriter::write_field`] does. The buffer is unchanged on error.
    ///
    /// # Errors
    /// [`FieldOverflow`] for a value or width the field cannot hold. The
    /// buffer grows, so [`OutputBufferTooSmall`] is only in the bound for
    /// symmetry with [`BitWriter::write_field`].
    pub fn write_field<E>(&mut self, value: u64, n: u32, field: &'static str) -> Result<(), E>
    where
        E: From<FieldOverflow> + From<OutputBufferTooSmall>,
    {
        let value = crate::len::fit_bits(value, n, field)?;
        let grown = (self.bit_len + n as usize).div_ceil(BITS_PER_BYTE);
        let previous = self.data.len();
        self.data.resize(grown, 0);
        let mut writer = BitWriter {
            data: &mut self.data,
            bit_pos: self.bit_len,
        };
        if let Err(e) = writer.put(value, n, field) {
            self.data.truncate(previous);
            return Err(e.into());
        }
        self.bit_len += n as usize;
        Ok(())
    }

    /// Append a single bit from a `bool`.
    ///
    /// # Errors
    /// Never fails in practice; the signature matches [`BitWriter::write_bool`].
    pub fn write_bool(&mut self, value: bool, what: &'static str) -> Result<(), BitError> {
        self.write_bits(u64::from(value), 1, what)
    }

    /// Pad with zero bits up to the next byte boundary (no-op if aligned).
    pub fn align_to_byte(&mut self) {
        self.bit_len = self.data.len() * BITS_PER_BYTE;
    }

    /// Append whole bytes at a byte boundary.
    ///
    /// # Errors
    /// [`BitError::InvalidValue`] if the cursor is not byte aligned (`value`
    /// is the bits to the next boundary); nothing is written.
    pub fn write_bytes(&mut self, bytes: &[u8], what: &'static str) -> Result<(), BitError> {
        if !self.is_byte_aligned() {
            return Err(BitError::InvalidValue(InvalidValue::new(
                what,
                (BITS_PER_BYTE - self.bit_len % BITS_PER_BYTE) as u64,
                "whole bytes written off a byte boundary",
            )));
        }
        self.data.extend_from_slice(bytes);
        self.bit_len += bytes.len() * BITS_PER_BYTE;
        Ok(())
    }

    /// The bytes written so far, a final partial byte zero-padded.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.data
    }

    /// Consume the buffer into its bytes, a final partial byte zero-padded.
    #[must_use]
    pub fn into_vec(self) -> Vec<u8> {
        self.data
    }
}

#[cfg(test)]
mod tests {
    // Binary literals here are grouped by *wire field boundaries* (e.g.
    // `0b1_01_10101` = a 1-bit, 2-bit and 5-bit field) to document the layout,
    // not by nibbles.
    use super::*;

    #[test]
    fn single_byte_fields_round_trip() {
        let mut buf = [0u8; 1];
        let mut w = BitWriter::new(&mut buf);
        w.write_bits(0b1, 1, "field").unwrap();
        w.write_bits(0b01, 2, "field").unwrap();
        w.write_bits(0b10101, 5, "field").unwrap();
        assert_eq!(w.bits_written(), 8);
        // 1 01 10101 = 0b1_01_10101 = 0xB5
        assert_eq!(buf[0], 0b10110101);

        let mut r = BitReader::new(&buf);
        assert_eq!(r.read_bits(1, "field").unwrap(), 0b1);
        assert_eq!(r.read_bits(2, "field").unwrap(), 0b01);
        assert_eq!(r.read_bits(5, "field").unwrap(), 0b10101);
        assert_eq!(r.bits_remaining(), 0);
    }

    #[test]
    fn field_crossing_byte_boundary_round_trips() {
        // An 18-bit field like L1_POST_SIZE, offset so it straddles 3 bytes.
        let mut buf = [0u8; 4];
        let mut w = BitWriter::new(&mut buf);
        w.write_bits(0b101, 3, "field").unwrap();
        w.write_bits(0b10_1010_1010_1010_1011, 18, "field").unwrap();
        let val18 = 0b10_1010_1010_1010_1011u64;

        let mut r = BitReader::new(&buf);
        assert_eq!(r.read_bits(3, "field").unwrap(), 0b101);
        assert_eq!(r.read_bits(18, "field").unwrap(), val18);
    }

    #[test]
    fn read_zero_bits_is_noop() {
        let buf = [0xFFu8];
        let mut r = BitReader::new(&buf);
        assert_eq!(r.read_bits(0, "field").unwrap(), 0);
        assert_eq!(r.bits_read(), 0);
    }

    #[test]
    fn full_64_bit_field() {
        let mut buf = [0u8; 8];
        let value = 0xDEAD_BEEF_CAFE_F00Du64;
        let mut w = BitWriter::new(&mut buf);
        w.write_bits(value, 64, "value").unwrap();
        let mut r = BitReader::new(&buf);
        assert_eq!(r.read_bits(64, "field").unwrap(), value);
    }

    #[test]
    fn read_past_end_errs() {
        let buf = [0xFFu8]; // 8 bits
        let mut r = BitReader::new(&buf);
        r.read_bits(7, "field").unwrap();
        let err = r.read_bits(2, "err").unwrap_err();
        assert_eq!(
            err,
            BitError::BufferTooShort(BufferTooShort::new(1, 0, "err"))
        );
    }

    fn short_of(error: BitError) -> BufferTooShort {
        match error.into_error::<Kind>() {
            Kind::Short(short) => short,
            other => panic!("not a shortfall: {other:?}"),
        }
    }

    #[test]
    fn an_overrun_converts_to_a_byte_shortfall() {
        // Seven bits left, sixteen wanted: two whole bytes needed and none of
        // the seven bits left is a whole one.
        let buf = [0xFFu8];
        let mut r = BitReader::new(&buf);
        r.read_bits(1, "field").unwrap();
        assert_eq!(
            short_of(r.read_bits(16, "field").unwrap_err()),
            BufferTooShort {
                need: 2,
                have: 0,
                what: "field",
            }
        );

        // One bit left, one more wanted: a single byte both spans and holds
        // the shortfall, so a partial byte rounds up and down to it.
        let mut r = BitReader::new(&buf);
        r.read_bits(7, "field").unwrap();
        assert_eq!(
            short_of(r.read_bits(2, "field").unwrap_err()),
            BufferTooShort {
                need: 1,
                have: 0,
                what: "field",
            }
        );

        // A whole byte available and a two-byte read wanted: the shortfall is
        // one whole byte, so both counts agree on it.
        let buf = [0u8; 2];
        let mut r = BitReader::new(&buf);
        r.read_bits(8, "field").unwrap();
        assert_eq!(
            short_of(r.read_bits(12, "field").unwrap_err()),
            BufferTooShort {
                need: 2,
                have: 1,
                what: "field",
            }
        );
    }

    #[test]
    fn a_position_and_a_width_convert_alike() {
        // An adapter reporting the position (12 bits needed) and one reporting
        // the width (12 bits wanted) both mean two bytes.
        for error in [read_short("field", 12, 8), read_short("field", 12, 4)] {
            assert_eq!(short_of(error).need, 2);
        }
    }

    #[test]
    fn a_non_shortage_is_never_a_short_buffer() {
        for error in [
            too_many_bits("field", 65),
            BitError::FieldOverflow(FieldOverflow::new("field", 0b100, 0b11)),
        ] {
            assert!(!matches!(error.into_error::<Kind>(), Kind::Short(_)));
        }
    }

    #[test]
    fn a_failed_skip_leaves_the_cursor_at_the_end() {
        let buf = [0xFFu8];
        let mut r = BitReader::new(&buf);
        r.skip_bits(3, "field").unwrap();
        assert_eq!(
            r.skip_bits(9, "field"),
            Err(BitError::BufferTooShort(BufferTooShort::new(2, 0, "field")))
        );
        assert_eq!(r.bits_remaining(), 0, "never past the end");
        assert_eq!(r.bits_read(), r.total_bits());
    }

    #[test]
    fn read_too_many_bits_errs() {
        let buf = [0u8; 16];
        let mut r = BitReader::new(&buf);
        assert_eq!(
            r.read_bits(65, "field").unwrap_err(),
            BitError::InvalidValue(InvalidValue::new("field", 65, "field wider than 64 bits"))
        );
    }

    #[test]
    fn write_value_too_wide_errs() {
        let mut buf = [0u8; 4];
        let mut w = BitWriter::new(&mut buf);
        // 0b100 needs 3 bits; asking for 2 must fail.
        assert_eq!(
            w.write_bits(0b100, 2, "field").unwrap_err(),
            BitError::FieldOverflow(FieldOverflow::new("field", 0b100, 0b11))
        );
    }

    #[test]
    fn write_past_end_errs() {
        let mut buf = [0u8; 1];
        let mut w = BitWriter::new(&mut buf);
        w.write_bits(0, 7, "field").unwrap();
        assert_eq!(
            w.write_bits(0b11, 2, "field").unwrap_err(),
            BitError::OutputBufferTooSmall(OutputBufferTooSmall::new(1, 0, "field"))
        );
    }

    #[test]
    fn writer_does_not_require_zeroed_buffer() {
        // Pre-fill with 0xFF; writer must clear bits it writes as 0.
        let mut buf = [0xFFu8; 1];
        let mut w = BitWriter::new(&mut buf);
        w.write_bits(0b0000_0000, 8, "field").unwrap();
        assert_eq!(buf[0], 0x00);
    }

    #[test]
    fn bool_round_trips() {
        let mut buf = [0u8; 1];
        let mut w = BitWriter::new(&mut buf);
        w.write_bool(true, "true").unwrap();
        w.write_bool(false, "false").unwrap();
        w.write_bool(true, "true").unwrap();
        let mut r = BitReader::new(&buf);
        assert!(r.read_bool("field").unwrap());
        assert!(!r.read_bool("field").unwrap());
        assert!(r.read_bool("field").unwrap());
    }

    #[test]
    fn skip_and_align() {
        let buf = [0b1010_1100u8, 0b1111_0000];
        let mut r = BitReader::new(&buf);
        r.read_bits(2, "field").unwrap(); // at bit 2
        r.skip_bits(3, "field").unwrap(); // at bit 5
        assert!(!r.is_byte_aligned());
        r.align_to_byte(); // at bit 8
        assert!(r.is_byte_aligned());
        assert_eq!(r.read_bits(4, "field").unwrap(), 0b1111);
    }

    #[test]
    fn writer_align_pads_with_zero() {
        let mut buf = [0xFFu8; 1];
        let mut w = BitWriter::new(&mut buf);
        w.write_bits(0b101, 3, "field").unwrap();
        w.align_to_byte().unwrap();
        assert_eq!(w.bits_written(), 8);
        assert_eq!(buf[0], 0b1010_0000); // 3 data bits + 5 zero pad
    }

    #[test]
    fn exhaustive_small_width_round_trip() {
        // Every value of every width 1..=16 reads back identically.
        for bits in 1u32..=16 {
            let max = if bits == 64 {
                u64::MAX
            } else {
                (1u64 << bits) - 1
            };
            for value in [0u64, 1, max, max / 2] {
                let mut buf = [0u8; 8];
                let mut w = BitWriter::new(&mut buf);
                w.write_bits(value, bits, "value").unwrap();
                let mut r = BitReader::new(&buf);
                assert_eq!(
                    r.read_bits(bits, "field").unwrap(),
                    value,
                    "round-trip failed: value={value:#x} bits={bits}"
                );
            }
        }
    }

    #[test]
    fn starting_at_resumes_mid_byte() {
        let buf = [0b1010_1100u8, 0b1111_0000];
        let mut r = BitReader::starting_at(&buf, 6).unwrap();
        assert_eq!(r.read_bits(6, "field").unwrap(), 0b00_1111);
        assert_eq!(
            BitReader::starting_at(&buf, 16).unwrap().bits_remaining(),
            0
        );
        assert_eq!(
            BitReader::starting_at(&buf, 17).unwrap_err(),
            BitError::BufferTooShort(BufferTooShort::new(3, 2, "bit start position"))
        );

        let mut out = [0xFFu8; 2];
        let mut w = BitWriter::starting_at(&mut out, 4).unwrap();
        w.write_bits(0, 8, "field").unwrap();
        assert_eq!(out, [0xF0, 0x0F]);
        let mut out = [0u8; 1];
        assert_eq!(
            BitWriter::starting_at(&mut out, 9).unwrap_err(),
            BitError::OutputBufferTooSmall(OutputBufferTooSmall::new(2, 1, "bit start position"))
        );
    }

    #[test]
    fn bit_buf_matches_the_slice_writer() {
        let fields = [
            (0b101u64, 3u32),
            (0x1FF, 9),
            (0, 1),
            (0xDEAD_BEEF, 32),
            (1, 1),
        ];
        let mut buf = BitBuf::new();
        let mut reference = [0u8; 8];
        let mut w = BitWriter::new(&mut reference);
        for (value, n) in fields {
            buf.write_bits(value, n, "value").unwrap();
            w.write_bits(value, n, "value").unwrap();
        }
        assert_eq!(buf.bits_written(), 46);
        assert_eq!(buf.as_bytes(), &reference[..6]);
        assert_eq!(buf.as_bytes(), [0xbf, 0xf6, 0xf5, 0x6d, 0xf7, 0x7c]);
    }

    #[test]
    fn bit_buf_edges() {
        let mut buf = BitBuf::new();
        assert_eq!(
            buf.write_bits(0b100, 2, "field"),
            Err(BitError::FieldOverflow(FieldOverflow::new(
                "field", 0b100, 0b11
            )))
        );
        assert_eq!(
            buf.write_bits(0, 65, "field"),
            Err(too_many_bits("field", 65))
        );
        assert_eq!(buf.bits_written(), 0);
        assert!(buf.as_bytes().is_empty());

        buf.write_bits(u64::MAX, 64, "field").unwrap();
        assert_eq!(buf.as_bytes(), [0xFF; 8]);
        buf.write_bool(true, "true").unwrap();
        assert!(!buf.is_byte_aligned());
        assert_eq!(
            buf.write_bytes(&[1], "field"),
            Err(BitError::InvalidValue(InvalidValue::new(
                "field",
                7,
                "whole bytes written off a byte boundary"
            )))
        );
        buf.align_to_byte();
        assert!(buf.is_byte_aligned());
        buf.write_bytes(&[0xAA], "field").unwrap();
        assert_eq!(buf.bits_written(), 80);
        assert_eq!(
            buf.into_vec(),
            [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x80, 0xAA]
        );
    }

    #[derive(Debug, PartialEq, Eq)]
    enum Kind {
        Short(BufferTooShort),
        Out(OutputBufferTooSmall),
        Invalid(InvalidValue),
        Overflow(FieldOverflow),
    }
    impl From<OutputBufferTooSmall> for Kind {
        fn from(e: OutputBufferTooSmall) -> Self {
            Kind::Out(e)
        }
    }
    impl From<BufferTooShort> for Kind {
        fn from(e: BufferTooShort) -> Self {
            Kind::Short(e)
        }
    }
    impl From<InvalidValue> for Kind {
        fn from(e: InvalidValue) -> Self {
            Kind::Invalid(e)
        }
    }
    impl From<FieldOverflow> for Kind {
        fn from(e: FieldOverflow) -> Self {
            Kind::Overflow(e)
        }
    }

    #[test]
    fn bytes_needed_rounds_up_and_saturates() {
        assert_eq!(bytes_needed(0, 0), 0);
        assert_eq!(bytes_needed(0, 1), 1);
        assert_eq!(bytes_needed(0, 8), 1);
        assert_eq!(bytes_needed(0, 9), 2);
        assert_eq!(bytes_needed(7, 1), 1);
        assert_eq!(bytes_needed(7, 2), 2);
        assert_eq!(bytes_needed(16, 0), 2);
        assert_eq!(bytes_needed(usize::MAX, 1), usize::MAX.div_ceil(8));
        assert_eq!(bytes_needed(usize::MAX, usize::MAX), usize::MAX.div_ceil(8));
    }

    #[test]
    fn into_error_maps_each_variant_to_its_shared_kind_without_loss() {
        let short = BufferTooShort::new(3, 0, "f");
        let out = OutputBufferTooSmall::new(3, 0, "f");
        let invalid = InvalidValue::new("f", 65, "field wider than 64 bits");
        let overflow = FieldOverflow::new("f", 8, 7);
        assert_eq!(
            BitError::BufferTooShort(short).into_error::<Kind>(),
            Kind::Short(short)
        );
        assert_eq!(
            BitError::OutputBufferTooSmall(out).into_error::<Kind>(),
            Kind::Out(out)
        );
        assert_eq!(
            BitError::InvalidValue(invalid).into_error::<Kind>(),
            Kind::Invalid(invalid)
        );
        assert_eq!(
            BitError::FieldOverflow(overflow).into_error::<Kind>(),
            Kind::Overflow(overflow)
        );
        assert_eq!(
            WireError::from(BitError::OutputBufferTooSmall(out)),
            WireError::OutputBufferTooSmall(out)
        );
    }

    #[test]
    fn a_write_past_the_end_is_an_output_error_not_a_short_input() {
        let mut buf = [0u8; 1];
        let mut w = BitWriter::new(&mut buf);
        w.write_bits(0, 8, "field").unwrap();
        assert!(matches!(
            w.write_bits(1, 1, "field")
                .unwrap_err()
                .into_error::<Kind>(),
            Kind::Out(_)
        ));
    }

    #[test]
    fn into_error_of_a_real_short_read_names_the_field() {
        let mut r = BitReader::new(&[0xFF]);
        let e = r.read_bits(9, "len").unwrap_err().into_error::<Kind>();
        assert_eq!(
            e,
            Kind::Short(BufferTooShort {
                need: 2,
                have: 1,
                what: "len"
            })
        );
    }

    #[test]
    fn write_field_writes_in_range_values_and_refuses_the_rest() {
        let mut buf = [0u8; 2];
        let mut w = BitWriter::new(&mut buf);
        assert_eq!(w.write_field::<Kind>(0, 1, "a"), Ok(()));
        assert_eq!(w.write_field::<Kind>(0x7F, 7, "b"), Ok(()));
        assert_eq!(
            w.write_field::<Kind>(0x100, 8, "c"),
            Err(Kind::Overflow(FieldOverflow {
                field: "c",
                value: 0x100,
                max: 0xFF
            }))
        );
        assert_eq!(
            w.write_field::<Kind>(0, 0, "zero"),
            Err(Kind::Overflow(FieldOverflow {
                field: "zero",
                value: 0,
                max: 0
            }))
        );
        assert_eq!(
            w.write_field::<Kind>(0, 65, "wide"),
            Err(Kind::Overflow(FieldOverflow {
                field: "wide",
                value: 0,
                max: 0
            }))
        );
        assert_eq!(w.write_field::<Kind>(0xFF, 8, "d"), Ok(()));
        assert_eq!(
            w.write_field::<Kind>(1, 1, "full"),
            Err(Kind::Out(OutputBufferTooSmall::new(1, 0, "full")))
        );
        assert_eq!(buf, [0x7F, 0xFF]);
    }

    #[test]
    fn bit_buf_write_field_matches_the_slice_writer() {
        let mut buf = BitBuf::new();
        assert_eq!(buf.write_field::<Kind>(0x5, 3, "a"), Ok(()));
        assert_eq!(
            buf.write_field::<Kind>(0x10, 4, "b"),
            Err(Kind::Overflow(FieldOverflow::new("b", 0x10, 0xF)))
        );
        assert_eq!(buf.bits_written(), 3);
        assert_eq!(buf.as_bytes(), [0b1010_0000]);
    }

    #[test]
    fn write_field_accepts_the_whole_u64_at_width_64() {
        let mut buf = [0u8; 8];
        let mut w = BitWriter::new(&mut buf);
        assert_eq!(w.write_field::<Kind>(u64::MAX, 64, "w"), Ok(()));
        assert_eq!(buf, [0xFF; 8]);
    }
}