kmip-protocol 0.5.1

KMIP protocol object (de)serialization
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
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
//! Deserializing TTLV elements quickly.
//!
//! This module provides low-level TTLV deserialization support.  It is entirely
//! manual -- it does not provide a declarative interface.  It is designed for
//! fast, streaming, zero-copy operation.

use core::fmt;

use crate::ttlv::types::Type;

use super::types::Tag;

//----------- FastScanner ----------------------------------------------------

/// A fast TTLV scanner.
///
/// In most cases, errors are highly unlikely.  This scanner optimizes for this
/// by omitting error handling and pinpointing facilities -- it detects errors
/// without tracking any details of them.  In some cases, it will delay errors,
/// returning garbage data instead of [`Err`].  If scanning with [`FastScanner`]
/// fails, a different scanner (e.g. [`crate::ttlv::from_slice()`]) needs to be
/// used to ascertain the position and cause of the error.
//
// TODO: Link to 'SlowScanner' instead, once it exists.
///
/// ## Delayed Errors
///
/// For efficiency, the scanner will sometimes return invalid data, e.g. from
/// [`Self::scan_int()`].  This only occurs if the input is invalid, but it is
/// more efficient than returning an actual [`Err`].  Once invalid data has been
/// returned, at any point, [`Self::has_delayed_error()`] will report `true`.
///
/// The caller should never "trust" the data being returned, e.g. to decide how
/// much memory to allocate.  Any field can return invalid data; the input may
/// be well-formed but contain an unexpected value for a field.
///
/// ## Streaming Operation
///
/// [`FastScanner`] can be used in streaming fashion.  For example, when
/// receiving a stream of serialized items (e.g. KMIP requests), one cannot
/// wait for the end of the stream to parse.  Instead, the user should store the
/// input in a dynamically allocated buffer.  Once some data is in the buffer, a
/// [`FastScanner`] can be initialized over it, and [`Self::have_next()`] can be
/// used to check whether a complete TTLV item is available.  If it is, the item
/// can be parsed; otherwise, more data needs to be buffered.
///
/// ```no_run
/// # use std::{io::Read, net::TcpStream};
/// # use kmip_protocol::ttlv::FastScanner;
/// #
/// // Buffer data in a `Vec`.
/// let mut buffer = Vec::new();
///
/// // Read some data from the network.
/// let mut stream = TcpStream::connect("127.0.0.1:8000").unwrap();
/// stream.set_nonblocking(true).unwrap();
/// loop {
///     // Fill the buffer as much as possible.
///     // NOTE: Only ignore 'std::io::ErrorKind::WouldBlock'.
///     let _ = stream.read_to_end(&mut buffer);
///
///     // Try parsing whole TTLV elements from the buffer.
///     while let Some((mut scanner, rest)) = FastScanner::next_element(&buffer) {
///         // Read the TTLV element out.
///         //...
///
///         // Remove the parsed data from the buffer.
///         // NOTE: This is quite inefficient, use a better data structure.
///         let remaining = rest.len();
///         let consumed = buffer.len() - remaining;
///         buffer.drain(0..consumed);
///     }
/// }
/// ```
#[derive(Clone)]
pub struct FastScanner<'a> {
    /// The currently remaining input.
    ///
    /// TTLV elements are always serialized into multiples of 8 bytes.  The
    /// first 8-byte block of each element contains the tag, type, and length;
    /// even if the content is less than 8 bytes, it gets padded.  By tracking
    /// these blocks, we can use 64-bit integer operations to process 8 bytes at
    /// a time, which is far more efficient than byte-by-byte scanning.
    remaining: &'a [[u8; 8]],

    pub tag: Option<Tag>,

    /// A machine word indicating failure.
    ///
    /// This is non-zero if an error was detected and delayed.  Conceptually, it
    /// is just a boolean.  Most operations here deal with 64-bit units of data
    /// (i.e. "machine words") from TTLV; representing failure data in the same
    /// way unlocks many simplifications.
    ///
    /// So what exactly is the problem with defining this as a `bool`?  A `bool`
    /// is represented in memory as a 0 or a 1.  But during scanning, failure
    /// could be represented in other ways, e.g. a 64-bit integer with certain
    /// bits set.  The generated code would have to convert all representations
    /// of failure into a 0 or 1, and this cost adds up.
    ///
    /// Side note: in some cases, LLVM could optimize around a `bool` by keeping
    /// it in a register and then changing its representation; but this heavily
    /// depends on the local control flow it can see.  Its "vision" is limited
    /// and gets obscured by function calls.
    failure_word: u64,
}

impl<'a> FastScanner<'a> {
    /// Construct a new [`FastScanner`].
    ///
    /// It is expected that the input will be scanned in its entirety.
    ///
    /// ## Errors
    ///
    /// Fails if the input is not a multiple of 8 bytes.  TTLV elements are
    /// always serialized into multiples of 8 bytes, so the presence of a
    /// partial 8-byte block immediately implies the input is invalid.
    pub fn new(input: &'a [u8]) -> Result<Self, FastScanError> {
        let (input, &[]) = input.as_chunks() else {
            // The input contains a partial block.
            return Err(FastScanError::assert());
        };

        Ok(Self::from_blocks(input))
    }

