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
//! The common failure kinds of the workspace, defined once.
//!
//! Every parser/serializer crate keeps its own `Error` enum for failures that
//! are specific to its format, and carries each kind below as a single
//! wrapping variant:
//!
//! ```ignore
//! #[error(transparent)]
//! BufferTooShort(#[from] broadcast_core::error::BufferTooShort),
//! ```
//!
//! so the struct, its `Display` message and its field names exist once (the
//! `http` / `aws-smithy-types` pattern: a foundation crate owns the shared
//! types, family crates wrap them) and `?` converts without hand-written
//! `From` impls.
//!
//! # Field naming
//!
//! `what` names the structure or unit being parsed, written or compared
//! (`"ProgramStreamMap"`, `"SNDU"`); `field` names one spec field inside it
//! (`"section_length"`). A kind that can only concern a field uses `field`;
//! one that can concern a whole structure uses `what`.
//!
//! # Shape
//!
//! Every kind is `Debug + Clone + Copy + PartialEq + Eq`, holds only plain
//! data and `&'static str` labels, and implements `core::error::Error`, so it
//! works in `no_std` and never allocates. Both are promises of the contract: a
//! dynamic name (a four-CC, a URL) belongs in a crate's own variant, not in a
//! shared kind. Every kind is `#[non_exhaustive]` with public fields: a caller
//! reads the fields and matches with `..`, and builds a value with its
//! `const fn new`, whose parameters are the fields in declaration order. A
//! field can then be added later without a breaking change.
//!
//! The `Display` text of each kind is diagnostic and outside semver; a caller
//! decides on the kind and its fields, never on the message. Under the
//! `serde` feature each kind serialises as its fields, and [`WireError`] as
//! those fields plus a `"kind"` tag in `snake_case`.
//!
//! Kinds whose meaning differs per crate (unknown tag, invalid length, UTF-8,
//! unexpected table id) are deliberately absent.
//!
//! [`WireError`] is the whole vocabulary as one enum: the cause a
//! [`Damage`](crate::damage::Damage) report carries, and the one variant a
//! crate may wrap instead of one variant per kind.

/// An input buffer held fewer bytes than the structure being parsed needs.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct BufferTooShort {
    /// Bytes required to proceed.
    pub need: usize,
    /// Bytes actually available.
    pub have: usize,
    /// Name of the type or field being parsed.
    pub what: &'static str,
}

impl BufferTooShort {
    /// Build the error from its fields, in declaration order.
    #[must_use]
    pub const fn new(need: usize, have: usize, what: &'static str) -> Self {
        Self { need, have, what }
    }
}

/// An output buffer was smaller than the serialized form requires.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct OutputBufferTooSmall {
    /// Required size.
    pub need: usize,
    /// Actual size.
    pub have: usize,
    /// Name of the type or field being serialized.
    pub what: &'static str,
}

impl OutputBufferTooSmall {
    /// Build the error from its fields, in declaration order.
    #[must_use]
    pub const fn new(need: usize, have: usize, what: &'static str) -> Self {
        Self { need, have, what }
    }
}

/// A value did not fit the wire field it is written to.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct FieldOverflow {
    /// Spec name of the field, e.g. "section_length".
    pub field: &'static str,
    /// The value that did not fit.
    pub value: u64,
    /// The largest value the field can hold.
    pub max: u64,
}

impl FieldOverflow {
    /// Build the error from its fields, in declaration order.
    #[must_use]
    pub const fn new(field: &'static str, value: u64, max: u64) -> Self {
        Self { field, value, max }
    }
}

/// A CRC-32 carried on the wire disagrees with the one computed over the data.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct CrcMismatch {
    /// The structure the CRC protects, e.g. "PSM", "SNDU", "section".
    pub what: &'static str,
    /// The CRC computed over the received bytes.
    pub computed: u32,
    /// The CRC carried in the stream.
    pub expected: u32,
}

impl CrcMismatch {
    /// Build the error from its fields, in declaration order.
    #[must_use]
    pub const fn new(what: &'static str, computed: u32, expected: u32) -> Self {
        Self {
            what,
            computed,
            expected,
        }
    }
}

