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