qubit_codec_binary/codec/non_strict.rs
1// =============================================================================
2// Copyright (c) 2026 Haixing Hu.
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Licensed under the Apache License, Version 2.0.
7// =============================================================================
8
9use super::Leb128DecodePolicy;
10
11/// Selects LEB128 decoding that accepts non-canonical integer encodings.
12///
13/// Use this zero-sized policy as the second type parameter of
14/// [`crate::Leb128Codec`] or [`crate::ZigZagCodec`] when decoding
15/// compatibility-sensitive input. Encoding remains canonical regardless of the
16/// selected policy. Non-canonical representations are accepted only within the
17/// target integer's maximum decode width
18/// ([`crate::Leb128Codec::MAX_DECODE_UNITS_PER_VALUE`]). The terminal payload
19/// must still fit the target bit width. Over-width payloads and sequences that
20/// remain unterminated at that maximum width are malformed; this policy does
21/// not accept arbitrarily long encodings.
22///
23/// # Examples
24///
25/// ```
26/// use qubit_codec_binary::{Leb128Codec, NonStrict};
27///
28/// let input = [0x80, 0x00];
29/// let (value, consumed) = unsafe {
30/// Leb128Codec::<u16, NonStrict>::decode(&input, 0)
31/// }
32/// .expect("non-canonical zero should decode with the non-strict policy");
33/// assert_eq!(0, value);
34/// assert_eq!(2, consumed.get());
35/// ```
36///
37/// ```
38/// use qubit_codec_binary::Leb128Codec;
39/// use qubit_codec_binary::Leb128DecodeErrorKind;
40/// use qubit_codec_binary::NonStrict;
41///
42/// let input = [0x80, 0x80, 0x00];
43/// // SAFETY: The non-empty array provides the required first readable byte.
44/// let error = unsafe { Leb128Codec::<u8, NonStrict>::decode(&input, 0) }
45/// .expect_err("three bytes exceed the u8 decode width");
46/// assert_eq!(Leb128DecodeErrorKind::Malformed, error.kind());
47///
48/// // SAFETY: The same array satisfies the decoder's readable-byte precondition.
49/// let (value, consumed) = unsafe {
50/// Leb128Codec::<u16, NonStrict>::decode(&input, 0)
51/// }
52/// .expect("the redundant zero fits the u16 decode width");
53/// assert_eq!(0, value);
54/// assert_eq!(3, consumed.get());
55/// ```
56#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
57pub struct NonStrict;
58
59impl super::internal::sealed::Sealed for NonStrict {}
60
61impl Leb128DecodePolicy for NonStrict {
62 /// Whether this policy rejects non-canonical encodings.
63 const STRICT: bool = false;
64}