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