/// A fixed marker (TS sync byte, burst sync word, start code) did not match.
///
/// `expected` and `found` are widened to `u32` so one kind covers an 8-bit
/// sync byte, a 16-bit sync word and a 24/32-bit start code.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct InvalidSync {
    /// The marker's name, e.g. "TS sync byte", "Pa sync word".
    pub what: &'static str,
    /// The value the spec fixes.
    pub expected: u32,
    /// The value read.
    pub found: u32,
}

impl InvalidSync {
    /// Build the error from its fields, in declaration order.
    #[must_use]
    pub const fn new(what: &'static str, expected: u32, found: u32) -> Self {
        Self {
            what,
            expected,
            found,
        }
    }
}

/// A reserved field did not hold the value the spec requires (all ones, or
/// zero).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ReservedBits {
    /// Spec name of the reserved field.
    pub field: &'static str,
    /// The value the spec requires.
    pub expected: u64,
    /// The value read.
    pub found: u64,
}

impl ReservedBits {
    /// Build the error from its fields, in declaration order.
    #[must_use]
    pub const fn new(field: &'static str, expected: u64, found: u64) -> Self {
        Self {
            field,
            expected,
            found,
        }
    }
}

/// A field held a value the spec does not allow.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct InvalidValue {
    /// Spec name of the field.
    pub field: &'static str,
    /// The value read, widened to `u64`.
    pub value: u64,
    /// Why the value is rejected.
    pub reason: &'static str,
}

impl InvalidValue {
    /// Build the error from its fields, in declaration order.
    #[must_use]
    pub const fn new(field: &'static str, value: u64, reason: &'static str) -> Self {
        Self {
            field,
            value,
            reason,
        }
    }
}

/// A field is structurally invalid and has no single offending number (a bad
/// combination, a missing mandatory part).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct InvalidField {
    /// Spec name of the field.
    pub field: &'static str,
    /// Why the field is rejected.
    pub reason: &'static str,
}

impl InvalidField {
    /// Build the error from its fields, in declaration order.
    #[must_use]
    pub const fn new(field: &'static str, reason: &'static str) -> Self {
        Self { field, reason }
    }
}

/// A format version number this crate does not support.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct UnsupportedVersion {
    /// The structure carrying the version, e.g. "RTP", "emsg".
    pub what: &'static str,
    /// The version read.
    pub found: u32,
}

impl UnsupportedVersion {
    /// Build the error from its fields, in declaration order.
    #[must_use]
    pub const fn new(what: &'static str, found: u32) -> Self {
        Self { what, found }
    }
}

/// A length field disagrees with the number of bytes actually present or
/// computed.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct LengthMismatch {
    /// The structure whose length is checked.
    pub what: &'static str,
    /// The length the header declares.
    pub declared: usize,
    /// The length actually found or computed.
    pub actual: usize,
}

impl LengthMismatch {
    /// Build the error from its fields, in declaration order.
    #[must_use]
    pub const fn new(what: &'static str, declared: usize, actual: usize) -> Self {
        Self {
            what,
            declared,
            actual,
        }
    }
}

/// A count or size read from the input exceeded a limit the caller supplied.
///
/// Checked before anything is allocated from the value (see
/// [`check_limit`](crate::len::check_limit)); a limit hit is an error, not a
/// [`Damage`](crate::damage::Damage) report.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct LimitExceeded {
    /// The quantity that exceeded its limit, e.g. "samples per track".
    pub what: &'static str,
    /// The caller's limit.
    pub limit: u64,
    /// The value the input asked for.
    pub value: u64,
}

impl LimitExceeded {
    /// Build the error from its fields, in declaration order.
    #[must_use]
    pub const fn new(what: &'static str, limit: u64, value: u64) -> Self {
        Self { what, limit, value }
    }
}