    /// Prepare to parse the next TTLV element from a buffer.
    ///
    /// If a whole TTLV element is present in the input, [`Some`] is returned,
    /// with a scanner ready to parse that element and the unused portion of
    /// the buffer.  Otherwise, [`None`] is returned, and more data needs to be
    /// collected for parsing.
    ///
    /// See [the `FastScanner` documentation on streaming
    /// operation](Self#streaming-operation) for more details.
    pub fn next_element(input: &'a [u8]) -> Option<(Self, &'a [u8])> {
        // Retrieve the header of the next element.
        let header = input.first_chunk::<8>()?;

        // Determine how many bytes are needed to parse this element.
        let length = u32::from_be_bytes(header[4..].try_into().unwrap());
        // If this fails, the element will never fit in memory.
        let length = usize::try_from(length).ok()?;
        // Round up to a whole number of blocks and count the header.
        let length = 8 + length.next_multiple_of(8);

        // Try extracting the whole element from the input.
        let (elem, rest) = input.split_at_checked(length)?;

        // SAFETY: 'length' is always a multiple of 8.
        let elem = unsafe { elem.as_chunks_unchecked() };

        Some((Self::from_blocks(elem), rest))
    }

    /// Construct a new [`FastScanner`] from a slice of 8-byte blocks.
    ///
    /// TTLV elements are always serialized into multiples of 8 bytes.
    /// [`FastScanner`] internally represents its input as slices of 8-byte
    /// blocks so it is easier to process.
    pub const fn from_blocks(input: &'a [[u8; 8]]) -> Self {
        Self {
            remaining: input,
            failure_word: 0,
            tag: None,
        }
    }

    /// The remaining input to the scanner.
    ///
    /// Note: in case an error has occurred (delayed or otherwise), the amount
    /// of remaining data is not well specified.  It might not include the data
    /// causing the failure.
    pub const fn remaining(&self) -> &'a [[u8; 8]] {
        self.remaining
    }

    /// Whether the scanner is finished.
    pub const fn is_empty(&self) -> bool {
        self.remaining.is_empty()
    }

    /// Whether an error has been delayed.
    ///
    /// This should be checked before acting on any parsed data.  If an error
    /// has been delayed, all previously-returned data should be assumed to be
    /// garbage.  See [the `FastScanner` documentation](Self#delayed-errors) for
    /// more information about delayed errors.
    pub const fn has_delayed_error(&self) -> bool {
        self.failure_word != 0
    }

    /// Whether an entire TTLV element is available.
    ///
    /// The length of the next element will be checked;
    ///
    ///   - if it is entirely loaded in the buffer, Ok(()) will be returned.
    ///   - if the buffer is empty, Err(None) will be returned.
    ///   - if the buffer is partially full, the L (from TT_L_V) value must be
    ///     available and so Err(Some(n)) is returned when n is the number of
    ///     missing bytes where n > 0.
    ///
    /// This can be used for streamed parsing, to decide whether more data
    /// needs to be buffered and, if known, how much more data needs to be
    /// fetched from the source.
    pub fn have_next(&self) -> Result<(), Option<u32>> {
        let [header, rest @ ..] = self.remaining else {
            return Err(None);
        };

        let length = u32::from_be_bytes(header[4..8].try_into().unwrap());
        let available = rest.as_flattened().len();

        let missing = if usize::BITS >= u32::BITS {
            // 'usize' is at least as big as 'u32'.
            // SAFETY: Since length cannot be larger than a u32 the result
            // of subtracting a value from length cannot be larger than a u32.
            (length as usize).checked_sub(available).map(|v| v as u32)
        } else {
            // 'u32' is bigger than 'usize'.
            length.checked_sub(available as u32)
        };

        match missing {
            // More bytes are available than needed
            None => Ok(()),

            // We have exactly the number of needed bytes.
            Some(0) => Ok(()),

            // We have n bytes less than we need.
            Some(n) => Err(Some(n)),
        }
    }

    /// Finish the scanner.
    ///
    /// If there is remaining input, or an error was delayed, [`Err`] is
    /// returned.  If additional remaining input is allowed, use
    /// [`Self::finish_non_exhaustive()`] instead.
    pub fn finish(self) -> Result<(), FastScanError> {
        if self.is_empty() && !self.has_delayed_error() {
            Ok(())
        } else {
            Err(FastScanError::assert())
        }
    }

    /// Finish the scanner non-exhaustively.
    ///
    /// Additional input is ignored.  [`Err`] is returned only if an error is
    /// delayed.  If additional remaining input is not allowed, use
    /// [`Self::finish()`] instead.
    pub fn finish_non_exhaustive(self) -> Result<(), FastScanError> {
        if !self.has_delayed_error() {
            Ok(())
        } else {
            Err(FastScanError::assert())
        }
    }
}

