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