/// Every shared kind as one enum.
///
/// A reader whose own error carries one of these kinds passes it through
/// here, so a caller can match on the cause without parsing text; a failure
/// with no shared kind (a format-specific parse error) has none rather than
/// an invented one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize),
    serde(tag = "kind", rename_all = "snake_case")
)]
#[non_exhaustive]
pub enum WireError {
    /// The input was shorter than the structure it declared.
    BufferTooShort(BufferTooShort),
    /// The output buffer was too small for the serialized form.
    OutputBufferTooSmall(OutputBufferTooSmall),
    /// A value did not fit the field it belonged in.
    FieldOverflow(FieldOverflow),
    /// A protected block's CRC disagreed.
    CrcMismatch(CrcMismatch),
    /// A fixed marker did not match.
    InvalidSync(InvalidSync),
    /// A reserved field held a value the format does not allow.
    ReservedBits(ReservedBits),
    /// A field held a value the format does not allow.
    InvalidValue(InvalidValue),
    /// A field was structurally invalid.
    InvalidField(InvalidField),
    /// A version the reader does not support.
    UnsupportedVersion(UnsupportedVersion),
    /// The unit declared a length the input did not hold.
    LengthMismatch(LengthMismatch),
    /// A count or size exceeded the caller's limit.
    LimitExceeded(LimitExceeded),
}

impl WireError {
    /// A short, stable label for the kind.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        match self {
            WireError::BufferTooShort(_) => "buffer too short",
            WireError::OutputBufferTooSmall(_) => "output buffer too small",
            WireError::FieldOverflow(_) => "field overflow",
            WireError::CrcMismatch(_) => "crc mismatch",
            WireError::InvalidSync(_) => "invalid sync",
            WireError::ReservedBits(_) => "reserved bits",
            WireError::InvalidValue(_) => "invalid value",
            WireError::InvalidField(_) => "invalid field",
            WireError::UnsupportedVersion(_) => "unsupported version",
            WireError::LengthMismatch(_) => "length mismatch",
            WireError::LimitExceeded(_) => "limit exceeded",
        }
    }
}

impl core::fmt::Display for WireError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            WireError::BufferTooShort(e) => e.fmt(f),
            WireError::OutputBufferTooSmall(e) => e.fmt(f),
            WireError::FieldOverflow(e) => e.fmt(f),
            WireError::CrcMismatch(e) => e.fmt(f),
            WireError::InvalidSync(e) => e.fmt(f),
            WireError::ReservedBits(e) => e.fmt(f),
            WireError::InvalidValue(e) => e.fmt(f),
            WireError::InvalidField(e) => e.fmt(f),
            WireError::UnsupportedVersion(e) => e.fmt(f),
            WireError::LengthMismatch(e) => e.fmt(f),
            WireError::LimitExceeded(e) => e.fmt(f),
        }
    }
}
impl core::error::Error for WireError {}

impl From<BufferTooShort> for WireError {
    fn from(e: BufferTooShort) -> Self {
        WireError::BufferTooShort(e)
    }
}
impl From<OutputBufferTooSmall> for WireError {
    fn from(e: OutputBufferTooSmall) -> Self {
        WireError::OutputBufferTooSmall(e)
    }
}
impl From<FieldOverflow> for WireError {
    fn from(e: FieldOverflow) -> Self {
        WireError::FieldOverflow(e)
    }
}
impl From<CrcMismatch> for WireError {
    fn from(e: CrcMismatch) -> Self {
        WireError::CrcMismatch(e)
    }
}
impl From<InvalidSync> for WireError {
    fn from(e: InvalidSync) -> Self {
        WireError::InvalidSync(e)
    }
}
impl From<ReservedBits> for WireError {
    fn from(e: ReservedBits) -> Self {
        WireError::ReservedBits(e)
    }
}
impl From<InvalidValue> for WireError {
    fn from(e: InvalidValue) -> Self {
        WireError::InvalidValue(e)
    }
}
impl From<InvalidField> for WireError {
    fn from(e: InvalidField) -> Self {
        WireError::InvalidField(e)
    }
}
impl From<UnsupportedVersion> for WireError {
    fn from(e: UnsupportedVersion) -> Self {
        WireError::UnsupportedVersion(e)
    }
}
impl From<LengthMismatch> for WireError {
    fn from(e: LengthMismatch) -> Self {
        WireError::LengthMismatch(e)
    }
}
impl From<LimitExceeded> for WireError {
    fn from(e: LimitExceeded) -> Self {
        WireError::LimitExceeded(e)
    }
}

impl core::fmt::Display for LimitExceeded {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "{} = {} exceeds the configured limit of {}",
            self.what, self.value, self.limit
        )
    }
}
impl core::error::Error for LimitExceeded {}