/// # Scanning Helpers
//
// Lemmas:
// - `u64::from_be_bytes(*header) == u64::from_be(u64::from_ne_bytes(*header))`.
// - `u64::from_ne_bytes(*header) == u64::from_be_bytes(*header).to_be()`.
// - `a.to_be() ^ b.to_be() == (a ^ b).to_be()`.
//
// Conventions:
// - `check_*` updates `self.failure_word` on error.
// - `test_*` returns `None` on error.
// - `calc_*` returns a non-zero `u64` on error.
impl<'a> FastScanner<'a> {
    /// Verify that a header has a particular tag, type, and length.
    ///
    /// An incorrect header will result in a delayed error.
    #[inline(always)]
    fn check_ttl(&mut self, header: &[u8; 8], tag: Tag, r#type: Type, length: u32) {
        self.failure_word |= Self::calc_ttl(header, tag, r#type, length);
    }

    /// Test that a header has a particular tag, type, and length.
    ///
    /// Returns `true` if it does.
    #[inline(always)]
    fn test_ttl(&self, header: &[u8; 8], tag: Tag, r#type: Type, length: u32) -> Option<()> {
        let mismatch = Self::calc_ttl(header, tag, r#type, length);
        (mismatch == 0).then_some(())
    }

    #[inline(always)]
    fn calc_ttl(header: &[u8; 8], tag: Tag, r#type: Type, length: u32) -> u64 {
        // Prepare an expected value as a big-endian integer.
        //
        // The compiler should be able to fold this computation into a simple
        // hard-coded 64-bit constant.
        let expected = ((tag.with_type(r#type).value() as u64) << 32 | (length as u64)).to_be();

        // Load the header without changing its endianness, so that it and
        // 'expected' have matching byte layouts.
        let actual = u64::from_ne_bytes(*header);

        // Return non-zero if at least one bit in the actual header did not
        // match.
        actual ^ expected
    }

    /// Verify that a header has a particular tag and type, and a length that is
    /// a multiple of 8.
    ///
    /// The length is returned, and is in units of 8-byte blocks.
    ///
    /// An incorrect header will result in a delayed error.
    #[inline(always)]
    fn check_tt_8l(&mut self, header: &[u8; 8], tag: Tag, r#type: Type) -> usize {
        let (mismatch, length) = Self::calc_tt_8l(header, tag, r#type);
        self.failure_word |= mismatch;
        length
    }

    /// Test that a header has a particular tag and type, and a length that is
    /// a multiple of 8.
    ///
    /// If the header matches, a length is returned, in units of 8-byte blocks.
    #[inline(always)]
    fn test_tt_8l(&self, header: &[u8; 8], tag: Tag, r#type: Type) -> Option<usize> {
        let (mismatch, length) = Self::calc_tt_8l(header, tag, r#type);
        (mismatch == 0).then_some(length)
    }

    #[inline(always)]
    fn calc_tt_8l(header: &[u8; 8], tag: Tag, r#type: Type) -> (u64, usize) {
        // Generate a mask for the length.
        //
        // We need to make sure the low 3 bits of the length are zero.
        //
        // We don't need to support lengths that can't fit in 'usize'; such
        // objects wouldn't fit in memory.  If 'usize' is smaller than 'u32',
        // we'll include the non-'usize' bits in the mask, and so ensure that
        // they are zero in the actual header.
        //
        // This is 0xFFFF_0007 on 16-bit, else 0x0000_0007.
        const LENGTH_MASK: u32 = !(usize::MAX as u32) | 0x07;

        // Generate a mask for the whole header.
        //
        // We always check the top 4 bytes (tag and type).
        const MASK: u64 = u64::MAX << 32 | LENGTH_MASK as u64;

        // Prepare an expected value as a native-endian integer.
        //
        // The length field is set to all-zeros; we will check that 'header'
        // contains the same bits, but only for 'LENGTH_MASK'.
        //
        // The compiler should be able to fold this computation into a simple
        // hard-coded 64-bit constant.
        let expected = (tag.with_type(r#type).value() as u64) << 32;

        // Load the header into the right endianness, as we need to read out its
        // low 32 bits for the length field.  Note that it and 'expected' have
        // matching byte layouts.
        let actual = u64::from_be_bytes(*header);

        // Return non-zero if at least one bit in the actual header (of the tag,
        // type, or low 3 bits of length) did not match.
        let mismatch = (actual ^ expected) & MASK;

        // Extract and return the length, in units of 8-byte blocks.  We have
        // already checked that it fits in a 'usize', so cast to that.
        //
        // Note that the division by 8 happens after casting; otherwise the top
        // 3 bits of the type would get thrown in here by accident.
        let length = (actual as u32 as usize) / 8;

        (mismatch, length)
    }

    /// Verify that a header has a particular tag and type.
    ///
    /// No restrictions are placed on the length field, which is returned in
    /// units of bytes.
    ///
    /// An incorrect header will result in a delayed error.
    #[inline(always)]
    fn check_tt(&mut self, header: &[u8; 8], tag: Tag, r#type: Type) -> usize {
        let (mismatch, length) = Self::calc_tt(header, tag, r#type);
        self.failure_word |= mismatch;
        length
    }

    #[inline(always)]
    fn test_tt(&self, header: &[u8; 8], tag: Tag, r#type: Type) -> Option<usize> {
        let (mismatch, length) = Self::calc_tt(header, tag, r#type);
        (mismatch == 0).then_some(length)
    }

    #[inline(always)]
    fn calc_tt(header: &[u8; 8], tag: Tag, r#type: Type) -> (u64, usize) {
        // If 'u32' can fit in a 'usize', then the encoded length is always a
        // valid 'usize'.  Load the tag-type half and the length as separate
        // 32-bit words; that way, we only hard-code 32-bit integer constants.
        if usize::BITS >= u32::BITS {
            // Prepare an expected value as a big-endian integer.
            //
            // This only accounts for the tag and type.
            //
            // The compiler should be able to fold this computation into a
            // simple hard-coded 32-bit constant.
            let expected = tag.with_type(r#type).value().to_be();

            // Load the tag-type part of the header without changing its
            // endianness, so that it and 'expected' have matching byte layouts.
            //
            // NOTE: This 'unwrap()' is guaranteed to never fail.
            let actual = u32::from_ne_bytes(header[..4].try_into().unwrap());

            // Make the failure word non-zero if at least one bit in the actual
            // header (of the tag or type) did not match.
            let mismatch = (actual ^ expected) as u64;

            // Load the length part of the header into native endianness.
            let length = u32::from_be_bytes(header[4..].try_into().unwrap());

            // We know 'u32' fits in a 'usize', so we can cast directly.
            (mismatch, length as usize)
        } else {
            // Generate a mask for the length.
            //
            // We don't need to support lengths that can't fit in 'usize';
            // such objects wouldn't fit in memory.  If 'usize' is smaller than
            // 'u32', we'll include the non-'usize' bits in the mask, and so
            // ensure that they are zero in the actual header.
            //
            // This is 0xFFFF_0000 on 16-bit.
            const LENGTH_MASK: u32 = !(usize::MAX as u32);

            // Generate a mask for the whole header.
            //
            // We always check the top 4 bytes (tag and type).
            const MASK: u64 = u64::MAX << 32 | LENGTH_MASK as u64;

            // Prepare an expected value as a native-endian integer.
            //
            // The length field is set to all-zeros; we will check that 'header'
            // contains the same bits, but only for 'LENGTH_MASK'.
            //
            // The compiler should be able to fold this computation into a
            // simple hard-coded 64-bit constant.
            let expected = (tag.with_type(r#type).value() as u64) << 32;

            // Load the header into the right endianness, as we need to read out
            // its low bits for the length field.  Note that it and 'expected'
            // have matching byte layouts.
            let actual = u64::from_be_bytes(*header);

            // Make the failure word non-zero if at least one bit in the actual
            // header (of the tag, type, or high part of length) did not match.
            let mismatch = (actual ^ expected) & MASK;

            // We have already checked that the length fits in a 'usize', so we
            // can freely truncate the value now.
            (mismatch, actual as u32 as usize)
        }
    }
}

impl<'a> FastScanner<'a> {
    /// Scan an expected structure.
    ///
    /// The returned sub-scanner can be used to scan the fields of the
    /// `struct`; `self` will independently continue from the end of the
    /// `struct`.
    #[must_use = "Use the returned scanner to parse the structure, or use `FastScanner::skip_struct()` to ignore its contents"]
    #[inline]
    pub fn scan_struct(&mut self, tag: Tag) -> Result<Self, FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        let length = self.check_tt_8l(header, tag, Type::Structure);
        let (body, rest) = rest.split_at_checked(length).ok_or(FastScanError::assert())?;
        self.remaining = rest;

        Ok(Self::from_blocks(body))
    }

    /// Scan an expected structure with a pre-determined length.
    ///
    /// The returned sub-scanner can be used scan the fields of the `struct`;
    /// `self` will independently continue from the end of the `struct`.  If
    /// the length encoded in the input is different from the pre-determined
    /// length, the error will be delayed and both scanners will return
    /// garbage.
    #[must_use = "Use the returned scanner to parse the structure, or use `FastScanner::skip_fixed_struct()` to ignore its contents"]
    #[inline]
    pub fn scan_fixed_struct(&mut self, tag: Tag, length: u32) -> Result<Self, FastScanError> {
        debug_assert!(length.is_multiple_of(8));
        if self.remaining.len() < 1 + length as usize / 8 {
            return Err(FastScanError::assert());
        }
        let (header, rest) = self.remaining.split_first().unwrap();
        self.check_ttl(header, tag, Type::Structure, length);
        let (body, rest) = rest.split_at(length as usize / 8);
        self.remaining = rest;

        Ok(Self::from_blocks(body))
    }

    /// Scan an expected integer.
    #[must_use = "Use the returned value, or use `FastScanner::skip_int()` to ignore it"]
    #[inline]
    pub fn scan_int(&mut self, tag: Tag) -> Result<i32, FastScanError> {
        let [header, value, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        self.check_ttl(header, tag, Type::Integer, 4);
        self.remaining = rest;

        Ok(i32::from_be_bytes(value[0..4].try_into().unwrap()))
    }

    /// Scan an expected long integer.
    #[must_use = "Use the returned value, or use `FastScanner::skip_long_int()` to ignore it"]
    #[inline]
    pub fn scan_long_int(&mut self, tag: Tag) -> Result<i64, FastScanError> {
        let [header, value, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        self.check_ttl(header, tag, Type::LongInteger, 8);
        self.remaining = rest;

        Ok(i64::from_be_bytes(*value))
    }

    /// Scan an expected big integer.
    #[must_use = "Use the returned value, or use `FastScanner::skip_big_int()` to ignore it"]
    #[inline]
    pub fn scan_big_int(&mut self, tag: Tag) -> Result<&'a [u8], FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        let length = self.check_tt_8l(header, tag, Type::BigInteger);
        let (body, rest) = rest.split_at_checked(length).ok_or(FastScanError::assert())?;
        self.remaining = rest;

        Ok(body.as_flattened())
    }

    /// Scan an expected enumeration.
    #[must_use = "Use the returned value, or use `FastScanner::skip_enum()` to ignore it"]
    #[inline]
    pub fn scan_enum(&mut self, tag: Tag) -> Result<u32, FastScanError> {
        let [header, value, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        self.check_ttl(header, tag, Type::Enumeration, 4);
        self.remaining = rest;

        Ok(u32::from_be_bytes(value[0..4].try_into().unwrap()))
    }

    /// Scan an expected boolean.
    #[must_use = "Use the returned value, or use `FastScanner::skip_bool()` to ignore it"]
    #[inline]
    pub fn scan_bool(&mut self, tag: Tag) -> Result<bool, FastScanError> {
        let [header, value, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        self.check_ttl(header, tag, Type::Boolean, 8);
        // Load the value without changing its endianness.
        let value = u64::from_ne_bytes(*value);
        // Check that all bits except the lowest are zero.
        self.failure_word |= value & !u64::from_be(1);
        self.remaining = rest;

        Ok(value != 0)
    }

    /// Scan an expected text string.
    #[must_use = "Use the returned value, or use `FastScanner::skip_text()` to ignore it"]
    #[inline]
    pub fn scan_text(&mut self, tag: Tag) -> Result<&'a str, FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        let length = self.check_tt(header, tag, Type::TextString);
        let body = rest.as_flattened().get(..length).ok_or(FastScanError::assert())?;
        let body = core::str::from_utf8(body).map_err(|_| FastScanError::assert())?;
        self.remaining = &rest[length.div_ceil(8)..];

        Ok(body)
    }

    /// Scan an expected text string as bytes.
    #[must_use = "Use the returned value, or use `FastScanner::skip_text()` to ignore it"]
    #[inline]
    pub fn scan_text_bytes(&mut self, tag: Tag) -> Result<&'a [u8], FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        let length = self.check_tt(header, tag, Type::TextString);
        let body = rest.as_flattened().get(..length).ok_or(FastScanError::assert())?;
        self.remaining = &rest[length.div_ceil(8)..];

        Ok(body)
    }

    /// Scan an expected byte string.
    #[must_use = "Use the returned value, or use `FastScanner::skip_bytes()` to ignore it"]
    #[inline]
    pub fn scan_bytes(&mut self, tag: Tag) -> Result<&'a [u8], FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        let length = self.check_tt(header, tag, Type::ByteString);
        let body = rest.as_flattened().get(..length).ok_or(FastScanError::assert())?;
        self.remaining = &rest[length.div_ceil(8)..];

        Ok(body)
    }

    /// Scan an expected date-time.
    #[must_use = "Use the returned value, or use `FastScanner::skip_date_time()` to ignore it"]
    #[inline]
    pub fn scan_date_time(&mut self, tag: Tag) -> Result<i64, FastScanError> {
        let [header, value, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        self.check_ttl(header, tag, Type::DateTime, 8);
        self.remaining = rest;

        Ok(i64::from_be_bytes(*value))
    }

    /// Scan an expected interval.
    #[must_use = "Use the returned value, or use `FastScanner::skip_interval()` to ignore it"]
    #[inline]
    pub fn scan_interval(&mut self, tag: Tag) -> Result<u32, FastScanError> {
        let [header, value, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        self.check_ttl(header, tag, Type::Interval, 4);
        self.remaining = rest;

        Ok(u32::from_be_bytes(value[0..4].try_into().unwrap()))
    }
}

impl FastScanner<'_> {
    /// Skip an expected structure.
    #[inline]
    pub fn skip_struct(&mut self, tag: Tag) -> Result<(), FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        let length = self.check_tt_8l(header, tag, Type::Structure);
        self.remaining = rest.get(length..).ok_or(FastScanError::assert())?;

        Ok(())
    }

    /// Skip an expected structure with a pre-determined length.
    #[inline]
    pub fn skip_fixed_struct(&mut self, tag: Tag, length: u32) -> Result<(), FastScanError> {
        debug_assert!(length.is_multiple_of(8));
        if self.remaining.len() < 1 + length as usize / 8 {
            return Err(FastScanError::assert());
        }
        self.check_ttl(&self.remaining[0], tag, Type::Structure, length);
        self.remaining = &self.remaining[1 + length as usize / 8..];

        Ok(())
    }

    /// Skip an expected integer.
    #[inline]
    pub fn skip_int(&mut self, tag: Tag) -> Result<(), FastScanError> {
        let [header, _, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        self.check_ttl(header, tag, Type::Integer, 4);
        self.remaining = rest;

        Ok(())
    }

    /// Skip an expected long integer.
    #[inline]
    pub fn skip_long_int(&mut self, tag: Tag) -> Result<(), FastScanError> {
        let [header, _, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        self.check_ttl(header, tag, Type::LongInteger, 8);
        self.remaining = rest;

        Ok(())
    }

    /// Skip an expected big integer.
    #[inline]
    pub fn skip_big_int(&mut self, tag: Tag) -> Result<(), FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        let length = self.check_tt_8l(header, tag, Type::BigInteger);
        self.remaining = rest.get(length..).ok_or(FastScanError::assert())?;

        Ok(())
    }

    /// Skip an expected enumeration.
    #[inline]
    pub fn skip_enum(&mut self, tag: Tag) -> Result<(), FastScanError> {
        let [header, _, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        self.check_ttl(header, tag, Type::Enumeration, 4);
        self.remaining = rest;

        Ok(())
    }

    /// Skip an expected boolean.
    #[inline]
    pub fn skip_bool(&mut self, tag: Tag) -> Result<(), FastScanError> {
        let [header, _, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        self.check_ttl(header, tag, Type::Boolean, 8);
        self.remaining = rest;

        Ok(())
    }

    /// Skip an expected text string.
    #[inline]
    pub fn skip_text(&mut self, tag: Tag) -> Result<(), FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        let length = self.check_tt(header, tag, Type::TextString);
        self.remaining = rest.get(length.div_ceil(8)..).ok_or(FastScanError::assert())?;

        Ok(())
    }

    /// Skip an expected byte string.
    #[inline]
    pub fn skip_bytes(&mut self, tag: Tag) -> Result<(), FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        let length = self.check_tt(header, tag, Type::ByteString);
        self.remaining = rest.get(length.div_ceil(8)..).ok_or(FastScanError::assert())?;

        Ok(())
    }

    /// Skip an expected date-time.
    #[inline]
    pub fn skip_date_time(&mut self, tag: Tag) -> Result<(), FastScanError> {
        let [header, _, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        self.check_ttl(header, tag, Type::DateTime, 8);
        self.remaining = rest;

        Ok(())
    }

    /// Skip an expected interval.
    #[inline]
    pub fn skip_interval(&mut self, tag: Tag) -> Result<(), FastScanError> {
        let [header, _, rest @ ..] = self.remaining else {
            return Err(FastScanError::assert());
        };
        self.check_ttl(header, tag, Type::Interval, 4);
        self.remaining = rest;

        Ok(())
    }
}

impl<'a> FastScanner<'a> {
    /// Scan an optional structure.
    ///
    /// The returned sub-scanner can be used to scan the fields of the
    /// `struct`; `self` will independently continue from the end of the
    /// `struct`.
    #[must_use = "Use the returned scanner to parse the structure, or use `FastScanner::skip_opt_struct()` to ignore its contents"]
    #[inline]
    pub fn scan_opt_struct(&mut self, tag: Tag) -> Result<Option<Self>, FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Ok(None);
        };
        let Some(length) = self.test_tt_8l(header, tag, Type::Structure) else {
            return Ok(None);
        };
        let (body, rest) = rest.split_at_checked(length).ok_or(FastScanError::assert())?;
        self.remaining = rest;

        Ok(Some(Self::from_blocks(body)))
    }

    /// Scan an optional structure with a pre-determined length.
    ///
    /// The returned sub-scanner can be used to scan the fields of the
    /// `struct`; `self` will independently continue from the end of the
    /// `struct`.  If the length encoded in the input is different from the
    /// pre-determined length, the error will be delayed and both scanners
    /// will return garbage.
    #[must_use = "Use the returned scanner to parse the structure, or use `FastScanner::skip_opt_fixed_struct()` to ignore its contents"]
    #[inline]
    pub fn scan_opt_fixed_struct(&mut self, tag: Tag, length: u32) -> Result<Option<Self>, FastScanError> {
        debug_assert!(length.is_multiple_of(8));

        if self.remaining.len() < 1 + length as usize / 8 {
            return Ok(None);
        }
        let (header, rest) = self.remaining.split_first().unwrap();
        let Some(()) = self.test_ttl(header, tag, Type::Structure, length) else {
            return Ok(None);
        };
        let (body, rest) = rest.split_at(length as usize / 8);
        self.remaining = rest;

        Ok(Some(Self::from_blocks(body)))
    }

    /// Scan an optional integer.
    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_int()` to ignore it"]
    #[inline]
    pub fn scan_opt_int(&mut self, tag: Tag) -> Result<Option<i32>, FastScanError> {
        let [header, value, rest @ ..] = self.remaining else {
            return Ok(None);
        };
        let Some(()) = self.test_ttl(header, tag, Type::Integer, 4) else {
            return Ok(None);
        };
        self.remaining = rest;

        Ok(Some(i32::from_be_bytes(value[0..4].try_into().unwrap())))
    }

    /// Scan an optional long integer.
    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_long_int()` to ignore it"]
    #[inline]
    pub fn scan_opt_long_int(&mut self, tag: Tag) -> Result<Option<i64>, FastScanError> {
        let [header, value, rest @ ..] = self.remaining else {
            return Ok(None);
        };
        let Some(()) = self.test_ttl(header, tag, Type::LongInteger, 8) else {
            return Ok(None);
        };
        self.remaining = rest;

        Ok(Some(i64::from_be_bytes(*value)))
    }

    /// Scan an optional big integer.
    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_big_int()` to ignore it"]
    #[inline]
    pub fn scan_opt_big_int(&mut self, tag: Tag) -> Result<Option<&'a [u8]>, FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Ok(None);
        };
        let Some(length) = self.test_tt_8l(header, tag, Type::BigInteger) else {
            return Ok(None);
        };
        let (body, rest) = rest.split_at_checked(length).ok_or(FastScanError::assert())?;
        self.remaining = rest;

        Ok(Some(body.as_flattened()))
    }

    /// Scan an optional enumeration.
    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_enum()` to ignore it"]
    #[inline]
    pub fn scan_opt_enum(&mut self, tag: Tag) -> Result<Option<u32>, FastScanError> {
        let [header, value, rest @ ..] = self.remaining else {
            return Ok(None);
        };
        let Some(()) = self.test_ttl(header, tag, Type::Enumeration, 4) else {
            return Ok(None);
        };
        self.remaining = rest;

        Ok(Some(u32::from_be_bytes(value[0..4].try_into().unwrap())))
    }

    /// Scan an optional boolean.
    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_bool()` to ignore it"]
    #[inline]
    pub fn scan_opt_bool(&mut self, tag: Tag) -> Result<Option<bool>, FastScanError> {
        let [header, value, rest @ ..] = self.remaining else {
            return Ok(None);
        };
        let Some(()) = self.test_ttl(header, tag, Type::Boolean, 8) else {
            return Ok(None);
        };
        // Load the value without changing its endianness.
        let value = u64::from_ne_bytes(*value);
        // Check that all bits except the lowest are zero.
        self.failure_word |= value & !u64::from_be(1);
        self.remaining = rest;

        Ok(Some(value != 0))
    }

    /// Scan an optional text string.
    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_text()` to ignore it"]
    #[inline]
    pub fn scan_opt_text(&mut self, tag: Tag) -> Result<Option<&'a str>, FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Ok(None);
        };
        let Some(length) = self.test_tt(header, tag, Type::TextString) else {
            return Ok(None);
        };
        let body = rest.as_flattened().get(..length).ok_or(FastScanError::assert())?;
        let body = core::str::from_utf8(body).map_err(|_| FastScanError::assert())?;
        self.remaining = &rest[length.div_ceil(8)..];

        Ok(Some(body))
    }

    /// Scan an optional text string as bytes.
    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_text()` to ignore it"]
    #[inline]
    pub fn scan_opt_text_bytes(&mut self, tag: Tag) -> Result<Option<&'a [u8]>, FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Ok(None);
        };
        let Some(length) = self.test_tt(header, tag, Type::TextString) else {
            return Ok(None);
        };
        let body = rest.as_flattened().get(..length).ok_or(FastScanError::assert())?;
        self.remaining = &rest[length.div_ceil(8)..];

        Ok(Some(body))
    }

    /// Scan an optional byte string.
    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_bytes()` to ignore it"]
    #[inline]
    pub fn scan_opt_bytes(&mut self, tag: Tag) -> Result<Option<&'a [u8]>, FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Ok(None);
        };
        let Some(length) = self.test_tt(header, tag, Type::ByteString) else {
            return Ok(None);
        };
        let body = rest.as_flattened().get(..length).ok_or(FastScanError::assert())?;
        self.remaining = &rest[length.div_ceil(8)..];

        Ok(Some(body))
    }

    /// Scan an optional date-time.
    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_date_time()` to ignore it"]
    #[inline]
    pub fn scan_opt_date_time(&mut self, tag: Tag) -> Result<Option<i64>, FastScanError> {
        let [header, value, rest @ ..] = self.remaining else {
            return Ok(None);
        };
        let Some(()) = self.test_ttl(header, tag, Type::DateTime, 8) else {
            return Ok(None);
        };
        self.remaining = rest;

        Ok(Some(i64::from_be_bytes(*value)))
    }

    /// Scan an optional interval.
    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_interval()` to ignore it"]
    #[inline]
    pub fn scan_opt_interval(&mut self, tag: Tag) -> Result<Option<u32>, FastScanError> {
        let [header, value, rest @ ..] = self.remaining else {
            return Ok(None);
        };
        let Some(()) = self.test_ttl(header, tag, Type::Interval, 4) else {
            return Ok(None);
        };
        self.remaining = rest;

        Ok(Some(u32::from_be_bytes(value[0..4].try_into().unwrap())))
    }
}

impl<'a> FastScanner<'a> {
    /// Skip an optional structure.
    #[inline]
    pub fn skip_opt_struct(&mut self, tag: Tag) -> Result<bool, FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Ok(false);
        };
        let Some(length) = self.test_tt_8l(header, tag, Type::Structure) else {
            return Ok(false);
        };
        self.remaining = rest.get(length..).ok_or(FastScanError::assert())?;

        Ok(true)
    }

    /// Skip an optional structure with a pre-determined length.
    #[inline]
    pub fn skip_opt_fixed_struct(&mut self, tag: Tag, length: u32) -> Result<bool, FastScanError> {
        debug_assert!(length.is_multiple_of(8));
        if self.remaining.len() < 1 + length as usize / 8 {
            return Ok(false);
        }
        let (header, rest) = self.remaining.split_first().unwrap();
        let Some(()) = self.test_ttl(header, tag, Type::Structure, length) else {
            return Ok(false);
        };
        self.remaining = &rest[length as usize / 8..];

        Ok(true)
    }

    /// Skip an optional integer.
    #[inline]
    pub fn skip_opt_int(&mut self, tag: Tag) -> Result<bool, FastScanError> {
        let [header, _, rest @ ..] = self.remaining else {
            return Ok(false);
        };
        let Some(()) = self.test_ttl(header, tag, Type::Integer, 4) else {
            return Ok(false);
        };
        self.remaining = rest;

        Ok(true)
    }

    /// Skip an optional long integer.
    #[inline]
    pub fn skip_opt_long_int(&mut self, tag: Tag) -> Result<bool, FastScanError> {
        let [header, _, rest @ ..] = self.remaining else {
            return Ok(false);
        };
        let Some(()) = self.test_ttl(header, tag, Type::LongInteger, 8) else {
            return Ok(false);
        };
        self.remaining = rest;

        Ok(true)
    }

    /// Skip an optional big integer.
    #[inline]
    pub fn skip_opt_big_int(&mut self, tag: Tag) -> Result<bool, FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Ok(false);
        };
        let Some(length) = self.test_tt_8l(header, tag, Type::BigInteger) else {
            return Ok(false);
        };
        self.remaining = rest.get(length..).ok_or(FastScanError::assert())?;

        Ok(true)
    }

    /// Skip an optional enumeration.
    #[inline]
    pub fn skip_opt_enum(&mut self, tag: Tag) -> Result<bool, FastScanError> {
        let [header, _, rest @ ..] = self.remaining else {
            return Ok(false);
        };
        let Some(()) = self.test_ttl(header, tag, Type::Enumeration, 4) else {
            return Ok(false);
        };
        self.remaining = rest;

        Ok(true)
    }

    /// Skip an optional boolean.
    #[inline]
    pub fn skip_opt_bool(&mut self, tag: Tag) -> Result<bool, FastScanError> {
        let [header, _, rest @ ..] = self.remaining else {
            return Ok(false);
        };
        let Some(()) = self.test_ttl(header, tag, Type::Boolean, 8) else {
            return Ok(false);
        };
        self.remaining = rest;

        Ok(true)
    }

    /// Skip an optional text string.
    #[inline]
    pub fn skip_opt_text(&mut self, tag: Tag) -> Result<bool, FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Ok(false);
        };
        let Some(length) = self.test_tt(header, tag, Type::TextString) else {
            return Ok(false);
        };
        self.remaining = rest.get(length.div_ceil(8)..).ok_or(FastScanError::assert())?;

        Ok(true)
    }

    /// Skip an optional byte string.
    #[inline]
    pub fn skip_opt_bytes(&mut self, tag: Tag) -> Result<bool, FastScanError> {
        let [header, rest @ ..] = self.remaining else {
            return Ok(false);
        };
        let Some(length) = self.test_tt(header, tag, Type::ByteString) else {
            return Ok(false);
        };
        self.remaining = rest.get(length.div_ceil(8)..).ok_or(FastScanError::assert())?;

        Ok(true)
    }

    /// Skip an optional date-time.
    #[inline]
    pub fn skip_opt_date_time(&mut self, tag: Tag) -> Result<bool, FastScanError> {
        let [header, _, rest @ ..] = self.remaining else {
            return Ok(false);
        };
        let Some(()) = self.test_ttl(header, tag, Type::DateTime, 8) else {
            return Ok(false);
        };
        self.remaining = rest;

        Ok(true)
    }

    /// Skip an optional interval.
    #[inline]
    pub fn skip_opt_interval(&mut self, tag: Tag) -> Result<bool, FastScanError> {
        let [header, _, rest @ ..] = self.remaining else {
            return Ok(false);
        };
        let Some(()) = self.test_ttl(header, tag, Type::Interval, 4) else {
            return Ok(false);
        };
        self.remaining = rest;

        Ok(true)
    }
}

//============ Errors ==========================================================

/// An error from a [`FastScanner`].
///
/// [`FastScanner`] deliberately elides information about the error, in order
/// to run more efficiently.  As such, this is a trivial zero-sized type.
///
/// ## Interpretation
///
/// Presumably, the input was received from an external entity.  This error
/// indicates a miscommunication between that entity and the caller.  There
/// are three expected causes of such miscommunication:
///
/// - Incompatibility (e.g. the entity expects the caller to understand more
///   than it does).  This is a persistent error, but may be localized to the
///   particular kind of input message.
///
/// - Transport error (e.g. the input was corrupted during network transfer).
///   This is an ephemeral error.
///
/// - Implementation bug (e.g. in the external entity).  This is a persistent
///   error, but may be localized to the particular kind of input message.
///
/// The caller can distinguish incompatibilities from the lower-level errors
/// by re-parsing the input using a different scanner.  In order to distinguish
/// transport errors from implementation bugs, the caller has to continue
/// operation and detect reoccurring parsing failures.
//
// TODO: Link to 'SlowScanner' once it exists.
///
/// ## Reaction
///
/// The caller can react to this error in a few ways:
///
/// - Assume the error was ephemeral and continue communicating with the
///   external entity as normal.  The caller should remember that the error
///   occurred and switch to a different reaction if it reoccurs.
///
/// - Actively work around the issue by parsing the input differently.  This
///   implies significant implementation burden, and is not recommended.
///
/// - Avoid receiving similar messages from the external entity (e.g. by
///   avoiding making the same kinds of requests to it, or informing it that
///   its message could not be parsed).  This is only feasible if the
///   communication is non-critical functionality for the caller.
///
/// - Crash.  This is ideal if the error prevents the caller from fulfilling
///   critical functionality.
///
/// The caller should re-parse the input using a different scanner; if the error
/// appears to be an incompatibility, it should avoid receiving such messages
/// from the entity.  If this is not possible, it should crash.  If the error
/// appears to be a lower-level bug, the caller should assume it is ephemeral
/// and continue operation.  If the error is persistent, it should avoid
/// receiving similar messages, or crash.
//
// TODO: Link to 'SlowScanner' once it exists.
pub struct FastScanError {
    /// A backtrace.
    #[cfg(debug_assertions)]
    backtrace: std::backtrace::Backtrace,

    /// Force this 'struct' to be private.
    _private: (),
}

impl FastScanError {
    /// Assert an error.
    pub fn assert() -> Self {
        Self {
            #[cfg(debug_assertions)]
            backtrace: std::backtrace::Backtrace::force_capture(),
            _private: (),
        }
    }
}

impl std::error::Error for FastScanError {}

impl fmt::Debug for FastScanError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        #[cfg(debug_assertions)]
        {
            f.debug_struct("FastScanError")
                .field("backtrace", &self.backtrace)
                .finish()
        }

        #[cfg(not(debug_assertions))]
        {
            f.write_str("a fast-scanning error occurred")
        }
    }
}

impl fmt::Display for FastScanError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("a fast-scanning error occurred")?;
        #[cfg(debug_assertions)]
        {
            write!(f, "\nBacktrace:\n{}", self.backtrace)?;
        }
        Ok(())
    }
}

impl PartialEq for FastScanError {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}

impl Eq for FastScanError {}