Skip to main content

qubit_codec_binary/codec/
binary_codec.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 core::convert::Infallible;
10use core::marker::PhantomData;
11use core::num::NonZeroUsize;
12
13use qubit_codec::BigEndian;
14use qubit_codec::ByteOrderSpec;
15use qubit_codec::Codec;
16use qubit_codec::DecodeFailure;
17use qubit_codec::LittleEndian;
18use qubit_codec::NativeEndian;
19use qubit_utils::UncheckedSlice;
20use qubit_utils::nonzero;
21
22/// Type-level unchecked binary codec for one scalar type and one byte order.
23///
24/// `BinaryCodec` is intentionally a zero-sized codec type. It exposes
25/// type-level unchecked helpers for direct hot-path use and also implements
26/// [`Codec`] for generic codec pipelines. Callers must validate buffer lengths
27/// before entering the hot path.
28///
29/// # Type Parameters
30///
31/// - `T`: Scalar value type to decode from bytes and encode into bytes.
32/// - `O`: Type-level byte order marker. Multi-byte scalar implementations use
33///   [`BigEndian`], [`LittleEndian`], or [`NativeEndian`]. Prefer big- or
34///   little-endian formats for persistent and cross-platform data;
35///   native-endian encoding is only suitable for platform-local data. Single-
36///   byte scalar implementations accept any [`ByteOrderSpec`] marker because
37///   byte order does not affect one-byte values.
38///
39/// # Examples
40///
41/// ```
42/// use qubit_codec::BigEndian;
43/// use qubit_codec_binary::BinaryCodec;
44///
45/// let mut output = [0_u8; BinaryCodec::<u32, BigEndian>::MAX_ENCODE_UNITS_PER_VALUE];
46/// let written = unsafe {
47///     BinaryCodec::<u32, BigEndian>::encode(0x0102_0304, &mut output, 0)
48/// };
49/// assert_eq!(4, written);
50/// assert_eq!([1, 2, 3, 4], output);
51///
52/// let (decoded, consumed) = unsafe {
53///     BinaryCodec::<u32, BigEndian>::decode(&output, 0)
54/// };
55/// assert_eq!(0x0102_0304, decoded);
56/// assert_eq!(4, consumed.get());
57/// ```
58///
59/// Byte-order markers are also required for single-byte codecs, even though
60/// the marker has no effect on the encoded bytes:
61///
62/// ```compile_fail
63/// use qubit_codec_binary::{BinaryCodec, Strict};
64///
65/// let mut output = [0_u8; 1];
66/// let _ = unsafe { BinaryCodec::<u8, Strict>::encode(1, &mut output, 0) };
67/// ```
68#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
69pub struct BinaryCodec<T, O> {
70    /// Associates the value and byte-order types without storing either one.
71    marker: PhantomData<fn() -> (T, O)>,
72}
73
74impl<O> BinaryCodec<u8, O>
75where
76    O: ByteOrderSpec,
77{
78    /// Minimum number of bytes required to encode or decode this type.
79    pub const MIN_UNITS_PER_VALUE: usize = <Self as Codec>::MIN_UNITS_PER_VALUE;
80
81    /// Maximum number of bytes emitted when encoding this type.
82    pub const MAX_ENCODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
83
84    /// Maximum number of bytes consumed when decoding this type.
85    pub const MAX_DECODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
86
87    /// Decodes a value from `input` starting at `input_index` without bounds
88    /// checks.
89    ///
90    /// # Parameters
91    ///
92    /// - `input`: Source byte buffer.
93    /// - `input_index`: Start index in `input`.
94    ///
95    /// # Returns
96    ///
97    /// Returns the decoded value and the non-zero number of consumed bytes.
98    ///
99    /// # Safety
100    ///
101    /// The caller must guarantee that `input.as_ptr().add(input_index)` is
102    /// valid to read [`Self::MIN_UNITS_PER_VALUE`] bytes.
103    #[must_use]
104    #[inline]
105    pub unsafe fn decode(input: &[u8], input_index: usize) -> (u8, NonZeroUsize) {
106        debug_assert!(input_index + Self::MIN_UNITS_PER_VALUE <= input.len());
107
108        // SAFETY: The caller guarantees that the indexed byte is readable.
109        (
110            unsafe { UncheckedSlice::read(input, input_index) },
111            nonzero(Self::MIN_UNITS_PER_VALUE),
112        )
113    }
114
115    /// Encodes `value` into `output` starting at `output_index` without bounds
116    /// checks.
117    ///
118    /// # Parameters
119    ///
120    /// - `value`: Value to encode.
121    /// - `output`: Destination byte buffer.
122    /// - `output_index`: Start index in `output`.
123    ///
124    /// # Returns
125    ///
126    /// Returns the number of bytes written, equal to
127    /// [`Self::MAX_ENCODE_UNITS_PER_VALUE`], independently of `output_index`.
128    /// The next output position is `output_index + written`, where `written`
129    /// is the returned byte count.
130    ///
131    /// # Safety
132    ///
133    /// The caller must guarantee that `output.as_mut_ptr().add(output_index)`
134    /// is valid to write [`Self::MAX_ENCODE_UNITS_PER_VALUE`] bytes.
135    #[inline]
136    pub unsafe fn encode(value: u8, output: &mut [u8], output_index: usize) -> usize {
137        debug_assert!(output_index + Self::MAX_ENCODE_UNITS_PER_VALUE <= output.len());
138
139        // SAFETY: The caller guarantees that the indexed byte is writable.
140        unsafe {
141            UncheckedSlice::write(output, output_index, value);
142        }
143        Self::MAX_ENCODE_UNITS_PER_VALUE
144    }
145}
146
147impl<O> Codec for BinaryCodec<u8, O>
148where
149    O: ByteOrderSpec,
150{
151    type Value = u8;
152    type Unit = u8;
153    type DecodeError = Infallible;
154    type EncodeError = Infallible;
155
156    const MIN_UNITS_PER_VALUE: usize = 1;
157    const MAX_ENCODE_UNITS_PER_VALUE: usize = 1;
158
159    const MAX_DECODE_UNITS_PER_VALUE: usize = 1;
160
161    #[inline]
162    unsafe fn decode(
163        &mut self,
164        input: &[u8],
165        input_index: usize,
166    ) -> Result<(u8, NonZeroUsize), DecodeFailure<Self::DecodeError>> {
167        // SAFETY: The caller upholds the `Codec::decode` contract.
168        Ok(unsafe { Self::decode(input, input_index) })
169    }
170
171    #[inline]
172    unsafe fn encode(
173        &mut self,
174        value: &u8,
175        output: &mut [u8],
176        output_index: usize,
177    ) -> Result<usize, Self::EncodeError> {
178        // SAFETY: The caller upholds the `Codec::encode` contract.
179        unsafe {
180            Self::encode(*value, output, output_index);
181        }
182        Ok(Self::MAX_ENCODE_UNITS_PER_VALUE)
183    }
184}
185
186impl<O> BinaryCodec<i8, O>
187where
188    O: ByteOrderSpec,
189{
190    /// Minimum number of bytes required to encode or decode this type.
191    pub const MIN_UNITS_PER_VALUE: usize = <Self as Codec>::MIN_UNITS_PER_VALUE;
192
193    /// Maximum number of bytes emitted when encoding this type.
194    pub const MAX_ENCODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
195
196    /// Maximum number of bytes consumed when decoding this type.
197    pub const MAX_DECODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
198
199    /// Decodes a value from `input` starting at `input_index` without bounds
200    /// checks.
201    ///
202    /// # Parameters
203    ///
204    /// - `input`: Source byte buffer.
205    /// - `input_index`: Start index in `input`.
206    ///
207    /// # Returns
208    ///
209    /// Returns the decoded value and the non-zero number of consumed bytes.
210    ///
211    /// # Safety
212    ///
213    /// The caller must guarantee that `input.as_ptr().add(input_index)` is
214    /// valid to read [`Self::MIN_UNITS_PER_VALUE`] bytes.
215    #[must_use]
216    #[inline]
217    pub unsafe fn decode(input: &[u8], input_index: usize) -> (i8, NonZeroUsize) {
218        debug_assert!(input_index + Self::MIN_UNITS_PER_VALUE <= input.len());
219
220        // SAFETY: The caller guarantees that the indexed byte is readable.
221        (
222            unsafe { UncheckedSlice::read(input, input_index) } as i8,
223            nonzero(Self::MIN_UNITS_PER_VALUE),
224        )
225    }
226
227    /// Encodes `value` into `output` starting at `output_index` without bounds
228    /// checks.
229    ///
230    /// # Parameters
231    ///
232    /// - `value`: Value to encode.
233    /// - `output`: Destination byte buffer.
234    /// - `output_index`: Start index in `output`.
235    ///
236    /// # Returns
237    ///
238    /// Returns the number of bytes written, equal to
239    /// [`Self::MAX_ENCODE_UNITS_PER_VALUE`], independently of `output_index`.
240    /// The next output position is `output_index + written`, where `written`
241    /// is the returned byte count.
242    ///
243    /// # Safety
244    ///
245    /// The caller must guarantee that `output.as_mut_ptr().add(output_index)`
246    /// is valid to write [`Self::MAX_ENCODE_UNITS_PER_VALUE`] bytes.
247    #[inline]
248    pub unsafe fn encode(value: i8, output: &mut [u8], output_index: usize) -> usize {
249        debug_assert!(output_index + Self::MAX_ENCODE_UNITS_PER_VALUE <= output.len());
250
251        // SAFETY: The caller guarantees that the indexed byte is writable.
252        unsafe {
253            UncheckedSlice::write(output, output_index, value as u8);
254        }
255        Self::MAX_ENCODE_UNITS_PER_VALUE
256    }
257}
258
259impl<O> Codec for BinaryCodec<i8, O>
260where
261    O: ByteOrderSpec,
262{
263    type Value = i8;
264    type Unit = u8;
265    type DecodeError = Infallible;
266    type EncodeError = Infallible;
267
268    const MIN_UNITS_PER_VALUE: usize = 1;
269    const MAX_ENCODE_UNITS_PER_VALUE: usize = 1;
270
271    const MAX_DECODE_UNITS_PER_VALUE: usize = 1;
272
273    #[inline]
274    unsafe fn decode(
275        &mut self,
276        input: &[u8],
277        input_index: usize,
278    ) -> Result<(i8, NonZeroUsize), DecodeFailure<Self::DecodeError>> {
279        // SAFETY: The caller upholds the `Codec::decode` contract.
280        Ok(unsafe { Self::decode(input, input_index) })
281    }
282
283    #[inline]
284    unsafe fn encode(
285        &mut self,
286        value: &i8,
287        output: &mut [u8],
288        output_index: usize,
289    ) -> Result<usize, Self::EncodeError> {
290        // SAFETY: The caller upholds the `Codec::encode` contract.
291        unsafe {
292            Self::encode(*value, output, output_index);
293        }
294        Ok(Self::MAX_ENCODE_UNITS_PER_VALUE)
295    }
296}
297
298macro_rules! impl_integer_binary_codec {
299    ($ty:ty, $len:expr) => {
300        impl BinaryCodec<$ty, BigEndian> {
301            /// Minimum number of bytes required to encode or decode this type.
302            pub const MIN_UNITS_PER_VALUE: usize = <Self as Codec>::MIN_UNITS_PER_VALUE;
303
304            /// Maximum number of bytes emitted when encoding this type.
305            pub const MAX_ENCODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
306
307            /// Maximum number of bytes consumed when decoding this type.
308            pub const MAX_DECODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
309
310            /// Decodes a value from `input` starting at `input_index` without
311            /// bounds checks.
312            ///
313            /// This function is intended for hot binary codec paths where the
314            /// caller has already validated the buffer length externally.
315            ///
316            /// # Parameters
317            ///
318            /// - `input`: Source byte buffer.
319            /// - `input_index`: Start byte index in `input`.
320            ///
321            /// # Returns
322            ///
323            /// Returns the decoded value and the non-zero number of consumed
324            /// bytes.
325            ///
326            /// # Safety
327            ///
328            /// The caller must guarantee that:
329            ///
330            /// - `input_index + Self::MIN_UNITS_PER_VALUE <= input.len()`
331            /// - `input[input_index..input_index + Self::MIN_UNITS_PER_VALUE]` is valid
332            ///   for reading.
333            #[must_use]
334            #[inline]
335            pub unsafe fn decode(input: &[u8], input_index: usize) -> ($ty, NonZeroUsize) {
336                debug_assert!(input.len().saturating_sub(input_index) >= Self::MIN_UNITS_PER_VALUE);
337
338                // SAFETY:
339                // The caller guarantees that the readable range is fully
340                // in-bounds. This unaligned helper handles byte-aligned load.
341                let raw = unsafe { UncheckedSlice::read_ne_unaligned(input, input_index) };
342
343                (<$ty>::from_be(raw), nonzero(Self::MIN_UNITS_PER_VALUE))
344            }
345
346            /// Encodes `value` into `output` starting at `output_index`
347            /// without bounds checks.
348            ///
349            /// This function is intended for hot binary codec paths where the
350            /// caller has already validated the buffer length externally.
351            ///
352            /// # Parameters
353            ///
354            /// - `value`: Value to encode.
355            /// - `output`: Destination byte buffer.
356            /// - `output_index`: Start byte index in `output`.
357            ///
358            /// # Returns
359            ///
360            /// Returns the number of bytes written, equal to
361            /// [`Self::MAX_ENCODE_UNITS_PER_VALUE`], independently of `output_index`.
362            /// The next output position is `output_index + written`, where `written`
363            /// is the returned byte count.
364            ///
365            /// # Safety
366            ///
367            /// The caller must guarantee that:
368            ///
369            /// - `output_index + Self::MAX_ENCODE_UNITS_PER_VALUE <= output.len()`
370            /// - `output[output_index..output_index +
371            ///   Self::MAX_ENCODE_UNITS_PER_VALUE]` is valid for writing.
372            #[inline]
373            pub unsafe fn encode(value: $ty, output: &mut [u8], output_index: usize) -> usize {
374                debug_assert!(output.len().saturating_sub(output_index) >= Self::MAX_ENCODE_UNITS_PER_VALUE);
375
376                let raw = value.to_be();
377
378                // SAFETY:
379                // The caller guarantees that the writable range is fully
380                // in-bounds. This unaligned helper handles byte-aligned store.
381                unsafe {
382                    UncheckedSlice::write_ne_unaligned::<$ty>(output, output_index, raw);
383                }
384                Self::MAX_ENCODE_UNITS_PER_VALUE
385            }
386        }
387
388        impl Codec for BinaryCodec<$ty, BigEndian> {
389            type Value = $ty;
390            type Unit = u8;
391            type DecodeError = Infallible;
392            type EncodeError = Infallible;
393
394            const MIN_UNITS_PER_VALUE: usize = $len;
395            const MAX_ENCODE_UNITS_PER_VALUE: usize = $len;
396
397            const MAX_DECODE_UNITS_PER_VALUE: usize = $len;
398
399            #[inline]
400            unsafe fn decode(
401                &mut self,
402                input: &[u8],
403                input_index: usize,
404            ) -> Result<($ty, NonZeroUsize), DecodeFailure<Self::DecodeError>> {
405                // SAFETY: The caller upholds the `Codec::decode`
406                // contract.
407                Ok(unsafe { Self::decode(input, input_index) })
408            }
409
410            #[inline]
411            unsafe fn encode(
412                &mut self,
413                value: &$ty,
414                output: &mut [u8],
415                output_index: usize,
416            ) -> Result<usize, Self::EncodeError> {
417                // SAFETY: The caller upholds the `Codec::encode`
418                // contract.
419                unsafe {
420                    Self::encode(*value, output, output_index);
421                }
422                Ok(Self::MAX_ENCODE_UNITS_PER_VALUE)
423            }
424        }
425
426        impl BinaryCodec<$ty, LittleEndian> {
427            /// Minimum number of bytes required to encode or decode this type.
428            pub const MIN_UNITS_PER_VALUE: usize = <Self as Codec>::MIN_UNITS_PER_VALUE;
429
430            /// Maximum number of bytes emitted when encoding this type.
431            pub const MAX_ENCODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
432
433            /// Maximum number of bytes consumed when decoding this type.
434            pub const MAX_DECODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
435
436            /// Decodes a value from `input` starting at `input_index` without
437            /// bounds checks.
438            ///
439            /// This function is intended for hot binary codec paths where the
440            /// caller has already validated the buffer length externally.
441            ///
442            /// # Parameters
443            ///
444            /// - `input`: Source byte buffer.
445            /// - `input_index`: Start byte index in `input`.
446            ///
447            /// # Returns
448            ///
449            /// Returns the decoded value and the non-zero number of consumed
450            /// bytes.
451            ///
452            /// # Safety
453            ///
454            /// The caller must guarantee that:
455            ///
456            /// - `input_index + Self::MIN_UNITS_PER_VALUE <= input.len()`
457            /// - `input[input_index..input_index + Self::MIN_UNITS_PER_VALUE]` is valid
458            ///   for reading.
459            #[must_use]
460            #[inline]
461            pub unsafe fn decode(input: &[u8], input_index: usize) -> ($ty, NonZeroUsize) {
462                debug_assert!(input.len().saturating_sub(input_index) >= Self::MIN_UNITS_PER_VALUE);
463
464                // SAFETY:
465                // The caller guarantees that the readable range is fully
466                // in-bounds. This unaligned helper handles byte-aligned load.
467                let raw = unsafe { UncheckedSlice::read_ne_unaligned(input, input_index) };
468
469                (<$ty>::from_le(raw), nonzero(Self::MIN_UNITS_PER_VALUE))
470            }
471
472            /// Encodes `value` into `output` starting at `output_index`
473            /// without bounds checks.
474            ///
475            /// This function is intended for hot binary codec paths where the
476            /// caller has already validated the buffer length externally.
477            ///
478            /// # Parameters
479            ///
480            /// - `value`: Value to encode.
481            /// - `output`: Destination byte buffer.
482            /// - `output_index`: Start byte index in `output`.
483            ///
484            /// # Returns
485            ///
486            /// Returns the number of bytes written, equal to
487            /// [`Self::MAX_ENCODE_UNITS_PER_VALUE`], independently of `output_index`.
488            /// The next output position is `output_index + written`, where `written`
489            /// is the returned byte count.
490            ///
491            /// # Safety
492            ///
493            /// The caller must guarantee that:
494            ///
495            /// - `output_index + Self::MAX_ENCODE_UNITS_PER_VALUE <= output.len()`
496            /// - `output[output_index..output_index +
497            ///   Self::MAX_ENCODE_UNITS_PER_VALUE]` is valid for writing.
498            #[inline]
499            pub unsafe fn encode(value: $ty, output: &mut [u8], output_index: usize) -> usize {
500                debug_assert!(output.len().saturating_sub(output_index) >= Self::MAX_ENCODE_UNITS_PER_VALUE);
501
502                let raw = value.to_le();
503
504                // SAFETY:
505                // The caller guarantees that the writable range is fully
506                // in-bounds. This unaligned helper handles byte-aligned store.
507                unsafe {
508                    UncheckedSlice::write_ne_unaligned::<$ty>(output, output_index, raw);
509                }
510                Self::MAX_ENCODE_UNITS_PER_VALUE
511            }
512        }
513
514        impl Codec for BinaryCodec<$ty, LittleEndian> {
515            type Value = $ty;
516            type Unit = u8;
517            type DecodeError = Infallible;
518            type EncodeError = Infallible;
519
520            const MIN_UNITS_PER_VALUE: usize = $len;
521            const MAX_ENCODE_UNITS_PER_VALUE: usize = $len;
522
523            const MAX_DECODE_UNITS_PER_VALUE: usize = $len;
524
525            #[inline]
526            unsafe fn decode(
527                &mut self,
528                input: &[u8],
529                input_index: usize,
530            ) -> Result<($ty, NonZeroUsize), DecodeFailure<Self::DecodeError>> {
531                // SAFETY: The caller upholds the `Codec::decode`
532                // contract.
533                Ok(unsafe { Self::decode(input, input_index) })
534            }
535
536            #[inline]
537            unsafe fn encode(
538                &mut self,
539                value: &$ty,
540                output: &mut [u8],
541                output_index: usize,
542            ) -> Result<usize, Self::EncodeError> {
543                // SAFETY: The caller upholds the `Codec::encode`
544                // contract.
545                unsafe {
546                    Self::encode(*value, output, output_index);
547                }
548                Ok(Self::MAX_ENCODE_UNITS_PER_VALUE)
549            }
550        }
551    };
552}
553
554macro_rules! impl_float_binary_codec {
555    ($ty:ty, $bits:ty, $len:expr) => {
556        impl BinaryCodec<$ty, BigEndian> {
557            /// Minimum number of bytes required to encode or decode this type.
558            pub const MIN_UNITS_PER_VALUE: usize = <Self as Codec>::MIN_UNITS_PER_VALUE;
559
560            /// Maximum number of bytes emitted when encoding this type.
561            pub const MAX_ENCODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
562
563            /// Maximum number of bytes consumed when decoding this type.
564            pub const MAX_DECODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
565
566            /// Decodes a value from `input` starting at `input_index` without
567            /// bounds checks.
568            ///
569            /// This function is intended for hot binary codec paths where the
570            /// caller has already validated the buffer length externally.
571            ///
572            /// # Parameters
573            ///
574            /// - `input`: Source byte buffer.
575            /// - `input_index`: Start byte index in `input`.
576            ///
577            /// # Returns
578            ///
579            /// Returns the decoded floating-point value and the non-zero number
580            /// of consumed bytes.
581            ///
582            /// # Safety
583            ///
584            /// The caller must guarantee that:
585            ///
586            /// - `input_index + Self::MIN_UNITS_PER_VALUE <= input.len()`
587            /// - `input[input_index..input_index + Self::MIN_UNITS_PER_VALUE]` is valid
588            ///   for reading.
589            #[must_use]
590            #[inline]
591            pub unsafe fn decode(input: &[u8], input_index: usize) -> ($ty, NonZeroUsize) {
592                debug_assert!(input.len().saturating_sub(input_index) >= Self::MIN_UNITS_PER_VALUE);
593
594                // SAFETY:
595                // The caller guarantees that the readable range is fully
596                // in-bounds. This unaligned helper handles byte-aligned load.
597                let raw = unsafe { UncheckedSlice::read_ne_unaligned(input, input_index) };
598
599                (
600                    <$ty>::from_bits(<$bits>::from_be(raw)),
601                    nonzero(Self::MIN_UNITS_PER_VALUE),
602                )
603            }
604
605            /// Encodes `value` into `output` starting at `output_index`
606            /// without bounds checks.
607            ///
608            /// This function is intended for hot binary codec paths where the
609            /// caller has already validated the buffer length externally.
610            ///
611            /// # Parameters
612            ///
613            /// - `value`: Floating-point value to encode.
614            /// - `output`: Destination byte buffer.
615            /// - `output_index`: Start byte index in `output`.
616            ///
617            /// # Returns
618            ///
619            /// Returns the number of bytes written, equal to
620            /// [`Self::MAX_ENCODE_UNITS_PER_VALUE`], independently of `output_index`.
621            /// The next output position is `output_index + written`, where `written`
622            /// is the returned byte count.
623            ///
624            /// # Safety
625            ///
626            /// The caller must guarantee that:
627            ///
628            /// - `output_index + Self::MAX_ENCODE_UNITS_PER_VALUE <= output.len()`
629            /// - `output[output_index..output_index +
630            ///   Self::MAX_ENCODE_UNITS_PER_VALUE]` is valid for writing.
631            #[inline]
632            pub unsafe fn encode(value: $ty, output: &mut [u8], output_index: usize) -> usize {
633                debug_assert!(output.len().saturating_sub(output_index) >= Self::MAX_ENCODE_UNITS_PER_VALUE);
634
635                let raw = value.to_bits().to_be();
636
637                // SAFETY:
638                // The caller guarantees that the writable range is fully
639                // in-bounds. This unaligned helper handles byte-aligned store.
640                unsafe {
641                    UncheckedSlice::write_ne_unaligned::<$bits>(output, output_index, raw);
642                }
643                Self::MAX_ENCODE_UNITS_PER_VALUE
644            }
645        }
646
647        impl Codec for BinaryCodec<$ty, BigEndian> {
648            type Value = $ty;
649            type Unit = u8;
650            type DecodeError = Infallible;
651            type EncodeError = Infallible;
652
653            const MIN_UNITS_PER_VALUE: usize = $len;
654            const MAX_ENCODE_UNITS_PER_VALUE: usize = $len;
655
656            const MAX_DECODE_UNITS_PER_VALUE: usize = $len;
657
658            #[inline]
659            unsafe fn decode(
660                &mut self,
661                input: &[u8],
662                input_index: usize,
663            ) -> Result<($ty, NonZeroUsize), DecodeFailure<Self::DecodeError>> {
664                // SAFETY: The caller upholds the `Codec::decode`
665                // contract.
666                Ok(unsafe { Self::decode(input, input_index) })
667            }
668
669            #[inline]
670            unsafe fn encode(
671                &mut self,
672                value: &$ty,
673                output: &mut [u8],
674                output_index: usize,
675            ) -> Result<usize, Self::EncodeError> {
676                // SAFETY: The caller upholds the `Codec::encode`
677                // contract.
678                unsafe {
679                    Self::encode(*value, output, output_index);
680                }
681                Ok(Self::MAX_ENCODE_UNITS_PER_VALUE)
682            }
683        }
684
685        impl BinaryCodec<$ty, LittleEndian> {
686            /// Minimum number of bytes required to encode or decode this type.
687            pub const MIN_UNITS_PER_VALUE: usize = <Self as Codec>::MIN_UNITS_PER_VALUE;
688
689            /// Maximum number of bytes emitted when encoding this type.
690            pub const MAX_ENCODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
691
692            /// Maximum number of bytes consumed when decoding this type.
693            pub const MAX_DECODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
694
695            /// Decodes a value from `input` starting at `input_index` without
696            /// bounds checks.
697            ///
698            /// This function is intended for hot binary codec paths where the
699            /// caller has already validated the buffer length externally.
700            ///
701            /// # Parameters
702            ///
703            /// - `input`: Source byte buffer.
704            /// - `input_index`: Start byte index in `input`.
705            ///
706            /// # Returns
707            ///
708            /// Returns the decoded floating-point value and the non-zero number
709            /// of consumed bytes.
710            ///
711            /// # Safety
712            ///
713            /// The caller must guarantee that:
714            ///
715            /// - `input_index + Self::MIN_UNITS_PER_VALUE <= input.len()`
716            /// - `input[input_index..input_index + Self::MIN_UNITS_PER_VALUE]` is valid
717            ///   for reading.
718            #[must_use]
719            #[inline]
720            pub unsafe fn decode(input: &[u8], input_index: usize) -> ($ty, NonZeroUsize) {
721                debug_assert!(input.len().saturating_sub(input_index) >= Self::MIN_UNITS_PER_VALUE);
722
723                // SAFETY:
724                // The caller guarantees that the readable range is fully
725                // in-bounds. This unaligned helper handles byte-aligned load.
726                let raw = unsafe { UncheckedSlice::read_ne_unaligned(input, input_index) };
727
728                (
729                    <$ty>::from_bits(<$bits>::from_le(raw)),
730                    nonzero(Self::MIN_UNITS_PER_VALUE),
731                )
732            }
733
734            /// Encodes `value` into `output` starting at `output_index`
735            /// without bounds checks.
736            ///
737            /// This function is intended for hot binary codec paths where the
738            /// caller has already validated the buffer length externally.
739            ///
740            /// # Parameters
741            ///
742            /// - `value`: Floating-point value to encode.
743            /// - `output`: Destination byte buffer.
744            /// - `output_index`: Start byte index in `output`.
745            ///
746            /// # Returns
747            ///
748            /// Returns the number of bytes written, equal to
749            /// [`Self::MAX_ENCODE_UNITS_PER_VALUE`], independently of `output_index`.
750            /// The next output position is `output_index + written`, where `written`
751            /// is the returned byte count.
752            ///
753            /// # Safety
754            ///
755            /// The caller must guarantee that:
756            ///
757            /// - `output_index + Self::MAX_ENCODE_UNITS_PER_VALUE <= output.len()`
758            /// - `output[output_index..output_index +
759            ///   Self::MAX_ENCODE_UNITS_PER_VALUE]` is valid for writing.
760            #[inline]
761            pub unsafe fn encode(value: $ty, output: &mut [u8], output_index: usize) -> usize {
762                debug_assert!(output.len().saturating_sub(output_index) >= Self::MAX_ENCODE_UNITS_PER_VALUE);
763
764                let raw = value.to_bits().to_le();
765
766                // SAFETY:
767                // The caller guarantees that the writable range is fully
768                // in-bounds. This unaligned helper handles byte-aligned store.
769                unsafe {
770                    UncheckedSlice::write_ne_unaligned::<$bits>(output, output_index, raw);
771                }
772                Self::MAX_ENCODE_UNITS_PER_VALUE
773            }
774        }
775
776        impl Codec for BinaryCodec<$ty, LittleEndian> {
777            type Value = $ty;
778            type Unit = u8;
779            type DecodeError = Infallible;
780            type EncodeError = Infallible;
781
782            const MIN_UNITS_PER_VALUE: usize = $len;
783            const MAX_ENCODE_UNITS_PER_VALUE: usize = $len;
784
785            const MAX_DECODE_UNITS_PER_VALUE: usize = $len;
786
787            #[inline]
788            unsafe fn decode(
789                &mut self,
790                input: &[u8],
791                input_index: usize,
792            ) -> Result<($ty, NonZeroUsize), DecodeFailure<Self::DecodeError>> {
793                // SAFETY: The caller upholds the `Codec::decode`
794                // contract.
795                Ok(unsafe { Self::decode(input, input_index) })
796            }
797
798            #[inline]
799            unsafe fn encode(
800                &mut self,
801                value: &$ty,
802                output: &mut [u8],
803                output_index: usize,
804            ) -> Result<usize, Self::EncodeError> {
805                // SAFETY: The caller upholds the `Codec::encode`
806                // contract.
807                unsafe {
808                    Self::encode(*value, output, output_index);
809                }
810                Ok(Self::MAX_ENCODE_UNITS_PER_VALUE)
811            }
812        }
813    };
814}
815
816macro_rules! impl_native_integer_binary_codec {
817    ($ty:ty, $len:expr) => {
818        impl BinaryCodec<$ty, NativeEndian> {
819            /// Minimum number of bytes required to encode or decode this type.
820            pub const MIN_UNITS_PER_VALUE: usize = <Self as Codec>::MIN_UNITS_PER_VALUE;
821            /// Maximum number of bytes emitted when encoding this type.
822            pub const MAX_ENCODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
823            /// Maximum number of bytes consumed when decoding this type.
824            pub const MAX_DECODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
825
826            /// Decodes a native-endian value without bounds checks.
827            ///
828            /// # Parameters
829            ///
830            /// - `input`: Byte slice containing the encoded value.
831            /// - `input_index`: Absolute byte index where decoding starts.
832            ///
833            /// # Returns
834            ///
835            /// Returns the decoded value and the fixed number of bytes read.
836            ///
837            /// # Safety
838            ///
839            /// The caller must guarantee that at least
840            /// [`Self::MIN_UNITS_PER_VALUE`] bytes are readable from `input_index`
841            /// within `input`.
842            #[must_use]
843            #[inline]
844            pub unsafe fn decode(input: &[u8], input_index: usize) -> ($ty, NonZeroUsize) {
845                debug_assert!(input.len().saturating_sub(input_index) >= Self::MIN_UNITS_PER_VALUE);
846
847                let raw = unsafe { UncheckedSlice::read_ne_unaligned(input, input_index) };
848                (raw, nonzero(Self::MIN_UNITS_PER_VALUE))
849            }
850
851            /// Encodes a native-endian value without bounds checks.
852            ///
853            /// # Parameters
854            ///
855            /// - `value`: Value to encode.
856            /// - `output`: Destination byte slice.
857            /// - `output_index`: Absolute byte index where encoding starts.
858            ///
859            /// # Returns
860            ///
861            /// Returns the fixed number of bytes written.
862            ///
863            /// # Safety
864            ///
865            /// The caller must guarantee that at least
866            /// [`Self::MAX_ENCODE_UNITS_PER_VALUE`] bytes are writable from
867            /// `output_index` within `output`.
868            #[inline]
869            pub unsafe fn encode(value: $ty, output: &mut [u8], output_index: usize) -> usize {
870                debug_assert!(output.len().saturating_sub(output_index) >= Self::MAX_ENCODE_UNITS_PER_VALUE);
871
872                unsafe { UncheckedSlice::write_ne_unaligned(output, output_index, value) };
873                Self::MAX_ENCODE_UNITS_PER_VALUE
874            }
875        }
876
877        impl Codec for BinaryCodec<$ty, NativeEndian> {
878            type Value = $ty;
879            type Unit = u8;
880            type DecodeError = Infallible;
881            type EncodeError = Infallible;
882            const MIN_UNITS_PER_VALUE: usize = $len;
883            const MAX_ENCODE_UNITS_PER_VALUE: usize = $len;
884            const MAX_DECODE_UNITS_PER_VALUE: usize = $len;
885
886            #[inline]
887            unsafe fn decode(
888                &mut self,
889                input: &[u8],
890                input_index: usize,
891            ) -> Result<($ty, NonZeroUsize), DecodeFailure<Self::DecodeError>> {
892                Ok(unsafe { Self::decode(input, input_index) })
893            }
894
895            #[inline]
896            unsafe fn encode(
897                &mut self,
898                value: &$ty,
899                output: &mut [u8],
900                output_index: usize,
901            ) -> Result<usize, Self::EncodeError> {
902                unsafe { Self::encode(*value, output, output_index) };
903                Ok(Self::MAX_ENCODE_UNITS_PER_VALUE)
904            }
905        }
906    };
907}
908
909macro_rules! impl_native_float_binary_codec {
910    ($ty:ty, $bits:ty, $len:expr) => {
911        impl BinaryCodec<$ty, NativeEndian> {
912            /// Minimum number of bytes required to encode or decode this type.
913            pub const MIN_UNITS_PER_VALUE: usize = <Self as Codec>::MIN_UNITS_PER_VALUE;
914            /// Maximum number of bytes emitted when encoding this type.
915            pub const MAX_ENCODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
916            /// Maximum number of bytes consumed when decoding this type.
917            pub const MAX_DECODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
918
919            /// Decodes a native-endian floating-point value without bounds
920            /// checks.
921            ///
922            /// # Parameters
923            ///
924            /// - `input`: Byte slice containing the encoded value.
925            /// - `input_index`: Absolute byte index where decoding starts.
926            ///
927            /// # Returns
928            ///
929            /// Returns the decoded floating-point value and fixed byte count.
930            ///
931            /// # Safety
932            ///
933            /// The caller must guarantee that at least
934            /// [`Self::MIN_UNITS_PER_VALUE`] bytes are readable from `input_index`
935            /// within `input`.
936            #[must_use]
937            #[inline]
938            pub unsafe fn decode(input: &[u8], input_index: usize) -> ($ty, NonZeroUsize) {
939                debug_assert!(input.len().saturating_sub(input_index) >= Self::MIN_UNITS_PER_VALUE);
940
941                let raw = unsafe { UncheckedSlice::read_ne_unaligned(input, input_index) };
942                (<$ty>::from_bits(raw), nonzero(Self::MIN_UNITS_PER_VALUE))
943            }
944
945            /// Encodes a native-endian floating-point value without bounds
946            /// checks.
947            ///
948            /// # Parameters
949            ///
950            /// - `value`: Floating-point value to encode.
951            /// - `output`: Destination byte slice.
952            /// - `output_index`: Absolute byte index where encoding starts.
953            ///
954            /// # Returns
955            ///
956            /// Returns the fixed number of bytes written.
957            ///
958            /// # Safety
959            ///
960            /// The caller must guarantee that at least
961            /// [`Self::MAX_ENCODE_UNITS_PER_VALUE`] bytes are writable from
962            /// `output_index` within `output`.
963            #[inline]
964            pub unsafe fn encode(value: $ty, output: &mut [u8], output_index: usize) -> usize {
965                debug_assert!(output.len().saturating_sub(output_index) >= Self::MAX_ENCODE_UNITS_PER_VALUE);
966
967                unsafe { UncheckedSlice::write_ne_unaligned(output, output_index, value.to_bits()) };
968                Self::MAX_ENCODE_UNITS_PER_VALUE
969            }
970        }
971
972        impl Codec for BinaryCodec<$ty, NativeEndian> {
973            type Value = $ty;
974            type Unit = u8;
975            type DecodeError = Infallible;
976            type EncodeError = Infallible;
977            const MIN_UNITS_PER_VALUE: usize = $len;
978            const MAX_ENCODE_UNITS_PER_VALUE: usize = $len;
979            const MAX_DECODE_UNITS_PER_VALUE: usize = $len;
980
981            #[inline]
982            unsafe fn decode(
983                &mut self,
984                input: &[u8],
985                input_index: usize,
986            ) -> Result<($ty, NonZeroUsize), DecodeFailure<Self::DecodeError>> {
987                Ok(unsafe { Self::decode(input, input_index) })
988            }
989
990            #[inline]
991            unsafe fn encode(
992                &mut self,
993                value: &$ty,
994                output: &mut [u8],
995                output_index: usize,
996            ) -> Result<usize, Self::EncodeError> {
997                unsafe { Self::encode(*value, output, output_index) };
998                Ok(Self::MAX_ENCODE_UNITS_PER_VALUE)
999            }
1000        }
1001    };
1002}
1003
1004impl_integer_binary_codec!(u16, 2);
1005impl_integer_binary_codec!(u32, 4);
1006impl_integer_binary_codec!(u64, 8);
1007impl_integer_binary_codec!(u128, 16);
1008impl_integer_binary_codec!(i16, 2);
1009impl_integer_binary_codec!(i32, 4);
1010impl_integer_binary_codec!(i64, 8);
1011impl_integer_binary_codec!(i128, 16);
1012impl_float_binary_codec!(f32, u32, 4);
1013impl_float_binary_codec!(f64, u64, 8);
1014impl_native_integer_binary_codec!(u16, 2);
1015impl_native_integer_binary_codec!(u32, 4);
1016impl_native_integer_binary_codec!(u64, 8);
1017impl_native_integer_binary_codec!(u128, 16);
1018impl_native_integer_binary_codec!(i16, 2);
1019impl_native_integer_binary_codec!(i32, 4);
1020impl_native_integer_binary_codec!(i64, 8);
1021impl_native_integer_binary_codec!(i128, 16);
1022impl_native_float_binary_codec!(f32, u32, 4);
1023impl_native_float_binary_codec!(f64, u64, 8);