impl core::fmt::Display for BufferTooShort {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "buffer too short: need {} bytes, have {} (while parsing {})",
            self.need, self.have, self.what
        )
    }
}
impl core::error::Error for BufferTooShort {}

impl core::fmt::Display for OutputBufferTooSmall {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "output buffer too small: need {}, have {} (while serializing {})",
            self.need, self.have, self.what
        )
    }
}
impl core::error::Error for OutputBufferTooSmall {}

impl core::fmt::Display for FieldOverflow {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "{} = {} exceeds the field maximum {}",
            self.field, self.value, self.max
        )
    }
}
impl core::error::Error for FieldOverflow {}

impl core::fmt::Display for CrcMismatch {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "{} CRC-32 mismatch: computed {:#010x}, expected {:#010x}",
            self.what, self.computed, self.expected
        )
    }
}
impl core::error::Error for CrcMismatch {}

impl core::fmt::Display for InvalidSync {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "invalid {}: expected {:#x}, got {:#x}",
            self.what, self.expected, self.found
        )
    }
}
impl core::error::Error for InvalidSync {}

impl core::fmt::Display for ReservedBits {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "reserved field {} must be {:#x}, found {:#x}",
            self.field, self.expected, self.found
        )
    }
}
impl core::error::Error for ReservedBits {}

impl core::fmt::Display for InvalidValue {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "field {} value {} invalid: {}",
            self.field, self.value, self.reason
        )
    }
}
impl core::error::Error for InvalidValue {}

impl core::fmt::Display for InvalidField {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "invalid field {}: {}", self.field, self.reason)
    }
}
impl core::error::Error for InvalidField {}

impl core::fmt::Display for UnsupportedVersion {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "unsupported {} version {}", self.what, self.found)
    }
}
impl core::error::Error for UnsupportedVersion {}

impl core::fmt::Display for LengthMismatch {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "length mismatch for {}: declared {}, actual {}",
            self.what, self.declared, self.actual
        )
    }
}
impl core::error::Error for LengthMismatch {}

#[cfg(test)]
mod tests {
    extern crate alloc;
    use super::*;
    use alloc::string::ToString;

    #[test]
    fn display_messages() {
        assert_eq!(
            BufferTooShort {
                need: 4,
                have: 1,
                what: "PAT"
            }
            .to_string(),
            "buffer too short: need 4 bytes, have 1 (while parsing PAT)"
        );
        assert_eq!(
            OutputBufferTooSmall {
                need: 4,
                have: 1,
                what: "Frame"
            }
            .to_string(),
            "output buffer too small: need 4, have 1 (while serializing Frame)"
        );
        assert_eq!(
            FieldOverflow {
                field: "section_length",
                value: 5000,
                max: 4095
            }
            .to_string(),
            "section_length = 5000 exceeds the field maximum 4095"
        );
        assert_eq!(
            CrcMismatch {
                what: "PSM",
                computed: 0xAB,
                expected: 0xCD
            }
            .to_string(),
            "PSM CRC-32 mismatch: computed 0x000000ab, expected 0x000000cd"
        );
        assert_eq!(
            InvalidSync {
                what: "TS sync byte",
                expected: 0x47,
                found: 0
            }
            .to_string(),
            "invalid TS sync byte: expected 0x47, got 0x0"
        );
        assert_eq!(
            ReservedBits {
                field: "reserved",
                expected: 0x7,
                found: 0x2
            }
            .to_string(),
            "reserved field reserved must be 0x7, found 0x2"
        );
        assert_eq!(
            InvalidValue {
                field: "version",
                value: 9,
                reason: "out of range"
            }
            .to_string(),
            "field version value 9 invalid: out of range"
        );
        assert_eq!(
            InvalidField {
                field: "pts",
                reason: "missing"
            }
            .to_string(),
            "invalid field pts: missing"
        );
        assert_eq!(
            UnsupportedVersion {
                what: "RTP",
                found: 1
            }
            .to_string(),
            "unsupported RTP version 1"
        );
        assert_eq!(
            LengthMismatch {
                what: "APDU",
                declared: 9,
                actual: 7
            }
            .to_string(),
            "length mismatch for APDU: declared 9, actual 7"
        );
    }

