Skip to main content

kmip_protocol/ttlv/
fast_scan.rs

1//! Deserializing TTLV elements quickly.
2//!
3//! This module provides low-level TTLV deserialization support.  It is entirely
4//! manual -- it does not provide a declarative interface.  It is designed for
5//! fast, streaming, zero-copy operation.
6
7use core::fmt;
8
9use crate::ttlv::types::Type;
10
11use super::types::Tag;
12
13//----------- FastScanner ----------------------------------------------------
14
15/// A fast TTLV scanner.
16///
17/// In most cases, errors are highly unlikely.  This scanner optimizes for this
18/// by omitting error handling and pinpointing facilities -- it detects errors
19/// without tracking any details of them.  In some cases, it will delay errors,
20/// returning garbage data instead of [`Err`].  If scanning with [`FastScanner`]
21/// fails, a different scanner (e.g. [`crate::ttlv::from_slice()`]) needs to be
22/// used to ascertain the position and cause of the error.
23//
24// TODO: Link to 'SlowScanner' instead, once it exists.
25///
26/// ## Delayed Errors
27///
28/// For efficiency, the scanner will sometimes return invalid data, e.g. from
29/// [`Self::scan_int()`].  This only occurs if the input is invalid, but it is
30/// more efficient than returning an actual [`Err`].  Once invalid data has been
31/// returned, at any point, [`Self::has_delayed_error()`] will report `true`.
32///
33/// The caller should never "trust" the data being returned, e.g. to decide how
34/// much memory to allocate.  Any field can return invalid data; the input may
35/// be well-formed but contain an unexpected value for a field.
36///
37/// ## Streaming Operation
38///
39/// [`FastScanner`] can be used in streaming fashion.  For example, when
40/// receiving a stream of serialized items (e.g. KMIP requests), one cannot
41/// wait for the end of the stream to parse.  Instead, the user should store the
42/// input in a dynamically allocated buffer.  Once some data is in the buffer, a
43/// [`FastScanner`] can be initialized over it, and [`Self::have_next()`] can be
44/// used to check whether a complete TTLV item is available.  If it is, the item
45/// can be parsed; otherwise, more data needs to be buffered.
46///
47/// ```no_run
48/// # use std::{io::Read, net::TcpStream};
49/// # use kmip_protocol::ttlv::FastScanner;
50/// #
51/// // Buffer data in a `Vec`.
52/// let mut buffer = Vec::new();
53///
54/// // Read some data from the network.
55/// let mut stream = TcpStream::connect("127.0.0.1:8000").unwrap();
56/// stream.set_nonblocking(true).unwrap();
57/// loop {
58///     // Fill the buffer as much as possible.
59///     // NOTE: Only ignore 'std::io::ErrorKind::WouldBlock'.
60///     let _ = stream.read_to_end(&mut buffer);
61///
62///     // Try parsing whole TTLV elements from the buffer.
63///     while let Some((mut scanner, rest)) = FastScanner::next_element(&buffer) {
64///         // Read the TTLV element out.
65///         //...
66///
67///         // Remove the parsed data from the buffer.
68///         // NOTE: This is quite inefficient, use a better data structure.
69///         let remaining = rest.len();
70///         let consumed = buffer.len() - remaining;
71///         buffer.drain(0..consumed);
72///     }
73/// }
74/// ```
75#[derive(Clone)]
76pub struct FastScanner<'a> {
77    /// The currently remaining input.
78    ///
79    /// TTLV elements are always serialized into multiples of 8 bytes.  The
80    /// first 8-byte block of each element contains the tag, type, and length;
81    /// even if the content is less than 8 bytes, it gets padded.  By tracking
82    /// these blocks, we can use 64-bit integer operations to process 8 bytes at
83    /// a time, which is far more efficient than byte-by-byte scanning.
84    remaining: &'a [[u8; 8]],
85
86    pub tag: Option<Tag>,
87
88    /// A machine word indicating failure.
89    ///
90    /// This is non-zero if an error was detected and delayed.  Conceptually, it
91    /// is just a boolean.  Most operations here deal with 64-bit units of data
92    /// (i.e. "machine words") from TTLV; representing failure data in the same
93    /// way unlocks many simplifications.
94    ///
95    /// So what exactly is the problem with defining this as a `bool`?  A `bool`
96    /// is represented in memory as a 0 or a 1.  But during scanning, failure
97    /// could be represented in other ways, e.g. a 64-bit integer with certain
98    /// bits set.  The generated code would have to convert all representations
99    /// of failure into a 0 or 1, and this cost adds up.
100    ///
101    /// Side note: in some cases, LLVM could optimize around a `bool` by keeping
102    /// it in a register and then changing its representation; but this heavily
103    /// depends on the local control flow it can see.  Its "vision" is limited
104    /// and gets obscured by function calls.
105    failure_word: u64,
106}
107
108impl<'a> FastScanner<'a> {
109    /// Construct a new [`FastScanner`].
110    ///
111    /// It is expected that the input will be scanned in its entirety.
112    ///
113    /// ## Errors
114    ///
115    /// Fails if the input is not a multiple of 8 bytes.  TTLV elements are
116    /// always serialized into multiples of 8 bytes, so the presence of a
117    /// partial 8-byte block immediately implies the input is invalid.
118    pub fn new(input: &'a [u8]) -> Result<Self, FastScanError> {
119        let (input, &[]) = input.as_chunks() else {
120            // The input contains a partial block.
121            return Err(FastScanError::assert());
122        };
123
124        Ok(Self::from_blocks(input))
125    }
126
127    /// Prepare to parse the next TTLV element from a buffer.
128    ///
129    /// If a whole TTLV element is present in the input, [`Some`] is returned,
130    /// with a scanner ready to parse that element and the unused portion of
131    /// the buffer.  Otherwise, [`None`] is returned, and more data needs to be
132    /// collected for parsing.
133    ///
134    /// See [the `FastScanner` documentation on streaming
135    /// operation](Self#streaming-operation) for more details.
136    pub fn next_element(input: &'a [u8]) -> Option<(Self, &'a [u8])> {
137        // Retrieve the header of the next element.
138        let header = input.first_chunk::<8>()?;
139
140        // Determine how many bytes are needed to parse this element.
141        let length = u32::from_be_bytes(header[4..].try_into().unwrap());
142        // If this fails, the element will never fit in memory.
143        let length = usize::try_from(length).ok()?;
144        // Round up to a whole number of blocks and count the header.
145        let length = 8 + length.next_multiple_of(8);
146
147        // Try extracting the whole element from the input.
148        let (elem, rest) = input.split_at_checked(length)?;
149
150        // SAFETY: 'length' is always a multiple of 8.
151        let elem = unsafe { elem.as_chunks_unchecked() };
152
153        Some((Self::from_blocks(elem), rest))
154    }
155
156    /// Construct a new [`FastScanner`] from a slice of 8-byte blocks.
157    ///
158    /// TTLV elements are always serialized into multiples of 8 bytes.
159    /// [`FastScanner`] internally represents its input as slices of 8-byte
160    /// blocks so it is easier to process.
161    pub const fn from_blocks(input: &'a [[u8; 8]]) -> Self {
162        Self {
163            remaining: input,
164            failure_word: 0,
165            tag: None,
166        }
167    }
168
169    /// The remaining input to the scanner.
170    ///
171    /// Note: in case an error has occurred (delayed or otherwise), the amount
172    /// of remaining data is not well specified.  It might not include the data
173    /// causing the failure.
174    pub const fn remaining(&self) -> &'a [[u8; 8]] {
175        self.remaining
176    }
177
178    /// Whether the scanner is finished.
179    pub const fn is_empty(&self) -> bool {
180        self.remaining.is_empty()
181    }
182
183    /// Whether an error has been delayed.
184    ///
185    /// This should be checked before acting on any parsed data.  If an error
186    /// has been delayed, all previously-returned data should be assumed to be
187    /// garbage.  See [the `FastScanner` documentation](Self#delayed-errors) for
188    /// more information about delayed errors.
189    pub const fn has_delayed_error(&self) -> bool {
190        self.failure_word != 0
191    }
192
193    /// Whether an entire TTLV element is available.
194    ///
195    /// The length of the next element will be checked;
196    ///
197    ///   - if it is entirely loaded in the buffer, Ok(()) will be returned.
198    ///   - if the buffer is empty, Err(None) will be returned.
199    ///   - if the buffer is partially full, the L (from TT_L_V) value must be
200    ///     available and so Err(Some(n)) is returned when n is the number of
201    ///     missing bytes where n > 0.
202    ///
203    /// This can be used for streamed parsing, to decide whether more data
204    /// needs to be buffered and, if known, how much more data needs to be
205    /// fetched from the source.
206    pub fn have_next(&self) -> Result<(), Option<u32>> {
207        let [header, rest @ ..] = self.remaining else {
208            return Err(None);
209        };
210
211        let length = u32::from_be_bytes(header[4..8].try_into().unwrap());
212        let available = rest.as_flattened().len();
213
214        let missing = if usize::BITS >= u32::BITS {
215            // 'usize' is at least as big as 'u32'.
216            // SAFETY: Since length cannot be larger than a u32 the result
217            // of subtracting a value from length cannot be larger than a u32.
218            (length as usize).checked_sub(available).map(|v| v as u32)
219        } else {
220            // 'u32' is bigger than 'usize'.
221            length.checked_sub(available as u32)
222        };
223
224        match missing {
225            // More bytes are available than needed
226            None => Ok(()),
227
228            // We have exactly the number of needed bytes.
229            Some(0) => Ok(()),
230
231            // We have n bytes less than we need.
232            Some(n) => Err(Some(n)),
233        }
234    }
235
236    /// Finish the scanner.
237    ///
238    /// If there is remaining input, or an error was delayed, [`Err`] is
239    /// returned.  If additional remaining input is allowed, use
240    /// [`Self::finish_non_exhaustive()`] instead.
241    pub fn finish(self) -> Result<(), FastScanError> {
242        if self.is_empty() && !self.has_delayed_error() {
243            Ok(())
244        } else {
245            Err(FastScanError::assert())
246        }
247    }
248
249    /// Finish the scanner non-exhaustively.
250    ///
251    /// Additional input is ignored.  [`Err`] is returned only if an error is
252    /// delayed.  If additional remaining input is not allowed, use
253    /// [`Self::finish()`] instead.
254    pub fn finish_non_exhaustive(self) -> Result<(), FastScanError> {
255        if !self.has_delayed_error() {
256            Ok(())
257        } else {
258            Err(FastScanError::assert())
259        }
260    }
261}
262
263/// # Scanning Helpers
264//
265// Lemmas:
266// - `u64::from_be_bytes(*header) == u64::from_be(u64::from_ne_bytes(*header))`.
267// - `u64::from_ne_bytes(*header) == u64::from_be_bytes(*header).to_be()`.
268// - `a.to_be() ^ b.to_be() == (a ^ b).to_be()`.
269//
270// Conventions:
271// - `check_*` updates `self.failure_word` on error.
272// - `test_*` returns `None` on error.
273// - `calc_*` returns a non-zero `u64` on error.
274impl<'a> FastScanner<'a> {
275    /// Verify that a header has a particular tag, type, and length.
276    ///
277    /// An incorrect header will result in a delayed error.
278    #[inline(always)]
279    fn check_ttl(&mut self, header: &[u8; 8], tag: Tag, r#type: Type, length: u32) {
280        self.failure_word |= Self::calc_ttl(header, tag, r#type, length);
281    }
282
283    /// Test that a header has a particular tag, type, and length.
284    ///
285    /// Returns `true` if it does.
286    #[inline(always)]
287    fn test_ttl(&self, header: &[u8; 8], tag: Tag, r#type: Type, length: u32) -> Option<()> {
288        let mismatch = Self::calc_ttl(header, tag, r#type, length);
289        (mismatch == 0).then_some(())
290    }
291
292    #[inline(always)]
293    fn calc_ttl(header: &[u8; 8], tag: Tag, r#type: Type, length: u32) -> u64 {
294        // Prepare an expected value as a big-endian integer.
295        //
296        // The compiler should be able to fold this computation into a simple
297        // hard-coded 64-bit constant.
298        let expected = ((tag.with_type(r#type).value() as u64) << 32 | (length as u64)).to_be();
299
300        // Load the header without changing its endianness, so that it and
301        // 'expected' have matching byte layouts.
302        let actual = u64::from_ne_bytes(*header);
303
304        // Return non-zero if at least one bit in the actual header did not
305        // match.
306        actual ^ expected
307    }
308
309    /// Verify that a header has a particular tag and type, and a length that is
310    /// a multiple of 8.
311    ///
312    /// The length is returned, and is in units of 8-byte blocks.
313    ///
314    /// An incorrect header will result in a delayed error.
315    #[inline(always)]
316    fn check_tt_8l(&mut self, header: &[u8; 8], tag: Tag, r#type: Type) -> usize {
317        let (mismatch, length) = Self::calc_tt_8l(header, tag, r#type);
318        self.failure_word |= mismatch;
319        length
320    }
321
322    /// Test that a header has a particular tag and type, and a length that is
323    /// a multiple of 8.
324    ///
325    /// If the header matches, a length is returned, in units of 8-byte blocks.
326    #[inline(always)]
327    fn test_tt_8l(&self, header: &[u8; 8], tag: Tag, r#type: Type) -> Option<usize> {
328        let (mismatch, length) = Self::calc_tt_8l(header, tag, r#type);
329        (mismatch == 0).then_some(length)
330    }
331
332    #[inline(always)]
333    fn calc_tt_8l(header: &[u8; 8], tag: Tag, r#type: Type) -> (u64, usize) {
334        // Generate a mask for the length.
335        //
336        // We need to make sure the low 3 bits of the length are zero.
337        //
338        // We don't need to support lengths that can't fit in 'usize'; such
339        // objects wouldn't fit in memory.  If 'usize' is smaller than 'u32',
340        // we'll include the non-'usize' bits in the mask, and so ensure that
341        // they are zero in the actual header.
342        //
343        // This is 0xFFFF_0007 on 16-bit, else 0x0000_0007.
344        const LENGTH_MASK: u32 = !(usize::MAX as u32) | 0x07;
345
346        // Generate a mask for the whole header.
347        //
348        // We always check the top 4 bytes (tag and type).
349        const MASK: u64 = u64::MAX << 32 | LENGTH_MASK as u64;
350
351        // Prepare an expected value as a native-endian integer.
352        //
353        // The length field is set to all-zeros; we will check that 'header'
354        // contains the same bits, but only for 'LENGTH_MASK'.
355        //
356        // The compiler should be able to fold this computation into a simple
357        // hard-coded 64-bit constant.
358        let expected = (tag.with_type(r#type).value() as u64) << 32;
359
360        // Load the header into the right endianness, as we need to read out its
361        // low 32 bits for the length field.  Note that it and 'expected' have
362        // matching byte layouts.
363        let actual = u64::from_be_bytes(*header);
364
365        // Return non-zero if at least one bit in the actual header (of the tag,
366        // type, or low 3 bits of length) did not match.
367        let mismatch = (actual ^ expected) & MASK;
368
369        // Extract and return the length, in units of 8-byte blocks.  We have
370        // already checked that it fits in a 'usize', so cast to that.
371        //
372        // Note that the division by 8 happens after casting; otherwise the top
373        // 3 bits of the type would get thrown in here by accident.
374        let length = (actual as u32 as usize) / 8;
375
376        (mismatch, length)
377    }
378
379    /// Verify that a header has a particular tag and type.
380    ///
381    /// No restrictions are placed on the length field, which is returned in
382    /// units of bytes.
383    ///
384    /// An incorrect header will result in a delayed error.
385    #[inline(always)]
386    fn check_tt(&mut self, header: &[u8; 8], tag: Tag, r#type: Type) -> usize {
387        let (mismatch, length) = Self::calc_tt(header, tag, r#type);
388        self.failure_word |= mismatch;
389        length
390    }
391
392    #[inline(always)]
393    fn test_tt(&self, header: &[u8; 8], tag: Tag, r#type: Type) -> Option<usize> {
394        let (mismatch, length) = Self::calc_tt(header, tag, r#type);
395        (mismatch == 0).then_some(length)
396    }
397
398    #[inline(always)]
399    fn calc_tt(header: &[u8; 8], tag: Tag, r#type: Type) -> (u64, usize) {
400        // If 'u32' can fit in a 'usize', then the encoded length is always a
401        // valid 'usize'.  Load the tag-type half and the length as separate
402        // 32-bit words; that way, we only hard-code 32-bit integer constants.
403        if usize::BITS >= u32::BITS {
404            // Prepare an expected value as a big-endian integer.
405            //
406            // This only accounts for the tag and type.
407            //
408            // The compiler should be able to fold this computation into a
409            // simple hard-coded 32-bit constant.
410            let expected = tag.with_type(r#type).value().to_be();
411
412            // Load the tag-type part of the header without changing its
413            // endianness, so that it and 'expected' have matching byte layouts.
414            //
415            // NOTE: This 'unwrap()' is guaranteed to never fail.
416            let actual = u32::from_ne_bytes(header[..4].try_into().unwrap());
417
418            // Make the failure word non-zero if at least one bit in the actual
419            // header (of the tag or type) did not match.
420            let mismatch = (actual ^ expected) as u64;
421
422            // Load the length part of the header into native endianness.
423            let length = u32::from_be_bytes(header[4..].try_into().unwrap());
424
425            // We know 'u32' fits in a 'usize', so we can cast directly.
426            (mismatch, length as usize)
427        } else {
428            // Generate a mask for the length.
429            //
430            // We don't need to support lengths that can't fit in 'usize';
431            // such objects wouldn't fit in memory.  If 'usize' is smaller than
432            // 'u32', we'll include the non-'usize' bits in the mask, and so
433            // ensure that they are zero in the actual header.
434            //
435            // This is 0xFFFF_0000 on 16-bit.
436            const LENGTH_MASK: u32 = !(usize::MAX as u32);
437
438            // Generate a mask for the whole header.
439            //
440            // We always check the top 4 bytes (tag and type).
441            const MASK: u64 = u64::MAX << 32 | LENGTH_MASK as u64;
442
443            // Prepare an expected value as a native-endian integer.
444            //
445            // The length field is set to all-zeros; we will check that 'header'
446            // contains the same bits, but only for 'LENGTH_MASK'.
447            //
448            // The compiler should be able to fold this computation into a
449            // simple hard-coded 64-bit constant.
450            let expected = (tag.with_type(r#type).value() as u64) << 32;
451
452            // Load the header into the right endianness, as we need to read out
453            // its low bits for the length field.  Note that it and 'expected'
454            // have matching byte layouts.
455            let actual = u64::from_be_bytes(*header);
456
457            // Make the failure word non-zero if at least one bit in the actual
458            // header (of the tag, type, or high part of length) did not match.
459            let mismatch = (actual ^ expected) & MASK;
460
461            // We have already checked that the length fits in a 'usize', so we
462            // can freely truncate the value now.
463            (mismatch, actual as u32 as usize)
464        }
465    }
466}
467
468impl<'a> FastScanner<'a> {
469    /// Scan an expected structure.
470    ///
471    /// The returned sub-scanner can be used to scan the fields of the
472    /// `struct`; `self` will independently continue from the end of the
473    /// `struct`.
474    #[must_use = "Use the returned scanner to parse the structure, or use `FastScanner::skip_struct()` to ignore its contents"]
475    #[inline]
476    pub fn scan_struct(&mut self, tag: Tag) -> Result<Self, FastScanError> {
477        let [header, rest @ ..] = self.remaining else {
478            return Err(FastScanError::assert());
479        };
480        let length = self.check_tt_8l(header, tag, Type::Structure);
481        let (body, rest) = rest.split_at_checked(length).ok_or(FastScanError::assert())?;
482        self.remaining = rest;
483
484        Ok(Self::from_blocks(body))
485    }
486
487    /// Scan an expected structure with a pre-determined length.
488    ///
489    /// The returned sub-scanner can be used scan the fields of the `struct`;
490    /// `self` will independently continue from the end of the `struct`.  If
491    /// the length encoded in the input is different from the pre-determined
492    /// length, the error will be delayed and both scanners will return
493    /// garbage.
494    #[must_use = "Use the returned scanner to parse the structure, or use `FastScanner::skip_fixed_struct()` to ignore its contents"]
495    #[inline]
496    pub fn scan_fixed_struct(&mut self, tag: Tag, length: u32) -> Result<Self, FastScanError> {
497        debug_assert!(length.is_multiple_of(8));
498        if self.remaining.len() < 1 + length as usize / 8 {
499            return Err(FastScanError::assert());
500        }
501        let (header, rest) = self.remaining.split_first().unwrap();
502        self.check_ttl(header, tag, Type::Structure, length);
503        let (body, rest) = rest.split_at(length as usize / 8);
504        self.remaining = rest;
505
506        Ok(Self::from_blocks(body))
507    }
508
509    /// Scan an expected integer.
510    #[must_use = "Use the returned value, or use `FastScanner::skip_int()` to ignore it"]
511    #[inline]
512    pub fn scan_int(&mut self, tag: Tag) -> Result<i32, FastScanError> {
513        let [header, value, rest @ ..] = self.remaining else {
514            return Err(FastScanError::assert());
515        };
516        self.check_ttl(header, tag, Type::Integer, 4);
517        self.remaining = rest;
518
519        Ok(i32::from_be_bytes(value[0..4].try_into().unwrap()))
520    }
521
522    /// Scan an expected long integer.
523    #[must_use = "Use the returned value, or use `FastScanner::skip_long_int()` to ignore it"]
524    #[inline]
525    pub fn scan_long_int(&mut self, tag: Tag) -> Result<i64, FastScanError> {
526        let [header, value, rest @ ..] = self.remaining else {
527            return Err(FastScanError::assert());
528        };
529        self.check_ttl(header, tag, Type::LongInteger, 8);
530        self.remaining = rest;
531
532        Ok(i64::from_be_bytes(*value))
533    }
534
535    /// Scan an expected big integer.
536    #[must_use = "Use the returned value, or use `FastScanner::skip_big_int()` to ignore it"]
537    #[inline]
538    pub fn scan_big_int(&mut self, tag: Tag) -> Result<&'a [u8], FastScanError> {
539        let [header, rest @ ..] = self.remaining else {
540            return Err(FastScanError::assert());
541        };
542        let length = self.check_tt_8l(header, tag, Type::BigInteger);
543        let (body, rest) = rest.split_at_checked(length).ok_or(FastScanError::assert())?;
544        self.remaining = rest;
545
546        Ok(body.as_flattened())
547    }
548
549    /// Scan an expected enumeration.
550    #[must_use = "Use the returned value, or use `FastScanner::skip_enum()` to ignore it"]
551    #[inline]
552    pub fn scan_enum(&mut self, tag: Tag) -> Result<u32, FastScanError> {
553        let [header, value, rest @ ..] = self.remaining else {
554            return Err(FastScanError::assert());
555        };
556        self.check_ttl(header, tag, Type::Enumeration, 4);
557        self.remaining = rest;
558
559        Ok(u32::from_be_bytes(value[0..4].try_into().unwrap()))
560    }
561
562    /// Scan an expected boolean.
563    #[must_use = "Use the returned value, or use `FastScanner::skip_bool()` to ignore it"]
564    #[inline]
565    pub fn scan_bool(&mut self, tag: Tag) -> Result<bool, FastScanError> {
566        let [header, value, rest @ ..] = self.remaining else {
567            return Err(FastScanError::assert());
568        };
569        self.check_ttl(header, tag, Type::Boolean, 8);
570        // Load the value without changing its endianness.
571        let value = u64::from_ne_bytes(*value);
572        // Check that all bits except the lowest are zero.
573        self.failure_word |= value & !u64::from_be(1);
574        self.remaining = rest;
575
576        Ok(value != 0)
577    }
578
579    /// Scan an expected text string.
580    #[must_use = "Use the returned value, or use `FastScanner::skip_text()` to ignore it"]
581    #[inline]
582    pub fn scan_text(&mut self, tag: Tag) -> Result<&'a str, FastScanError> {
583        let [header, rest @ ..] = self.remaining else {
584            return Err(FastScanError::assert());
585        };
586        let length = self.check_tt(header, tag, Type::TextString);
587        let body = rest.as_flattened().get(..length).ok_or(FastScanError::assert())?;
588        let body = core::str::from_utf8(body).map_err(|_| FastScanError::assert())?;
589        self.remaining = &rest[length.div_ceil(8)..];
590
591        Ok(body)
592    }
593
594    /// Scan an expected text string as bytes.
595    #[must_use = "Use the returned value, or use `FastScanner::skip_text()` to ignore it"]
596    #[inline]
597    pub fn scan_text_bytes(&mut self, tag: Tag) -> Result<&'a [u8], FastScanError> {
598        let [header, rest @ ..] = self.remaining else {
599            return Err(FastScanError::assert());
600        };
601        let length = self.check_tt(header, tag, Type::TextString);
602        let body = rest.as_flattened().get(..length).ok_or(FastScanError::assert())?;
603        self.remaining = &rest[length.div_ceil(8)..];
604
605        Ok(body)
606    }
607
608    /// Scan an expected byte string.
609    #[must_use = "Use the returned value, or use `FastScanner::skip_bytes()` to ignore it"]
610    #[inline]
611    pub fn scan_bytes(&mut self, tag: Tag) -> Result<&'a [u8], FastScanError> {
612        let [header, rest @ ..] = self.remaining else {
613            return Err(FastScanError::assert());
614        };
615        let length = self.check_tt(header, tag, Type::ByteString);
616        let body = rest.as_flattened().get(..length).ok_or(FastScanError::assert())?;
617        self.remaining = &rest[length.div_ceil(8)..];
618
619        Ok(body)
620    }
621
622    /// Scan an expected date-time.
623    #[must_use = "Use the returned value, or use `FastScanner::skip_date_time()` to ignore it"]
624    #[inline]
625    pub fn scan_date_time(&mut self, tag: Tag) -> Result<i64, FastScanError> {
626        let [header, value, rest @ ..] = self.remaining else {
627            return Err(FastScanError::assert());
628        };
629        self.check_ttl(header, tag, Type::DateTime, 8);
630        self.remaining = rest;
631
632        Ok(i64::from_be_bytes(*value))
633    }
634
635    /// Scan an expected interval.
636    #[must_use = "Use the returned value, or use `FastScanner::skip_interval()` to ignore it"]
637    #[inline]
638    pub fn scan_interval(&mut self, tag: Tag) -> Result<u32, FastScanError> {
639        let [header, value, rest @ ..] = self.remaining else {
640            return Err(FastScanError::assert());
641        };
642        self.check_ttl(header, tag, Type::Interval, 4);
643        self.remaining = rest;
644
645        Ok(u32::from_be_bytes(value[0..4].try_into().unwrap()))
646    }
647}
648
649impl FastScanner<'_> {
650    /// Skip an expected structure.
651    #[inline]
652    pub fn skip_struct(&mut self, tag: Tag) -> Result<(), FastScanError> {
653        let [header, rest @ ..] = self.remaining else {
654            return Err(FastScanError::assert());
655        };
656        let length = self.check_tt_8l(header, tag, Type::Structure);
657        self.remaining = rest.get(length..).ok_or(FastScanError::assert())?;
658
659        Ok(())
660    }
661
662    /// Skip an expected structure with a pre-determined length.
663    #[inline]
664    pub fn skip_fixed_struct(&mut self, tag: Tag, length: u32) -> Result<(), FastScanError> {
665        debug_assert!(length.is_multiple_of(8));
666        if self.remaining.len() < 1 + length as usize / 8 {
667            return Err(FastScanError::assert());
668        }
669        self.check_ttl(&self.remaining[0], tag, Type::Structure, length);
670        self.remaining = &self.remaining[1 + length as usize / 8..];
671
672        Ok(())
673    }
674
675    /// Skip an expected integer.
676    #[inline]
677    pub fn skip_int(&mut self, tag: Tag) -> Result<(), FastScanError> {
678        let [header, _, rest @ ..] = self.remaining else {
679            return Err(FastScanError::assert());
680        };
681        self.check_ttl(header, tag, Type::Integer, 4);
682        self.remaining = rest;
683
684        Ok(())
685    }
686
687    /// Skip an expected long integer.
688    #[inline]
689    pub fn skip_long_int(&mut self, tag: Tag) -> Result<(), FastScanError> {
690        let [header, _, rest @ ..] = self.remaining else {
691            return Err(FastScanError::assert());
692        };
693        self.check_ttl(header, tag, Type::LongInteger, 8);
694        self.remaining = rest;
695
696        Ok(())
697    }
698
699    /// Skip an expected big integer.
700    #[inline]
701    pub fn skip_big_int(&mut self, tag: Tag) -> Result<(), FastScanError> {
702        let [header, rest @ ..] = self.remaining else {
703            return Err(FastScanError::assert());
704        };
705        let length = self.check_tt_8l(header, tag, Type::BigInteger);
706        self.remaining = rest.get(length..).ok_or(FastScanError::assert())?;
707
708        Ok(())
709    }
710
711    /// Skip an expected enumeration.
712    #[inline]
713    pub fn skip_enum(&mut self, tag: Tag) -> Result<(), FastScanError> {
714        let [header, _, rest @ ..] = self.remaining else {
715            return Err(FastScanError::assert());
716        };
717        self.check_ttl(header, tag, Type::Enumeration, 4);
718        self.remaining = rest;
719
720        Ok(())
721    }
722
723    /// Skip an expected boolean.
724    #[inline]
725    pub fn skip_bool(&mut self, tag: Tag) -> Result<(), FastScanError> {
726        let [header, _, rest @ ..] = self.remaining else {
727            return Err(FastScanError::assert());
728        };
729        self.check_ttl(header, tag, Type::Boolean, 8);
730        self.remaining = rest;
731
732        Ok(())
733    }
734
735    /// Skip an expected text string.
736    #[inline]
737    pub fn skip_text(&mut self, tag: Tag) -> Result<(), FastScanError> {
738        let [header, rest @ ..] = self.remaining else {
739            return Err(FastScanError::assert());
740        };
741        let length = self.check_tt(header, tag, Type::TextString);
742        self.remaining = rest.get(length.div_ceil(8)..).ok_or(FastScanError::assert())?;
743
744        Ok(())
745    }
746
747    /// Skip an expected byte string.
748    #[inline]
749    pub fn skip_bytes(&mut self, tag: Tag) -> Result<(), FastScanError> {
750        let [header, rest @ ..] = self.remaining else {
751            return Err(FastScanError::assert());
752        };
753        let length = self.check_tt(header, tag, Type::ByteString);
754        self.remaining = rest.get(length.div_ceil(8)..).ok_or(FastScanError::assert())?;
755
756        Ok(())
757    }
758
759    /// Skip an expected date-time.
760    #[inline]
761    pub fn skip_date_time(&mut self, tag: Tag) -> Result<(), FastScanError> {
762        let [header, _, rest @ ..] = self.remaining else {
763            return Err(FastScanError::assert());
764        };
765        self.check_ttl(header, tag, Type::DateTime, 8);
766        self.remaining = rest;
767
768        Ok(())
769    }
770
771    /// Skip an expected interval.
772    #[inline]
773    pub fn skip_interval(&mut self, tag: Tag) -> Result<(), FastScanError> {
774        let [header, _, rest @ ..] = self.remaining else {
775            return Err(FastScanError::assert());
776        };
777        self.check_ttl(header, tag, Type::Interval, 4);
778        self.remaining = rest;
779
780        Ok(())
781    }
782}
783
784impl<'a> FastScanner<'a> {
785    /// Scan an optional structure.
786    ///
787    /// The returned sub-scanner can be used to scan the fields of the
788    /// `struct`; `self` will independently continue from the end of the
789    /// `struct`.
790    #[must_use = "Use the returned scanner to parse the structure, or use `FastScanner::skip_opt_struct()` to ignore its contents"]
791    #[inline]
792    pub fn scan_opt_struct(&mut self, tag: Tag) -> Result<Option<Self>, FastScanError> {
793        let [header, rest @ ..] = self.remaining else {
794            return Ok(None);
795        };
796        let Some(length) = self.test_tt_8l(header, tag, Type::Structure) else {
797            return Ok(None);
798        };
799        let (body, rest) = rest.split_at_checked(length).ok_or(FastScanError::assert())?;
800        self.remaining = rest;
801
802        Ok(Some(Self::from_blocks(body)))
803    }
804
805    /// Scan an optional structure with a pre-determined length.
806    ///
807    /// The returned sub-scanner can be used to scan the fields of the
808    /// `struct`; `self` will independently continue from the end of the
809    /// `struct`.  If the length encoded in the input is different from the
810    /// pre-determined length, the error will be delayed and both scanners
811    /// will return garbage.
812    #[must_use = "Use the returned scanner to parse the structure, or use `FastScanner::skip_opt_fixed_struct()` to ignore its contents"]
813    #[inline]
814    pub fn scan_opt_fixed_struct(&mut self, tag: Tag, length: u32) -> Result<Option<Self>, FastScanError> {
815        debug_assert!(length.is_multiple_of(8));
816
817        if self.remaining.len() < 1 + length as usize / 8 {
818            return Ok(None);
819        }
820        let (header, rest) = self.remaining.split_first().unwrap();
821        let Some(()) = self.test_ttl(header, tag, Type::Structure, length) else {
822            return Ok(None);
823        };
824        let (body, rest) = rest.split_at(length as usize / 8);
825        self.remaining = rest;
826
827        Ok(Some(Self::from_blocks(body)))
828    }
829
830    /// Scan an optional integer.
831    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_int()` to ignore it"]
832    #[inline]
833    pub fn scan_opt_int(&mut self, tag: Tag) -> Result<Option<i32>, FastScanError> {
834        let [header, value, rest @ ..] = self.remaining else {
835            return Ok(None);
836        };
837        let Some(()) = self.test_ttl(header, tag, Type::Integer, 4) else {
838            return Ok(None);
839        };
840        self.remaining = rest;
841
842        Ok(Some(i32::from_be_bytes(value[0..4].try_into().unwrap())))
843    }
844
845    /// Scan an optional long integer.
846    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_long_int()` to ignore it"]
847    #[inline]
848    pub fn scan_opt_long_int(&mut self, tag: Tag) -> Result<Option<i64>, FastScanError> {
849        let [header, value, rest @ ..] = self.remaining else {
850            return Ok(None);
851        };
852        let Some(()) = self.test_ttl(header, tag, Type::LongInteger, 8) else {
853            return Ok(None);
854        };
855        self.remaining = rest;
856
857        Ok(Some(i64::from_be_bytes(*value)))
858    }
859
860    /// Scan an optional big integer.
861    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_big_int()` to ignore it"]
862    #[inline]
863    pub fn scan_opt_big_int(&mut self, tag: Tag) -> Result<Option<&'a [u8]>, FastScanError> {
864        let [header, rest @ ..] = self.remaining else {
865            return Ok(None);
866        };
867        let Some(length) = self.test_tt_8l(header, tag, Type::BigInteger) else {
868            return Ok(None);
869        };
870        let (body, rest) = rest.split_at_checked(length).ok_or(FastScanError::assert())?;
871        self.remaining = rest;
872
873        Ok(Some(body.as_flattened()))
874    }
875
876    /// Scan an optional enumeration.
877    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_enum()` to ignore it"]
878    #[inline]
879    pub fn scan_opt_enum(&mut self, tag: Tag) -> Result<Option<u32>, FastScanError> {
880        let [header, value, rest @ ..] = self.remaining else {
881            return Ok(None);
882        };
883        let Some(()) = self.test_ttl(header, tag, Type::Enumeration, 4) else {
884            return Ok(None);
885        };
886        self.remaining = rest;
887
888        Ok(Some(u32::from_be_bytes(value[0..4].try_into().unwrap())))
889    }
890
891    /// Scan an optional boolean.
892    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_bool()` to ignore it"]
893    #[inline]
894    pub fn scan_opt_bool(&mut self, tag: Tag) -> Result<Option<bool>, FastScanError> {
895        let [header, value, rest @ ..] = self.remaining else {
896            return Ok(None);
897        };
898        let Some(()) = self.test_ttl(header, tag, Type::Boolean, 8) else {
899            return Ok(None);
900        };
901        // Load the value without changing its endianness.
902        let value = u64::from_ne_bytes(*value);
903        // Check that all bits except the lowest are zero.
904        self.failure_word |= value & !u64::from_be(1);
905        self.remaining = rest;
906
907        Ok(Some(value != 0))
908    }
909
910    /// Scan an optional text string.
911    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_text()` to ignore it"]
912    #[inline]
913    pub fn scan_opt_text(&mut self, tag: Tag) -> Result<Option<&'a str>, FastScanError> {
914        let [header, rest @ ..] = self.remaining else {
915            return Ok(None);
916        };
917        let Some(length) = self.test_tt(header, tag, Type::TextString) else {
918            return Ok(None);
919        };
920        let body = rest.as_flattened().get(..length).ok_or(FastScanError::assert())?;
921        let body = core::str::from_utf8(body).map_err(|_| FastScanError::assert())?;
922        self.remaining = &rest[length.div_ceil(8)..];
923
924        Ok(Some(body))
925    }
926
927    /// Scan an optional text string as bytes.
928    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_text()` to ignore it"]
929    #[inline]
930    pub fn scan_opt_text_bytes(&mut self, tag: Tag) -> Result<Option<&'a [u8]>, FastScanError> {
931        let [header, rest @ ..] = self.remaining else {
932            return Ok(None);
933        };
934        let Some(length) = self.test_tt(header, tag, Type::TextString) else {
935            return Ok(None);
936        };
937        let body = rest.as_flattened().get(..length).ok_or(FastScanError::assert())?;
938        self.remaining = &rest[length.div_ceil(8)..];
939
940        Ok(Some(body))
941    }
942
943    /// Scan an optional byte string.
944    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_bytes()` to ignore it"]
945    #[inline]
946    pub fn scan_opt_bytes(&mut self, tag: Tag) -> Result<Option<&'a [u8]>, FastScanError> {
947        let [header, rest @ ..] = self.remaining else {
948            return Ok(None);
949        };
950        let Some(length) = self.test_tt(header, tag, Type::ByteString) else {
951            return Ok(None);
952        };
953        let body = rest.as_flattened().get(..length).ok_or(FastScanError::assert())?;
954        self.remaining = &rest[length.div_ceil(8)..];
955
956        Ok(Some(body))
957    }
958
959    /// Scan an optional date-time.
960    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_date_time()` to ignore it"]
961    #[inline]
962    pub fn scan_opt_date_time(&mut self, tag: Tag) -> Result<Option<i64>, FastScanError> {
963        let [header, value, rest @ ..] = self.remaining else {
964            return Ok(None);
965        };
966        let Some(()) = self.test_ttl(header, tag, Type::DateTime, 8) else {
967            return Ok(None);
968        };
969        self.remaining = rest;
970
971        Ok(Some(i64::from_be_bytes(*value)))
972    }
973
974    /// Scan an optional interval.
975    #[must_use = "Use the returned value, or use `FastScanner::skip_opt_interval()` to ignore it"]
976    #[inline]
977    pub fn scan_opt_interval(&mut self, tag: Tag) -> Result<Option<u32>, FastScanError> {
978        let [header, value, rest @ ..] = self.remaining else {
979            return Ok(None);
980        };
981        let Some(()) = self.test_ttl(header, tag, Type::Interval, 4) else {
982            return Ok(None);
983        };
984        self.remaining = rest;
985
986        Ok(Some(u32::from_be_bytes(value[0..4].try_into().unwrap())))
987    }
988}
989
990impl<'a> FastScanner<'a> {
991    /// Skip an optional structure.
992    #[inline]
993    pub fn skip_opt_struct(&mut self, tag: Tag) -> Result<bool, FastScanError> {
994        let [header, rest @ ..] = self.remaining else {
995            return Ok(false);
996        };
997        let Some(length) = self.test_tt_8l(header, tag, Type::Structure) else {
998            return Ok(false);
999        };
1000        self.remaining = rest.get(length..).ok_or(FastScanError::assert())?;
1001
1002        Ok(true)
1003    }
1004
1005    /// Skip an optional structure with a pre-determined length.
1006    #[inline]
1007    pub fn skip_opt_fixed_struct(&mut self, tag: Tag, length: u32) -> Result<bool, FastScanError> {
1008        debug_assert!(length.is_multiple_of(8));
1009        if self.remaining.len() < 1 + length as usize / 8 {
1010            return Ok(false);
1011        }
1012        let (header, rest) = self.remaining.split_first().unwrap();
1013        let Some(()) = self.test_ttl(header, tag, Type::Structure, length) else {
1014            return Ok(false);
1015        };
1016        self.remaining = &rest[length as usize / 8..];
1017
1018        Ok(true)
1019    }
1020
1021    /// Skip an optional integer.
1022    #[inline]
1023    pub fn skip_opt_int(&mut self, tag: Tag) -> Result<bool, FastScanError> {
1024        let [header, _, rest @ ..] = self.remaining else {
1025            return Ok(false);
1026        };
1027        let Some(()) = self.test_ttl(header, tag, Type::Integer, 4) else {
1028            return Ok(false);
1029        };
1030        self.remaining = rest;
1031
1032        Ok(true)
1033    }
1034
1035    /// Skip an optional long integer.
1036    #[inline]
1037    pub fn skip_opt_long_int(&mut self, tag: Tag) -> Result<bool, FastScanError> {
1038        let [header, _, rest @ ..] = self.remaining else {
1039            return Ok(false);
1040        };
1041        let Some(()) = self.test_ttl(header, tag, Type::LongInteger, 8) else {
1042            return Ok(false);
1043        };
1044        self.remaining = rest;
1045
1046        Ok(true)
1047    }
1048
1049    /// Skip an optional big integer.
1050    #[inline]
1051    pub fn skip_opt_big_int(&mut self, tag: Tag) -> Result<bool, FastScanError> {
1052        let [header, rest @ ..] = self.remaining else {
1053            return Ok(false);
1054        };
1055        let Some(length) = self.test_tt_8l(header, tag, Type::BigInteger) else {
1056            return Ok(false);
1057        };
1058        self.remaining = rest.get(length..).ok_or(FastScanError::assert())?;
1059
1060        Ok(true)
1061    }
1062
1063    /// Skip an optional enumeration.
1064    #[inline]
1065    pub fn skip_opt_enum(&mut self, tag: Tag) -> Result<bool, FastScanError> {
1066        let [header, _, rest @ ..] = self.remaining else {
1067            return Ok(false);
1068        };
1069        let Some(()) = self.test_ttl(header, tag, Type::Enumeration, 4) else {
1070            return Ok(false);
1071        };
1072        self.remaining = rest;
1073
1074        Ok(true)
1075    }
1076
1077    /// Skip an optional boolean.
1078    #[inline]
1079    pub fn skip_opt_bool(&mut self, tag: Tag) -> Result<bool, FastScanError> {
1080        let [header, _, rest @ ..] = self.remaining else {
1081            return Ok(false);
1082        };
1083        let Some(()) = self.test_ttl(header, tag, Type::Boolean, 8) else {
1084            return Ok(false);
1085        };
1086        self.remaining = rest;
1087
1088        Ok(true)
1089    }
1090
1091    /// Skip an optional text string.
1092    #[inline]
1093    pub fn skip_opt_text(&mut self, tag: Tag) -> Result<bool, FastScanError> {
1094        let [header, rest @ ..] = self.remaining else {
1095            return Ok(false);
1096        };
1097        let Some(length) = self.test_tt(header, tag, Type::TextString) else {
1098            return Ok(false);
1099        };
1100        self.remaining = rest.get(length.div_ceil(8)..).ok_or(FastScanError::assert())?;
1101
1102        Ok(true)
1103    }
1104
1105    /// Skip an optional byte string.
1106    #[inline]
1107    pub fn skip_opt_bytes(&mut self, tag: Tag) -> Result<bool, FastScanError> {
1108        let [header, rest @ ..] = self.remaining else {
1109            return Ok(false);
1110        };
1111        let Some(length) = self.test_tt(header, tag, Type::ByteString) else {
1112            return Ok(false);
1113        };
1114        self.remaining = rest.get(length.div_ceil(8)..).ok_or(FastScanError::assert())?;
1115
1116        Ok(true)
1117    }
1118
1119    /// Skip an optional date-time.
1120    #[inline]
1121    pub fn skip_opt_date_time(&mut self, tag: Tag) -> Result<bool, FastScanError> {
1122        let [header, _, rest @ ..] = self.remaining else {
1123            return Ok(false);
1124        };
1125        let Some(()) = self.test_ttl(header, tag, Type::DateTime, 8) else {
1126            return Ok(false);
1127        };
1128        self.remaining = rest;
1129
1130        Ok(true)
1131    }
1132
1133    /// Skip an optional interval.
1134    #[inline]
1135    pub fn skip_opt_interval(&mut self, tag: Tag) -> Result<bool, FastScanError> {
1136        let [header, _, rest @ ..] = self.remaining else {
1137            return Ok(false);
1138        };
1139        let Some(()) = self.test_ttl(header, tag, Type::Interval, 4) else {
1140            return Ok(false);
1141        };
1142        self.remaining = rest;
1143
1144        Ok(true)
1145    }
1146}
1147
1148//============ Errors ==========================================================
1149
1150/// An error from a [`FastScanner`].
1151///
1152/// [`FastScanner`] deliberately elides information about the error, in order
1153/// to run more efficiently.  As such, this is a trivial zero-sized type.
1154///
1155/// ## Interpretation
1156///
1157/// Presumably, the input was received from an external entity.  This error
1158/// indicates a miscommunication between that entity and the caller.  There
1159/// are three expected causes of such miscommunication:
1160///
1161/// - Incompatibility (e.g. the entity expects the caller to understand more
1162///   than it does).  This is a persistent error, but may be localized to the
1163///   particular kind of input message.
1164///
1165/// - Transport error (e.g. the input was corrupted during network transfer).
1166///   This is an ephemeral error.
1167///
1168/// - Implementation bug (e.g. in the external entity).  This is a persistent
1169///   error, but may be localized to the particular kind of input message.
1170///
1171/// The caller can distinguish incompatibilities from the lower-level errors
1172/// by re-parsing the input using a different scanner.  In order to distinguish
1173/// transport errors from implementation bugs, the caller has to continue
1174/// operation and detect reoccurring parsing failures.
1175//
1176// TODO: Link to 'SlowScanner' once it exists.
1177///
1178/// ## Reaction
1179///
1180/// The caller can react to this error in a few ways:
1181///
1182/// - Assume the error was ephemeral and continue communicating with the
1183///   external entity as normal.  The caller should remember that the error
1184///   occurred and switch to a different reaction if it reoccurs.
1185///
1186/// - Actively work around the issue by parsing the input differently.  This
1187///   implies significant implementation burden, and is not recommended.
1188///
1189/// - Avoid receiving similar messages from the external entity (e.g. by
1190///   avoiding making the same kinds of requests to it, or informing it that
1191///   its message could not be parsed).  This is only feasible if the
1192///   communication is non-critical functionality for the caller.
1193///
1194/// - Crash.  This is ideal if the error prevents the caller from fulfilling
1195///   critical functionality.
1196///
1197/// The caller should re-parse the input using a different scanner; if the error
1198/// appears to be an incompatibility, it should avoid receiving such messages
1199/// from the entity.  If this is not possible, it should crash.  If the error
1200/// appears to be a lower-level bug, the caller should assume it is ephemeral
1201/// and continue operation.  If the error is persistent, it should avoid
1202/// receiving similar messages, or crash.
1203//
1204// TODO: Link to 'SlowScanner' once it exists.
1205pub struct FastScanError {
1206    /// A backtrace.
1207    #[cfg(debug_assertions)]
1208    backtrace: std::backtrace::Backtrace,
1209
1210    /// Force this 'struct' to be private.
1211    _private: (),
1212}
1213
1214impl FastScanError {
1215    /// Assert an error.
1216    pub fn assert() -> Self {
1217        Self {
1218            #[cfg(debug_assertions)]
1219            backtrace: std::backtrace::Backtrace::force_capture(),
1220            _private: (),
1221        }
1222    }
1223}
1224
1225impl std::error::Error for FastScanError {}
1226
1227impl fmt::Debug for FastScanError {
1228    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1229        #[cfg(debug_assertions)]
1230        {
1231            f.debug_struct("FastScanError")
1232                .field("backtrace", &self.backtrace)
1233                .finish()
1234        }
1235
1236        #[cfg(not(debug_assertions))]
1237        {
1238            f.write_str("a fast-scanning error occurred")
1239        }
1240    }
1241}
1242
1243impl fmt::Display for FastScanError {
1244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1245        f.write_str("a fast-scanning error occurred")?;
1246        #[cfg(debug_assertions)]
1247        {
1248            write!(f, "\nBacktrace:\n{}", self.backtrace)?;
1249        }
1250        Ok(())
1251    }
1252}
1253
1254impl PartialEq for FastScanError {
1255    fn eq(&self, _: &Self) -> bool {
1256        true
1257    }
1258}
1259
1260impl Eq for FastScanError {}