Skip to main content

bincode_next/
config.rs

1//! The config module is used to change the behavior of bincode's encoding and decoding logic.
2//!
3//! *Important* make sure you use the same config for encoding and decoding, or else bincode will not work properly.
4//!
5//! To use a config, first create a type of [Configuration]. This type will implement trait [Config] for use with bincode.
6//!
7//! ```
8//! let config = bincode_next::config::standard()
9//!     // pick one of:
10//!     .with_big_endian()
11//!     .with_little_endian()
12//!     // pick one of:
13//!     .with_variable_int_encoding()
14//!     .with_fixed_int_encoding()
15//!     // pick one of:
16//!     .with_bit_packing()
17//!     .with_no_bit_packing();
18//! ```
19//!
20//! See [Configuration] for more information on the configuration options.
21
22#[doc(hidden)]
23pub use self::internal::*;
24use core::marker::PhantomData;
25
26/// The Configuration struct is used to build bincode configurations. The [Config] trait is implemented
27/// by this struct when a valid configuration has been constructed.
28///
29/// The following methods are mutually exclusive and will overwrite each other. The last call to one of these methods determines the behavior of the configuration:
30///
31/// - [`with_little_endian`\] and [`with_big_endian`\]
32/// - [`with_fixed_int_encoding`\] and [`with_variable_int_encoding`\]
33/// - [`with_bit_packing`\] and [`with_no_bit_packing`\]
34///
35///
36/// [with_little_endian]: #method.with_little_endian
37/// [with_big_endian]: #method.with_big_endian
38/// [with_fixed_int_encoding]: #method.with_fixed_int_encoding
39/// [with_variable_int_encoding]: #method.with_variable_int_encoding
40/// [with_bit_packing]: #method.with_bit_packing
41/// [with_no_bit_packing]: #method.with_no_bit_packing
42#[derive(Copy, Clone, Debug)]
43pub struct Configuration<
44    E = LittleEndian,
45    I = Varint,
46    L = NoLimit,
47    B = SkipBitPacking,
48    O = LsbFirst,
49    F = FingerprintDisabled,
50    FO = BincodeFormat,
51> {
52    _e: PhantomData<E>,
53    _i: PhantomData<I>,
54    _l: PhantomData<L>,
55    _b: PhantomData<B>,
56    _o: PhantomData<O>,
57    _f: PhantomData<F>,
58    _fo: PhantomData<FO>,
59}
60
61/// The modes for CBOR deterministic encoding.
62#[derive(Copy, Clone, Debug, PartialEq, Eq)]
63#[repr(u8)]
64pub enum CborDeterministicMode {
65    /// No deterministic encoding requirements.
66    None = 0,
67    /// Core deterministic encoding (RFC 8949 §4.2.1).
68    Core = 1,
69    /// Length-first deterministic encoding (RFC 8949 §4.2.3).
70    LengthFirst = 2,
71}
72
73/// The modes for deterministic encoding of the bincode format.
74///
75/// These only affect the *ordering* of unordered collections (`HashMap`,
76/// `HashSet`, ...) and collections that are re-sorted by their encoded bytes
77/// (e.g. `BinaryHeap`). The wire format stays plain bincode, so any mode can
78/// be decoded by a regular bincode decoder.
79#[derive(Copy, Clone, Debug, PartialEq, Eq)]
80#[repr(u8)]
81pub enum BincodeDeterministicMode {
82    /// No deterministic encoding requirements.
83    None = 0,
84    /// Core deterministic encoding: map keys / set elements are sorted by the
85    /// bytewise lexicographic order of their bincode encodings.
86    Core = 1,
87    /// Length-first deterministic encoding: shorter encodings sort first, ties
88    /// are broken by bytewise lexicographic order (mirrors
89    /// [`CborDeterministicMode::LengthFirst`]).
90    LengthFirst = 2,
91}
92
93/// Detailed options for bincode encoding.
94#[derive(Copy, Clone, Debug, PartialEq, Eq)]
95pub struct BincodeOptions {
96    /// Deterministic encoding mode.
97    pub deterministic_mode: BincodeDeterministicMode,
98}
99
100impl BincodeOptions {
101    /// Default bincode options.
102    pub const DEFAULT: Self = Self {
103        deterministic_mode: BincodeDeterministicMode::None,
104    };
105    /// Default options for deterministic bincode.
106    pub const DETERMINISTIC: Self = Self {
107        deterministic_mode: BincodeDeterministicMode::Core,
108    };
109}
110
111/// Detailed options for CBOR encoding.
112#[allow(clippy::struct_excessive_bools)]
113#[derive(Copy, Clone, Debug, PartialEq, Eq)]
114pub struct CborOptions {
115    /// Deterministic encoding mode.
116    pub deterministic_mode: CborDeterministicMode,
117    /// Preferred serialization for floating-point values (§4.1).
118    pub preferred_float: bool,
119    /// Canonical NaN encoding (0xf97e00).
120    pub canonical_nan: bool,
121    /// Normalize negative zero (-0.0) to positive zero (0.0).
122    pub normalize_neg_zero: bool,
123    /// Allow indefinite-length items.
124    pub allow_indefinite: bool,
125    /// Strict tag validity checking.
126    pub strict_tags: bool,
127}
128
129impl CborOptions {
130    /// Default CBOR options.
131    pub const DEFAULT: Self = Self {
132        deterministic_mode: CborDeterministicMode::None,
133        preferred_float: true,
134        canonical_nan: true,
135        normalize_neg_zero: false,
136        allow_indefinite: true,
137        strict_tags: false,
138    };
139    /// Default options for deterministic CBOR.
140    pub const DETERMINISTIC: Self = Self {
141        deterministic_mode: CborDeterministicMode::Core,
142        preferred_float: true,
143        canonical_nan: true,
144        normalize_neg_zero: false, // RFC 8949 §4.2.1: MUST NOT normalize -0.0
145        allow_indefinite: false,
146        strict_tags: true,
147    };
148}
149
150// When adding more features to configuration, follow these steps:
151// - Create 2 or more structs that can be used as a type (e.g. Limit and NoLimit)
152// - Add an `Internal...Config` to the `internal` module
153// - Make sure `Config` and `impl<T> Config for T` extend from this new trait
154// - Add a generic to `Configuration`
155// - Add this generic to `impl<...> Default for Configuration<...>`
156// - Add this generic to `const fn generate<...>()`
157// - Add this generic to _every_ function in `Configuration`
158// - Add your new methods
159
160/// The default config for bincode 2.0. By default this will be:
161/// - Little endian
162/// - Variable int encoding
163#[must_use]
164pub const fn standard() -> Configuration {
165    generate()
166}
167
168/// Creates the "legacy" default config. This is the default config that was present in bincode 1.0
169/// - Little endian
170/// - Fixed int length encoding
171#[must_use]
172pub const fn legacy() -> Configuration<
173    LittleEndian,
174    Fixint,
175    NoLimit,
176    SkipBitPacking,
177    LsbFirst,
178    FingerprintDisabled,
179    BincodeLegacyFormat,
180> {
181    generate()
182}
183
184impl<E, I, L, B, O, F, FO> Default for Configuration<E, I, L, B, O, F, FO> {
185    fn default() -> Self {
186        generate()
187    }
188}
189
190const fn generate<E, I, L, B, O, F, FO>() -> Configuration<E, I, L, B, O, F, FO> {
191    Configuration {
192        _e: PhantomData,
193        _i: PhantomData,
194        _l: PhantomData,
195        _b: PhantomData,
196        _o: PhantomData,
197        _f: PhantomData,
198        _fo: PhantomData,
199    }
200}
201
202impl<E, I, L, B, O, F, FO> Configuration<E, I, L, B, O, F, FO> {
203    /// Makes bincode encode all integer types in big endian.
204    #[must_use]
205    pub const fn with_big_endian(self) -> Configuration<BigEndian, I, L, B, MsbFirst, F, FO> {
206        generate()
207    }
208
209    /// Makes bincode encode all integer types in little endian.
210    #[must_use]
211    pub const fn with_little_endian(self) -> Configuration<LittleEndian, I, L, B, LsbFirst, F, FO> {
212        generate()
213    }
214
215    /// Makes bincode encode all integer types with a variable integer encoding.
216    ///
217    /// Encoding an unsigned integer `v` (of any type excepting `u8`) works as follows:
218    ///
219    /// 1. If `u < 251`, encode it as a single byte with that value.
220    /// 2. If `251 <= u < 2**16`, encode it as a literal byte `251`, followed by a `u16` with value `u`.
221    /// 3. If `2**16 <= u < 2**32`, encode it as a literal byte `252`, followed by a `u32` with value `u`.
222    /// 4. If `2**32 <= u < 2**64`, encode it as a literal byte `253`, followed by a `u64` with value `u`.
223    /// 5. If `2**64 <= u < 2**128`, encode it as a literal byte `254`, followed by a `u128` with value `u`.
224    ///
225    /// Then, for signed integers, we first convert to unsigned using the zigzag algorithm,
226    /// and then encode them as we do for unsigned integers generally. The reason we use this
227    /// algorithm is that it encodes those values which are close to zero in less bytes; the
228    /// obvious algorithm, where we encode the cast values, gives a very large encoding for all
229    /// negative values.
230    ///
231    /// The zigzag algorithm is defined as follows:
232    ///
233    /// ```rust
234    /// # type Signed = i32;
235    /// # type Unsigned = u32;
236    /// fn zigzag(v: Signed) -> Unsigned {
237    ///     match v {
238    ///         | 0 => 0,
239    ///         // To avoid the edge case of Signed::min_value()
240    ///         // !n is equal to `-n - 1`, so this is:
241    ///         // !n * 2 + 1 = 2(-n - 1) + 1 = -2n - 2 + 1 = -2n - 1
242    ///         | v if v < 0 => !(v as Unsigned) * 2 - 1,
243    ///         | v if v > 0 => (v as Unsigned) * 2,
244    /// #       _ => unreachable!()
245    ///     }
246    /// }
247    /// ```
248    ///
249    /// And works such that:
250    ///
251    /// ```rust
252    /// # let zigzag = |n: i64| -> u64 {
253    /// #     match n {
254    /// #         0 => 0,
255    /// #         v if v < 0 => !(v as u64) * 2 + 1,
256    /// #         v if v > 0 => (v as u64) * 2,
257    /// #         _ => unreachable!(),
258    /// #     }
259    /// # };
260    /// assert_eq!(zigzag(0), 0);
261    /// assert_eq!(zigzag(-1), 1);
262    /// assert_eq!(zigzag(1), 2);
263    /// assert_eq!(zigzag(-2), 3);
264    /// assert_eq!(zigzag(2), 4);
265    /// // etc
266    /// assert_eq!(zigzag(i64::min_value()), u64::max_value());
267    /// ```
268    ///
269    /// Note that u256 and the like are unsupported by this format; if and when they are added to the
270    /// language, they may be supported via the extension point given by the 255 byte.
271    #[must_use]
272    pub const fn with_variable_int_encoding(self) -> Configuration<E, Varint, L, B, O, F, FO> {
273        generate()
274    }
275
276    /// Fixed-size integer encoding.
277    ///
278    /// * Fixed size integers are encoded directly
279    /// * Enum discriminants are encoded as u32
280    /// * Lengths and usize are encoded as u64
281    #[must_use]
282    pub const fn with_fixed_int_encoding(self) -> Configuration<E, Fixint, L, B, O, F, FO> {
283        generate()
284    }
285
286    /// Sets the byte limit to `limit`.
287    #[must_use]
288    pub const fn with_limit<const N: usize>(self) -> Configuration<E, I, Limit<N>, B, O, F, FO> {
289        generate()
290    }
291
292    /// Clear the byte limit.
293    #[must_use]
294    pub const fn with_no_limit(self) -> Configuration<E, I, NoLimit, B, O, F, FO> {
295        generate()
296    }
297
298    /// Enables bit-packing for types that support it.
299    #[must_use]
300    pub const fn with_bit_packing(self) -> Configuration<E, I, L, AllowBitPacking, O, F, FO> {
301        generate()
302    }
303
304    /// Disables bit-packing.
305    #[must_use]
306    pub const fn with_no_bit_packing(self) -> Configuration<E, I, L, SkipBitPacking, O, F, FO> {
307        generate()
308    }
309
310    /// Enables fingerprinting with the default deterministic seed (0).
311    ///
312    /// The fingerprint is a 64-bit hash that covers:
313    /// - The type name
314    /// - For structs: field names, types, and their order
315    /// - For enums: variant names, field names, types, and their order
316    /// - Configuration settings such as endianness and integer encoding
317    #[must_use]
318    pub const fn with_fingerprint(self) -> Configuration<E, I, L, B, O, FingerprintEnabled<0>, FO> {
319        generate()
320    }
321
322    /// Enables fingerprinting with a custom seed.
323    ///
324    /// This is similar to [`with_fingerprint`](Self::with_fingerprint), but allows specifying a custom seed
325    /// to further differentiate fingerprints.
326    #[must_use]
327    pub const fn with_fingerprint_and_seed<const SEED: u64>(
328        self
329    ) -> Configuration<E, I, L, B, O, FingerprintEnabled<SEED>, FO> {
330        generate()
331    }
332
333    /// Enables legacy fingerprinting with an expected hash.
334    ///
335    /// In this mode, bincode will not calculate the fingerprint automatically.
336    /// Instead, it will use the provided `EXPECTED` hash for verification.
337    #[must_use]
338    pub const fn with_legacy_fingerprint<const EXPECTED: u64>(
339        self
340    ) -> Configuration<E, I, L, B, O, FingerprintLegacy<EXPECTED>, FO> {
341        generate()
342    }
343
344    /// Sets the format to CBOR with default options.
345    #[must_use]
346    pub const fn with_cbor_format(self) -> Configuration<E, I, L, B, O, F, CborFormat> {
347        generate()
348    }
349
350    /// Sets the format to CBOR with deterministic encoding (Core mode).
351    #[must_use]
352    pub const fn with_deterministic_cbor(
353        self
354    ) -> Configuration<E, I, L, B, O, F, CborDeterministicFormat> {
355        generate()
356    }
357
358    /// Sets the format to Bincode with deterministic encoding.
359    #[must_use]
360    pub const fn with_deterministic_bincode(
361        self
362    ) -> Configuration<E, I, L, B, O, F, BincodeDeterministicFormat> {
363        generate()
364    }
365
366    /// Sets the format to Bincode with a specific deterministic mode.
367    ///
368    /// `DET` is the `repr(u8)` value of a [`BincodeDeterministicMode`]
369    /// (`0` = none, `1` = core, `2` = length-first).
370    #[must_use]
371    pub const fn with_bincode_deterministic_mode<const DET: u8>(
372        self
373    ) -> Configuration<E, I, L, B, O, F, BincodeConfig<DET>> {
374        generate()
375    }
376
377    /// Sets the format to Bincode with length-first deterministic encoding.
378    #[must_use]
379    pub const fn with_deterministic_bincode_length_first(
380        self
381    ) -> Configuration<E, I, L, B, O, F, BincodeLengthFirstFormat> {
382        generate()
383    }
384
385    /// Sets the format to CBOR with custom options.
386    #[must_use]
387    pub const fn with_cbor_options<
388        const DET: u8,
389        const PREF: bool,
390        const NAN: bool,
391        const NZ: bool,
392        const INDEF: bool,
393        const TAGS: bool,
394    >(
395        self
396    ) -> Configuration<E, I, L, B, O, F, CborConfig<DET, PREF, NAN, NZ, INDEF, TAGS>> {
397        generate()
398    }
399}
400
401/// Indicates a type is valid for controlling the bincode configuration
402pub trait Config:
403    InternalEndianConfig
404    + InternalIntEncodingConfig
405    + InternalLimitConfig
406    + InternalBitPackingConfig
407    + InternalBitOrderingConfig
408    + InternalFingerprintConfig
409    + InternalFormatConfig
410    + InternalConfigFingerprint
411    + InternalFingerprintConfigExt
412    + Copy
413    + Clone
414{
415    /// This configuration's Endianness
416    fn endianness(&self) -> Endianness;
417
418    /// This configuration's Integer Encoding
419    fn int_encoding(&self) -> IntEncoding;
420
421    /// This configuration's byte limit, or `None` if no limit is configured
422    fn limit(&self) -> Option<usize>;
423
424    /// Whether bit-packing is enabled for this configuration
425    fn bit_packing_enabled(&self) -> bool;
426
427    /// Returns the bit ordering of this configuration
428    fn bit_ordering(&self) -> BitOrdering;
429
430    /// Returns the fingerprint mode of this configuration
431    fn fingerprint_mode(&self) -> FingerprintMode;
432
433    /// Returns the format of this configuration
434    fn format(&self) -> Format;
435
436    /// Returns the bincode options of this configuration.
437    /// Returns default options if the format is not deterministic bincode.
438    fn bincode_options(&self) -> BincodeOptions;
439
440    /// Returns the CBOR options of this configuration.
441    /// Returns default options if the format is not CBOR.
442    fn cbor_options(&self) -> CborOptions;
443
444    /// Returns true if this configuration uses compact network encoding (omitting `flowinfo/scope_id`).
445    fn is_compact_net(&self) -> bool;
446}
447
448impl<T> Config for T
449where
450    T: InternalEndianConfig
451        + InternalIntEncodingConfig
452        + InternalLimitConfig
453        + InternalBitPackingConfig
454        + InternalBitOrderingConfig
455        + InternalFingerprintConfig
456        + InternalFormatConfig
457        + InternalConfigFingerprint
458        + InternalFingerprintConfigExt
459        + Copy
460        + Clone,
461{
462    fn endianness(&self) -> Endianness {
463        <T as InternalEndianConfig>::ENDIAN
464    }
465
466    fn int_encoding(&self) -> IntEncoding {
467        <T as InternalIntEncodingConfig>::INT_ENCODING
468    }
469
470    fn limit(&self) -> Option<usize> {
471        <T as InternalLimitConfig>::LIMIT
472    }
473
474    fn bit_packing_enabled(&self) -> bool {
475        matches!(
476            <T as InternalBitPackingConfig>::BIT_PACKING,
477            BitPacking::Enabled
478        )
479    }
480
481    fn bit_ordering(&self) -> BitOrdering {
482        <T as InternalBitOrderingConfig>::BIT_ORDERING
483    }
484
485    fn fingerprint_mode(&self) -> FingerprintMode {
486        <T as InternalFingerprintConfig>::FINGERPRINT_MODE
487    }
488
489    fn format(&self) -> Format {
490        <T as InternalFormatConfig>::FORMAT
491    }
492
493    fn cbor_options(&self) -> CborOptions {
494        <T as InternalFormatConfig>::CBOR_OPTIONS
495    }
496
497    fn bincode_options(&self) -> BincodeOptions {
498        <T as InternalFormatConfig>::BINCODE_OPTIONS
499    }
500
501    fn is_compact_net(&self) -> bool {
502        <T as InternalFormatConfig>::IS_COMPACT_NET
503    }
504}
505
506/// Encodes all integer types in big endian.
507#[derive(Copy, Clone, Debug)]
508#[doc(hidden)]
509pub struct BigEndian;
510
511impl InternalEndianConfig for BigEndian {
512    const ENDIAN: Endianness = Endianness::Big;
513}
514
515/// Encodes all integer types in little endian.
516#[derive(Copy, Clone, Debug)]
517#[doc(hidden)]
518pub struct LittleEndian;
519
520impl InternalEndianConfig for LittleEndian {
521    const ENDIAN: Endianness = Endianness::Little;
522}
523
524/// Use fixed-size integer encoding.
525#[derive(Copy, Clone, Debug)]
526#[doc(hidden)]
527pub struct Fixint;
528
529impl InternalIntEncodingConfig for Fixint {
530    const INT_ENCODING: IntEncoding = IntEncoding::Fixed;
531}
532
533/// Use variable integer encoding.
534#[derive(Copy, Clone, Debug)]
535#[doc(hidden)]
536pub struct Varint;
537
538impl InternalIntEncodingConfig for Varint {
539    const INT_ENCODING: IntEncoding = IntEncoding::Variable;
540}
541
542/// Sets an unlimited byte limit.
543#[derive(Copy, Clone, Debug)]
544#[doc(hidden)]
545pub struct NoLimit;
546impl InternalLimitConfig for NoLimit {
547    const LIMIT: Option<usize> = None;
548}
549
550/// Sets the byte limit to N.
551#[derive(Copy, Clone, Debug)]
552#[doc(hidden)]
553pub struct Limit<const N: usize>;
554impl<const N: usize> InternalLimitConfig for Limit<N> {
555    const LIMIT: Option<usize> = Some(N);
556}
557
558/// Use bit-packing for types that support it.
559#[derive(Copy, Clone, Debug)]
560#[doc(hidden)]
561pub struct AllowBitPacking;
562
563impl InternalBitPackingConfig for AllowBitPacking {
564    const BIT_PACKING: BitPacking = BitPacking::Enabled;
565}
566
567/// Skip bit-packing.
568#[derive(Copy, Clone, Debug)]
569#[doc(hidden)]
570pub struct SkipBitPacking;
571
572impl InternalBitPackingConfig for SkipBitPacking {
573    const BIT_PACKING: BitPacking = BitPacking::Disabled;
574}
575
576/// Use MSB-first bit ordering.
577#[derive(Copy, Clone, Debug)]
578#[doc(hidden)]
579pub struct MsbFirst;
580
581impl InternalBitOrderingConfig for MsbFirst {
582    const BIT_ORDERING: BitOrdering = BitOrdering::Msb;
583}
584
585/// Use LSB-first bit ordering.
586#[derive(Copy, Clone, Debug)]
587#[doc(hidden)]
588pub struct LsbFirst;
589
590impl InternalBitOrderingConfig for LsbFirst {
591    const BIT_ORDERING: BitOrdering = BitOrdering::Lsb;
592}
593
594/// Fingerprinting is disabled.
595#[derive(Copy, Clone, Debug)]
596#[doc(hidden)]
597pub struct FingerprintDisabled;
598
599impl InternalFingerprintConfig for FingerprintDisabled {
600    const FINGERPRINT_MODE: FingerprintMode = FingerprintMode::Disabled;
601}
602
603/// Fingerprinting is enabled with a seed.
604#[derive(Copy, Clone, Debug)]
605#[doc(hidden)]
606pub struct FingerprintEnabled<const SEED: u64>;
607
608impl<const SEED: u64> InternalFingerprintConfig for FingerprintEnabled<SEED> {
609    const FINGERPRINT_MODE: FingerprintMode = FingerprintMode::Enabled { seed: SEED };
610}
611
612/// Legacy fingerprinting with an expected hash.
613#[derive(Copy, Clone, Debug)]
614#[doc(hidden)]
615pub struct FingerprintLegacy<const EXPECTED: u64>;
616
617impl<const EXPECTED: u64> InternalFingerprintConfig for FingerprintLegacy<EXPECTED> {
618    const FINGERPRINT_MODE: FingerprintMode = FingerprintMode::Legacy { expected: EXPECTED };
619}
620
621/// The default bincode format.
622#[derive(Copy, Clone, Debug)]
623#[doc(hidden)]
624pub struct BincodeFormat;
625
626impl InternalFormatConfig for BincodeFormat {
627    const BINCODE_OPTIONS: BincodeOptions = BincodeOptions::DEFAULT;
628    const CBOR_OPTIONS: CborOptions = CborOptions::DEFAULT;
629    const FORMAT: Format = Format::Bincode;
630    const IS_COMPACT_NET: bool = false;
631}
632
633/// Bincode configuration with a const generic deterministic mode.
634#[derive(Copy, Clone, Debug)]
635#[doc(hidden)]
636pub struct BincodeConfig<const DET: u8>;
637
638impl<const DET: u8> InternalFormatConfig for BincodeConfig<DET> {
639    const BINCODE_OPTIONS: BincodeOptions = BincodeOptions {
640        deterministic_mode: match DET {
641            | 1 => BincodeDeterministicMode::Core,
642            | 2 => BincodeDeterministicMode::LengthFirst,
643            | _ => BincodeDeterministicMode::None,
644        },
645    };
646    const CBOR_OPTIONS: CborOptions = CborOptions::DEFAULT;
647    const FORMAT: Format = if DET == 0 {
648        Format::Bincode
649    } else {
650        Format::BincodeDeterministic
651    };
652    const IS_COMPACT_NET: bool = false;
653}
654
655/// Bincode format with deterministic encoding (core mode).
656#[doc(hidden)]
657pub type BincodeDeterministicFormat = BincodeConfig<1>;
658
659/// Bincode format with length-first deterministic encoding.
660#[doc(hidden)]
661pub type BincodeLengthFirstFormat = BincodeConfig<2>;
662
663/// CBOR configuration with const generic options.
664#[derive(Copy, Clone, Debug)]
665#[doc(hidden)]
666pub struct CborConfig<
667    const DET: u8,
668    const PREF: bool,
669    const NAN: bool,
670    const NZ: bool,
671    const INDEF: bool,
672    const TAGS: bool,
673>;
674
675impl<
676    const DET: u8,
677    const PREF: bool,
678    const NAN: bool,
679    const NZ: bool,
680    const INDEF: bool,
681    const TAGS: bool,
682> InternalFormatConfig for CborConfig<DET, PREF, NAN, NZ, INDEF, TAGS>
683{
684    const BINCODE_OPTIONS: BincodeOptions = BincodeOptions::DEFAULT;
685    const CBOR_OPTIONS: CborOptions = CborOptions {
686        deterministic_mode: match DET {
687            | 1 => CborDeterministicMode::Core,
688            | 2 => CborDeterministicMode::LengthFirst,
689            | _ => CborDeterministicMode::None,
690        },
691        preferred_float: PREF,
692        canonical_nan: NAN,
693        normalize_neg_zero: NZ,
694        allow_indefinite: INDEF,
695        strict_tags: TAGS,
696    };
697    const FORMAT: Format = if DET == 0 {
698        Format::Cbor
699    } else {
700        Format::CborDeterministic
701    };
702    const IS_COMPACT_NET: bool = false;
703}
704
705/// Bincode format for legacy compatibility (omitting flowinfo/scope_id).
706#[derive(Copy, Clone, Debug)]
707#[doc(hidden)]
708pub struct BincodeLegacyFormat;
709
710impl InternalFormatConfig for BincodeLegacyFormat {
711    const BINCODE_OPTIONS: BincodeOptions = BincodeOptions::DEFAULT;
712    const CBOR_OPTIONS: CborOptions = CborOptions::DEFAULT;
713    const FORMAT: Format = Format::Bincode;
714    const IS_COMPACT_NET: bool = true;
715}
716
717/// CBOR format with default options.
718#[doc(hidden)]
719pub type CborFormat = CborConfig<0, true, true, false, true, false>;
720
721/// CBOR format with deterministic encoding (Canonical CBOR).
722#[doc(hidden)]
723pub type CborDeterministicFormat = CborConfig<1, true, true, false, false, true>;
724
725/// Endianness of a `Configuration`.
726#[derive(Copy, Clone, Debug, PartialEq, Eq)]
727#[non_exhaustive]
728pub enum Endianness {
729    /// Little Endian encoding, see `LittleEndian`.
730    Little,
731    /// Big Endian encoding, see `BigEndian`.
732    Big,
733}
734
735/// Integer Encoding of a `Configuration`.
736#[derive(Copy, Clone, Debug, PartialEq, Eq)]
737#[non_exhaustive]
738pub enum IntEncoding {
739    /// Fixed Integer Encoding, see `Fixint`.
740    Fixed,
741    /// Variable Integer Encoding, see `Varint`.
742    Variable,
743}
744
745/// Bit packing of a `Configuration`.
746#[derive(Copy, Clone, Debug, PartialEq, Eq)]
747#[non_exhaustive]
748pub enum BitPacking {
749    /// Enable bit-packing.
750    Enabled,
751    /// Disable bit-packing.
752    Disabled,
753}
754
755/// Bit ordering of a `Configuration`.
756#[derive(Copy, Clone, Debug, PartialEq, Eq)]
757#[non_exhaustive]
758pub enum BitOrdering {
759    /// Least Significant Bit first.
760    Lsb,
761    /// Most Significant Bit first.
762    Msb,
763}
764
765/// Fingerprint mode of a `Configuration`.
766#[derive(Copy, Clone, Debug, PartialEq, Eq)]
767#[non_exhaustive]
768pub enum FingerprintMode {
769    /// Fingerprinting is disabled.
770    Disabled,
771    /// Fingerprinting is enabled with a seed.
772    Enabled {
773        /// The seed to use for hashing.
774        seed: u64,
775    },
776    /// Legacy fingerprinting with an expected hash.
777    Legacy {
778        /// The hash that is expected to be present.
779        expected: u64,
780    },
781}
782
783/// Format of a `Configuration`.
784#[derive(Copy, Clone, Debug, PartialEq, Eq)]
785#[non_exhaustive]
786pub enum Format {
787    /// Bincode (default).
788    Bincode,
789    /// Bincode with deterministic encoding.
790    BincodeDeterministic,
791    /// CBOR.
792    Cbor,
793    /// CBOR with deterministic encoding.
794    CborDeterministic,
795}
796
797#[doc(hidden)]
798pub mod internal {
799    use super::BitOrdering;
800    use super::BitPacking;
801    use super::Configuration;
802    use super::Endianness;
803    use super::FingerprintMode;
804    use super::IntEncoding;
805
806    pub trait InternalEndianConfig {
807        const ENDIAN: Endianness;
808    }
809
810    impl<E: InternalEndianConfig, I, L, B, O, F, FO> InternalEndianConfig
811        for Configuration<E, I, L, B, O, F, FO>
812    {
813        const ENDIAN: Endianness = E::ENDIAN;
814    }
815
816    pub trait InternalIntEncodingConfig {
817        const INT_ENCODING: IntEncoding;
818    }
819
820    impl<E, I: InternalIntEncodingConfig, L, B, O, F, FO> InternalIntEncodingConfig
821        for Configuration<E, I, L, B, O, F, FO>
822    {
823        const INT_ENCODING: IntEncoding = I::INT_ENCODING;
824    }
825
826    pub trait InternalLimitConfig {
827        const LIMIT: Option<usize>;
828    }
829
830    impl<E, I, L: InternalLimitConfig, B, O, F, FO> InternalLimitConfig
831        for Configuration<E, I, L, B, O, F, FO>
832    {
833        const LIMIT: Option<usize> = L::LIMIT;
834    }
835
836    pub trait InternalBitPackingConfig {
837        const BIT_PACKING: BitPacking;
838    }
839
840    impl<E, I, L, B: InternalBitPackingConfig, O, F, FO> InternalBitPackingConfig
841        for Configuration<E, I, L, B, O, F, FO>
842    {
843        const BIT_PACKING: BitPacking = B::BIT_PACKING;
844    }
845
846    pub trait InternalBitOrderingConfig {
847        const BIT_ORDERING: BitOrdering;
848    }
849
850    impl<E, I, L, B, O: InternalBitOrderingConfig, F, FO> InternalBitOrderingConfig
851        for Configuration<E, I, L, B, O, F, FO>
852    {
853        const BIT_ORDERING: BitOrdering = O::BIT_ORDERING;
854    }
855
856    pub trait InternalFingerprintConfig {
857        const FINGERPRINT_MODE: FingerprintMode;
858    }
859
860    impl<E, I, L, B, O, F: InternalFingerprintConfig, FO> InternalFingerprintConfig
861        for Configuration<E, I, L, B, O, F, FO>
862    {
863        const FINGERPRINT_MODE: FingerprintMode = F::FINGERPRINT_MODE;
864    }
865
866    pub trait InternalFingerprintConfigExt {
867        type Mode;
868    }
869
870    impl<E, I, L, B, O, F, FO> InternalFingerprintConfigExt for Configuration<E, I, L, B, O, F, FO> {
871        type Mode = F;
872    }
873
874    pub trait InternalFingerprintGuard<D, C: super::Config> {
875        fn decode_check<R: crate::de::read::Reader>(
876            _config: &C,
877            reader: &mut R,
878        ) -> core::result::Result<(), crate::error::DecodeError>;
879        fn encode_check<W: crate::enc::write::Writer>(
880            _config: &C,
881            writer: &mut W,
882        ) -> core::result::Result<(), crate::error::EncodeError>;
883    }
884
885    impl<D, C: super::Config> InternalFingerprintGuard<D, C> for super::FingerprintDisabled {
886        #[inline(always)]
887        fn decode_check<R: crate::de::read::Reader>(
888            _config: &C,
889            _reader: &mut R,
890        ) -> core::result::Result<(), crate::error::DecodeError> {
891            core::result::Result::Ok(())
892        }
893
894        #[inline(always)]
895        fn encode_check<W: crate::enc::write::Writer>(
896            _config: &C,
897            _writer: &mut W,
898        ) -> core::result::Result<(), crate::error::EncodeError> {
899            core::result::Result::Ok(())
900        }
901    }
902
903    impl<D: crate::fingerprint::Fingerprint<C>, C: super::Config, const SEED: u64>
904        InternalFingerprintGuard<D, C> for super::FingerprintEnabled<SEED>
905    {
906        #[inline]
907        fn decode_check<R: crate::de::read::Reader>(
908            _config: &C,
909            reader: &mut R,
910        ) -> core::result::Result<(), crate::error::DecodeError> {
911            let mut bytes = [0u8; 8];
912            reader.read(&mut bytes)?;
913            let actual = u64::from_le_bytes(bytes);
914            if actual != D::SCHEMA_HASH {
915                return crate::error::cold_decode_error_schema_mismatch(D::SCHEMA_HASH, actual);
916            }
917            core::result::Result::Ok(())
918        }
919
920        #[inline]
921        fn encode_check<W: crate::enc::write::Writer>(
922            _config: &C,
923            writer: &mut W,
924        ) -> core::result::Result<(), crate::error::EncodeError> {
925            writer.write(&D::SCHEMA_HASH.to_le_bytes())
926        }
927    }
928
929    impl<D, C: super::Config, const EXPECTED: u64> InternalFingerprintGuard<D, C>
930        for super::FingerprintLegacy<EXPECTED>
931    {
932        #[inline]
933        fn decode_check<R: crate::de::read::Reader>(
934            _config: &C,
935            reader: &mut R,
936        ) -> core::result::Result<(), crate::error::DecodeError> {
937            let mut bytes = [0u8; 8];
938            reader.read(&mut bytes)?;
939            let actual = u64::from_le_bytes(bytes);
940            if actual != EXPECTED {
941                return crate::error::cold_decode_error_schema_mismatch(EXPECTED, actual);
942            }
943            core::result::Result::Ok(())
944        }
945
946        #[inline]
947        fn encode_check<W: crate::enc::write::Writer>(
948            _config: &C,
949            _writer: &mut W,
950        ) -> core::result::Result<(), crate::error::EncodeError> {
951            core::result::Result::Ok(())
952        }
953    }
954
955    pub trait InternalConfigFingerprint {
956        const CONFIG_HASH: u64;
957    }
958
959    impl<E, I, L, B, O, F, FO> InternalConfigFingerprint for Configuration<E, I, L, B, O, F, FO>
960    where
961        E: InternalEndianConfig,
962        I: InternalIntEncodingConfig,
963        L: InternalLimitConfig,
964        B: InternalBitPackingConfig,
965        O: InternalBitOrderingConfig,
966        F: InternalFingerprintConfig,
967        FO: InternalFormatConfig,
968    {
969        const CONFIG_HASH: u64 = {
970            // The user-chosen fingerprint seed must change the schema hash, otherwise
971            // `with_fingerprint_and_seed` would be a no-op. Seed 0 (the default) keeps
972            // the historical hash.
973            let seed = match F::FINGERPRINT_MODE {
974                | super::FingerprintMode::Enabled { seed } => seed,
975                | _ => 0,
976            };
977            let format_byte: u8 = match FO::FORMAT {
978                | super::Format::Bincode => 0,
979                | super::Format::BincodeDeterministic => 1,
980                | super::Format::Cbor => 2,
981                | super::Format::CborDeterministic => 3,
982            };
983            let opts = FO::CBOR_OPTIONS;
984            rapidhash::v3::rapidhash_v3_seeded(
985                &[
986                    crate::BINCODE_MAJOR_VERSION as u8,
987                    E::ENDIAN as u8,
988                    I::INT_ENCODING as u8,
989                    match L::LIMIT {
990                        | None => 0,
991                        | Some(_) => 1,
992                    },
993                    B::BIT_PACKING as u8,
994                    O::BIT_ORDERING as u8,
995                    format_byte,
996                    opts.deterministic_mode as u8,
997                    FO::BINCODE_OPTIONS.deterministic_mode as u8,
998                    opts.preferred_float as u8,
999                    opts.canonical_nan as u8,
1000                    opts.normalize_neg_zero as u8,
1001                    opts.allow_indefinite as u8,
1002                    opts.strict_tags as u8,
1003                ],
1004                &rapidhash::v3::RapidSecrets::seed_cpp(seed),
1005            )
1006        };
1007    }
1008
1009    pub trait InternalFormatConfig {
1010        const FORMAT: super::Format;
1011        const BINCODE_OPTIONS: super::BincodeOptions;
1012        const CBOR_OPTIONS: super::CborOptions;
1013        const IS_COMPACT_NET: bool;
1014    }
1015
1016    impl<E, I, L, B, O, F, FO: InternalFormatConfig> InternalFormatConfig
1017        for Configuration<E, I, L, B, O, F, FO>
1018    {
1019        const BINCODE_OPTIONS: super::BincodeOptions = FO::BINCODE_OPTIONS;
1020        const CBOR_OPTIONS: super::CborOptions = FO::CBOR_OPTIONS;
1021        const FORMAT: super::Format = FO::FORMAT;
1022        const IS_COMPACT_NET: bool = FO::IS_COMPACT_NET;
1023    }
1024}