    #[test]
    fn equality_distinguishes_every_field() {
        let a = CrcMismatch {
            what: "PSM",
            computed: 1,
            expected: 2,
        };
        assert_eq!(a, a);
        assert_ne!(a, CrcMismatch { what: "SNDU", ..a });
        assert_ne!(a, CrcMismatch { computed: 3, ..a });
        assert_ne!(a, CrcMismatch { expected: 3, ..a });
        let b = LengthMismatch {
            what: "x",
            declared: 1,
            actual: 2,
        };
        assert_ne!(b, LengthMismatch { declared: 2, ..b });
        assert_ne!(b, LengthMismatch { actual: 1, ..b });
    }

    #[test]
    fn len_helpers_return_the_shared_kinds() {
        let e: BufferTooShort = crate::len::need_in(&[], 1, "x").unwrap_err();
        assert_eq!(
            e,
            BufferTooShort {
                need: 1,
                have: 0,
                what: "x"
            }
        );
        let o: OutputBufferTooSmall =
            crate::len::need_out(&[], 1, "len_helpers_return_the_shared_kinds").unwrap_err();
        assert_eq!(
            o,
            OutputBufferTooSmall {
                need: 1,
                have: 0,
                what: "len_helpers_return_the_shared_kinds"
            }
        );
        let _: FieldOverflow = crate::len::fit_bits(256, 8, "f").unwrap_err();
    }

    #[test]
    fn limit_exceeded_names_the_quantity_value_and_limit() {
        assert_eq!(
            LimitExceeded {
                what: "moov bytes",
                limit: 4,
                value: 5
            }
            .to_string(),
            "moov bytes = 5 exceeds the configured limit of 4"
        );
    }

    #[test]
    fn every_kind_converts_into_wire_error_and_keeps_its_display() {
        let short = BufferTooShort {
            need: 2,
            have: 1,
            what: "x",
        };
        let cases: [(WireError, &str); 11] = [
            (short.into(), "buffer too short"),
            (
                OutputBufferTooSmall {
                    need: 2,
                    have: 1,
                    what: "every_kind_converts_into_wire_error_and_keeps_its_display",
                }
                .into(),
                "output buffer too small",
            ),
            (
                FieldOverflow {
                    field: "f",
                    value: 2,
                    max: 1,
                }
                .into(),
                "field overflow",
            ),
            (
                CrcMismatch {
                    what: "s",
                    computed: 1,
                    expected: 2,
                }
                .into(),
                "crc mismatch",
            ),
            (
                InvalidSync {
                    what: "s",
                    expected: 1,
                    found: 2,
                }
                .into(),
                "invalid sync",
            ),
            (
                ReservedBits {
                    field: "r",
                    expected: 1,
                    found: 0,
                }
                .into(),
                "reserved bits",
            ),
            (
                InvalidValue {
                    field: "v",
                    value: 1,
                    reason: "r",
                }
                .into(),
                "invalid value",
            ),
            (
                InvalidField {
                    field: "f",
                    reason: "r",
                }
                .into(),
                "invalid field",
            ),
            (
                UnsupportedVersion {
                    what: "w",
                    found: 9,
                }
                .into(),
                "unsupported version",
            ),
            (
                LengthMismatch {
                    what: "w",
                    declared: 1,
                    actual: 2,
                }
                .into(),
                "length mismatch",
            ),
            (
                LimitExceeded {
                    what: "w",
                    limit: 1,
                    value: 2,
                }
                .into(),
                "limit exceeded",
            ),
        ];
        for (error, name) in cases {
            assert_eq!(error.name(), name);
            assert!(!error.to_string().is_empty());
        }
        assert_eq!(
            WireError::from(short).to_string(),
            short.to_string(),
            "Display delegates to the kind"
        );
    }

    #[test]
    fn kinds_are_core_errors() {
        fn is_error<E: core::error::Error + Copy + Send + Sync + 'static>() {}
        is_error::<BufferTooShort>();
        is_error::<CrcMismatch>();
        is_error::<InvalidSync>();
        is_error::<ReservedBits>();
        is_error::<InvalidValue>();
        is_error::<InvalidField>();
        is_error::<UnsupportedVersion>();
        is_error::<LengthMismatch>();
        is_error::<LimitExceeded>();
        is_error::<WireError>();
    }
}