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_io::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_io::UncheckedSlice::read(input, input_index) },
117 qubit_codec::nz!(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_io::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_codec::nz!(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_io::UncheckedSlice::write(output, output_index, value as u8);
266 }
267 Self::MAX_ENCODE_UNITS_PER_VALUE
268 }
269}
270
271impl<O> Codec for BinaryCodec<i8, O>
272where
273 O: ByteOrderSpec,
274{
275 type Value = i8;
276 type Unit = u8;
277 type DecodeError = Infallible;
278 type EncodeError = Infallible;
279
280 const MIN_UNITS_PER_VALUE: usize = 1;
281 const MAX_ENCODE_UNITS_PER_VALUE: usize = 1;
282
283 const MAX_DECODE_UNITS_PER_VALUE: usize = 1;
284
285 #[inline(always)]
286 unsafe fn decode(
287 &mut self,
288 input: &[u8],
289 input_index: usize,
290 ) -> Result<
291 (i8, core::num::NonZeroUsize),
292 qubit_codec::DecodeFailure<Self::DecodeError>,
293 > {
294 // SAFETY: The caller upholds the `Codec::decode` contract.
295 Ok(unsafe { Self::decode(input, input_index) })
296 }
297
298 #[inline(always)]
299 unsafe fn encode(
300 &mut self,
301 value: &i8,
302 output: &mut [u8],
303 output_index: usize,
304 ) -> Result<usize, Self::EncodeError> {
305 // SAFETY: The caller upholds the `Codec::encode` contract.
306 unsafe {
307 Self::encode(*value, output, output_index);
308 }
309 Ok(Self::MAX_ENCODE_UNITS_PER_VALUE)
310 }
311}
312
313macro_rules! impl_integer_binary_codec {
314 ($ty:ty, $len:expr) => {
315 impl BinaryCodec<$ty, BigEndian> {
316 /// Minimum number of bytes required to encode or decode this type.
317 pub const MIN_UNITS_PER_VALUE: usize =
318 <Self as Codec>::MIN_UNITS_PER_VALUE;
319
320 /// Maximum number of bytes emitted when encoding this type.
321 pub const MAX_ENCODE_UNITS_PER_VALUE: usize =
322 <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
323
324 /// Maximum number of bytes consumed when decoding this type.
325 pub const MAX_DECODE_UNITS_PER_VALUE: usize =
326 <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
327
328 /// Decodes a value from `input` starting at `input_index` without
329 /// bounds checks.
330 ///
331 /// This function is intended for hot binary codec paths where the
332 /// caller has already validated the buffer length externally.
333 ///
334 /// # Parameters
335 ///
336 /// - `input`: Source byte buffer.
337 /// - `input_index`: Start byte index in `input`.
338 ///
339 /// # Returns
340 ///
341 /// Returns the decoded value and the non-zero number of consumed
342 /// bytes.
343 ///
344 /// # Safety
345 ///
346 /// The caller must guarantee that:
347 ///
348 /// - `input_index + Self::MIN_UNITS_PER_VALUE <= input.len()`
349 /// - `input[input_index..input_index + Self::MIN_UNITS_PER_VALUE]`
350 /// is valid for reading.
351 #[must_use]
352 #[inline(always)]
353 pub unsafe fn decode(
354 input: &[u8],
355 input_index: usize,
356 ) -> ($ty, core::num::NonZeroUsize) {
357 // SAFETY:
358 // The caller guarantees that the readable range is fully
359 // in-bounds. This unaligned helper handles byte-aligned load.
360 let raw = unsafe {
361 UncheckedSlice::read_ne_unaligned(input, input_index)
362 };
363
364 (
365 <$ty>::from_be(raw),
366 qubit_codec::nz!(Self::MIN_UNITS_PER_VALUE),
367 )
368 }
369
370 /// Encodes `value` into `output` starting at `output_index`
371 /// without bounds checks.
372 ///
373 /// This function is intended for hot binary codec paths where the
374 /// caller has already validated the buffer length externally.
375 ///
376 /// # Parameters
377 ///
378 /// - `value`: Value to encode.
379 /// - `output`: Destination byte buffer.
380 /// - `output_index`: Start byte index in `output`.
381 ///
382 /// # Safety
383 ///
384 /// The caller must guarantee that:
385 ///
386 /// - `output_index + Self::MAX_ENCODE_UNITS_PER_VALUE <=
387 /// output.len()`
388 /// - `output[output_index..output_index +
389 /// Self::MAX_ENCODE_UNITS_PER_VALUE]` is valid for writing.
390 #[inline(always)]
391 pub unsafe fn encode(
392 value: $ty,
393 output: &mut [u8],
394 output_index: usize,
395 ) -> usize {
396 let raw = value.to_be();
397
398 // SAFETY:
399 // The caller guarantees that the writable range is fully
400 // in-bounds. This unaligned helper handles byte-aligned store.
401 unsafe {
402 UncheckedSlice::write_ne_unaligned::<$ty>(
403 output,
404 output_index,
405 raw,
406 );
407 }
408 Self::MAX_ENCODE_UNITS_PER_VALUE
409 }
410 }
411
412 impl Codec for BinaryCodec<$ty, BigEndian> {
413 type Value = $ty;
414 type Unit = u8;
415 type DecodeError = Infallible;
416 type EncodeError = Infallible;
417
418 const MIN_UNITS_PER_VALUE: usize = $len;
419 const MAX_ENCODE_UNITS_PER_VALUE: usize = $len;
420
421 const MAX_DECODE_UNITS_PER_VALUE: usize = $len;
422
423 #[inline(always)]
424 unsafe fn decode(
425 &mut self,
426 input: &[u8],
427 input_index: usize,
428 ) -> Result<
429 ($ty, core::num::NonZeroUsize),
430 qubit_codec::DecodeFailure<Self::DecodeError>,
431 > {
432 // SAFETY: The caller upholds the `Codec::decode`
433 // contract.
434 Ok(unsafe { Self::decode(input, input_index) })
435 }
436
437 #[inline(always)]
438 unsafe fn encode(
439 &mut self,
440 value: &$ty,
441 output: &mut [u8],
442 output_index: usize,
443 ) -> Result<usize, Self::EncodeError> {
444 // SAFETY: The caller upholds the `Codec::encode`
445 // contract.
446 unsafe {
447 Self::encode(*value, output, output_index);
448 }
449 Ok(Self::MAX_ENCODE_UNITS_PER_VALUE)
450 }
451 }
452
453 impl BinaryCodec<$ty, LittleEndian> {
454 /// Minimum number of bytes required to encode or decode this type.
455 pub const MIN_UNITS_PER_VALUE: usize =
456 <Self as Codec>::MIN_UNITS_PER_VALUE;
457
458 /// Maximum number of bytes emitted when encoding this type.
459 pub const MAX_ENCODE_UNITS_PER_VALUE: usize =
460 <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
461
462 /// Maximum number of bytes consumed when decoding this type.
463 pub const MAX_DECODE_UNITS_PER_VALUE: usize =
464 <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
465
466 /// Decodes a value from `input` starting at `input_index` without
467 /// bounds checks.
468 ///
469 /// This function is intended for hot binary codec paths where the
470 /// caller has already validated the buffer length externally.
471 ///
472 /// # Parameters
473 ///
474 /// - `input`: Source byte buffer.
475 /// - `input_index`: Start byte index in `input`.
476 ///
477 /// # Returns
478 ///
479 /// Returns the decoded value and the non-zero number of consumed
480 /// bytes.
481 ///
482 /// # Safety
483 ///
484 /// The caller must guarantee that:
485 ///
486 /// - `input_index + Self::MIN_UNITS_PER_VALUE <= input.len()`
487 /// - `input[input_index..input_index + Self::MIN_UNITS_PER_VALUE]`
488 /// is valid for reading.
489 #[must_use]
490 #[inline(always)]
491 pub unsafe fn decode(
492 input: &[u8],
493 input_index: usize,
494 ) -> ($ty, core::num::NonZeroUsize) {
495 // SAFETY:
496 // The caller guarantees that the readable range is fully
497 // in-bounds. This unaligned helper handles byte-aligned load.
498 let raw = unsafe {
499 UncheckedSlice::read_ne_unaligned(input, input_index)
500 };
501
502 (
503 <$ty>::from_le(raw),
504 qubit_codec::nz!(Self::MIN_UNITS_PER_VALUE),
505 )
506 }
507
508 /// Encodes `value` into `output` starting at `output_index`
509 /// without bounds checks.
510 ///
511 /// This function is intended for hot binary codec paths where the
512 /// caller has already validated the buffer length externally.
513 ///
514 /// # Parameters
515 ///
516 /// - `value`: Value to encode.
517 /// - `output`: Destination byte buffer.
518 /// - `output_index`: Start byte index in `output`.
519 ///
520 /// # Safety
521 ///
522 /// The caller must guarantee that:
523 ///
524 /// - `output_index + Self::MAX_ENCODE_UNITS_PER_VALUE <=
525 /// output.len()`
526 /// - `output[output_index..output_index +
527 /// Self::MAX_ENCODE_UNITS_PER_VALUE]` is valid for writing.
528 #[inline(always)]
529 pub unsafe fn encode(
530 value: $ty,
531 output: &mut [u8],
532 output_index: usize,
533 ) -> usize {
534 let raw = value.to_le();
535
536 // SAFETY:
537 // The caller guarantees that the writable range is fully
538 // in-bounds. This unaligned helper handles byte-aligned store.
539 unsafe {
540 UncheckedSlice::write_ne_unaligned::<$ty>(
541 output,
542 output_index,
543 raw,
544 );
545 }
546 Self::MAX_ENCODE_UNITS_PER_VALUE
547 }
548 }
549
550 impl Codec for BinaryCodec<$ty, LittleEndian> {
551 type Value = $ty;
552 type Unit = u8;
553 type DecodeError = Infallible;
554 type EncodeError = Infallible;
555
556 const MIN_UNITS_PER_VALUE: usize = $len;
557 const MAX_ENCODE_UNITS_PER_VALUE: usize = $len;
558
559 const MAX_DECODE_UNITS_PER_VALUE: usize = $len;
560
561 #[inline(always)]
562 unsafe fn decode(
563 &mut self,
564 input: &[u8],
565 input_index: usize,
566 ) -> Result<
567 ($ty, core::num::NonZeroUsize),
568 qubit_codec::DecodeFailure<Self::DecodeError>,
569 > {
570 // SAFETY: The caller upholds the `Codec::decode`
571 // contract.
572 Ok(unsafe { Self::decode(input, input_index) })
573 }
574
575 #[inline(always)]
576 unsafe fn encode(
577 &mut self,
578 value: &$ty,
579 output: &mut [u8],
580 output_index: usize,
581 ) -> Result<usize, Self::EncodeError> {
582 // SAFETY: The caller upholds the `Codec::encode`
583 // contract.
584 unsafe {
585 Self::encode(*value, output, output_index);
586 }
587 Ok(Self::MAX_ENCODE_UNITS_PER_VALUE)
588 }
589 }
590 };
591}
592
593macro_rules! impl_float_binary_codec {
594 ($ty:ty, $bits:ty, $len:expr) => {
595 impl BinaryCodec<$ty, BigEndian> {
596 /// Minimum number of bytes required to encode or decode this type.
597 pub const MIN_UNITS_PER_VALUE: usize =
598 <Self as Codec>::MIN_UNITS_PER_VALUE;
599
600 /// Maximum number of bytes emitted when encoding this type.
601 pub const MAX_ENCODE_UNITS_PER_VALUE: usize =
602 <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
603
604 /// Maximum number of bytes consumed when decoding this type.
605 pub const MAX_DECODE_UNITS_PER_VALUE: usize =
606 <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
607
608 /// Decodes a value from `input` starting at `input_index` without
609 /// bounds checks.
610 ///
611 /// This function is intended for hot binary codec paths where the
612 /// caller has already validated the buffer length externally.
613 ///
614 /// # Parameters
615 ///
616 /// - `input`: Source byte buffer.
617 /// - `input_index`: Start byte index in `input`.
618 ///
619 /// # Returns
620 ///
621 /// Returns the decoded floating-point value and the non-zero number
622 /// of consumed bytes.
623 ///
624 /// # Safety
625 ///
626 /// The caller must guarantee that:
627 ///
628 /// - `input_index + Self::MIN_UNITS_PER_VALUE <= input.len()`
629 /// - `input[input_index..input_index + Self::MIN_UNITS_PER_VALUE]`
630 /// is valid for reading.
631 #[must_use]
632 #[inline(always)]
633 pub unsafe fn decode(
634 input: &[u8],
635 input_index: usize,
636 ) -> ($ty, core::num::NonZeroUsize) {
637 // SAFETY:
638 // The caller guarantees that the readable range is fully
639 // in-bounds. This unaligned helper handles byte-aligned load.
640 let raw = unsafe {
641 UncheckedSlice::read_ne_unaligned(input, input_index)
642 };
643
644 (
645 <$ty>::from_bits(<$bits>::from_be(raw)),
646 qubit_codec::nz!(Self::MIN_UNITS_PER_VALUE),
647 )
648 }
649
650 /// Encodes `value` into `output` starting at `output_index`
651 /// without bounds checks.
652 ///
653 /// This function is intended for hot binary codec paths where the
654 /// caller has already validated the buffer length externally.
655 ///
656 /// # Parameters
657 ///
658 /// - `value`: Floating-point value to encode.
659 /// - `output`: Destination byte buffer.
660 /// - `output_index`: Start byte index in `output`.
661 ///
662 /// # Safety
663 ///
664 /// The caller must guarantee that:
665 ///
666 /// - `output_index + Self::MAX_ENCODE_UNITS_PER_VALUE <=
667 /// output.len()`
668 /// - `output[output_index..output_index +
669 /// Self::MAX_ENCODE_UNITS_PER_VALUE]` is valid for writing.
670 #[inline(always)]
671 pub unsafe fn encode(
672 value: $ty,
673 output: &mut [u8],
674 output_index: usize,
675 ) -> usize {
676 let raw = value.to_bits().to_be();
677
678 // SAFETY:
679 // The caller guarantees that the writable range is fully
680 // in-bounds. This unaligned helper handles byte-aligned store.
681 unsafe {
682 UncheckedSlice::write_ne_unaligned::<$bits>(
683 output,
684 output_index,
685 raw,
686 );
687 }
688 Self::MAX_ENCODE_UNITS_PER_VALUE
689 }
690 }
691
692 impl Codec for BinaryCodec<$ty, BigEndian> {
693 type Value = $ty;
694 type Unit = u8;
695 type DecodeError = Infallible;
696 type EncodeError = Infallible;
697
698 const MIN_UNITS_PER_VALUE: usize = $len;
699 const MAX_ENCODE_UNITS_PER_VALUE: usize = $len;
700
701 const MAX_DECODE_UNITS_PER_VALUE: usize = $len;
702
703 #[inline(always)]
704 unsafe fn decode(
705 &mut self,
706 input: &[u8],
707 input_index: usize,
708 ) -> Result<
709 ($ty, core::num::NonZeroUsize),
710 qubit_codec::DecodeFailure<Self::DecodeError>,
711 > {
712 // SAFETY: The caller upholds the `Codec::decode`
713 // contract.
714 Ok(unsafe { Self::decode(input, input_index) })
715 }
716
717 #[inline(always)]
718 unsafe fn encode(
719 &mut self,
720 value: &$ty,
721 output: &mut [u8],
722 output_index: usize,
723 ) -> Result<usize, Self::EncodeError> {
724 // SAFETY: The caller upholds the `Codec::encode`
725 // contract.
726 unsafe {
727 Self::encode(*value, output, output_index);
728 }
729 Ok(Self::MAX_ENCODE_UNITS_PER_VALUE)
730 }
731 }
732
733 impl BinaryCodec<$ty, LittleEndian> {
734 /// Minimum number of bytes required to encode or decode this type.
735 pub const MIN_UNITS_PER_VALUE: usize =
736 <Self as Codec>::MIN_UNITS_PER_VALUE;
737
738 /// Maximum number of bytes emitted when encoding this type.
739 pub const MAX_ENCODE_UNITS_PER_VALUE: usize =
740 <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
741
742 /// Maximum number of bytes consumed when decoding this type.
743 pub const MAX_DECODE_UNITS_PER_VALUE: usize =
744 <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
745
746 /// Decodes a value from `input` starting at `input_index` without
747 /// bounds checks.
748 ///
749 /// This function is intended for hot binary codec paths where the
750 /// caller has already validated the buffer length externally.
751 ///
752 /// # Parameters
753 ///
754 /// - `input`: Source byte buffer.
755 /// - `input_index`: Start byte index in `input`.
756 ///
757 /// # Returns
758 ///
759 /// Returns the decoded floating-point value and the non-zero number
760 /// of consumed bytes.
761 ///
762 /// # Safety
763 ///
764 /// The caller must guarantee that:
765 ///
766 /// - `input_index + Self::MIN_UNITS_PER_VALUE <= input.len()`
767 /// - `input[input_index..input_index + Self::MIN_UNITS_PER_VALUE]`
768 /// is valid for reading.
769 #[must_use]
770 #[inline(always)]
771 pub unsafe fn decode(
772 input: &[u8],
773 input_index: usize,
774 ) -> ($ty, core::num::NonZeroUsize) {
775 // SAFETY:
776 // The caller guarantees that the readable range is fully
777 // in-bounds. This unaligned helper handles byte-aligned load.
778 let raw = unsafe {
779 UncheckedSlice::read_ne_unaligned(input, input_index)
780 };
781
782 (
783 <$ty>::from_bits(<$bits>::from_le(raw)),
784 qubit_codec::nz!(Self::MIN_UNITS_PER_VALUE),
785 )
786 }
787
788 /// Encodes `value` into `output` starting at `output_index`
789 /// without bounds checks.
790 ///
791 /// This function is intended for hot binary codec paths where the
792 /// caller has already validated the buffer length externally.
793 ///
794 /// # Parameters
795 ///
796 /// - `value`: Floating-point value to encode.
797 /// - `output`: Destination byte buffer.
798 /// - `output_index`: Start byte index in `output`.
799 ///
800 /// # Safety
801 ///
802 /// The caller must guarantee that:
803 ///
804 /// - `output_index + Self::MAX_ENCODE_UNITS_PER_VALUE <=
805 /// output.len()`
806 /// - `output[output_index..output_index +
807 /// Self::MAX_ENCODE_UNITS_PER_VALUE]` is valid for writing.
808 #[inline(always)]
809 pub unsafe fn encode(
810 value: $ty,
811 output: &mut [u8],
812 output_index: usize,
813 ) -> usize {
814 let raw = value.to_bits().to_le();
815
816 // SAFETY:
817 // The caller guarantees that the writable range is fully
818 // in-bounds. This unaligned helper handles byte-aligned store.
819 unsafe {
820 UncheckedSlice::write_ne_unaligned::<$bits>(
821 output,
822 output_index,
823 raw,
824 );
825 }
826 Self::MAX_ENCODE_UNITS_PER_VALUE
827 }
828 }
829
830 impl Codec for BinaryCodec<$ty, LittleEndian> {
831 type Value = $ty;
832 type Unit = u8;
833 type DecodeError = Infallible;
834 type EncodeError = Infallible;
835
836 const MIN_UNITS_PER_VALUE: usize = $len;
837 const MAX_ENCODE_UNITS_PER_VALUE: usize = $len;
838
839 const MAX_DECODE_UNITS_PER_VALUE: usize = $len;
840
841 #[inline(always)]
842 unsafe fn decode(
843 &mut self,
844 input: &[u8],
845 input_index: usize,
846 ) -> Result<
847 ($ty, core::num::NonZeroUsize),
848 qubit_codec::DecodeFailure<Self::DecodeError>,
849 > {
850 // SAFETY: The caller upholds the `Codec::decode`
851 // contract.
852 Ok(unsafe { Self::decode(input, input_index) })
853 }
854
855 #[inline(always)]
856 unsafe fn encode(
857 &mut self,
858 value: &$ty,
859 output: &mut [u8],
860 output_index: usize,
861 ) -> Result<usize, Self::EncodeError> {
862 // SAFETY: The caller upholds the `Codec::encode`
863 // contract.
864 unsafe {
865 Self::encode(*value, output, output_index);
866 }
867 Ok(Self::MAX_ENCODE_UNITS_PER_VALUE)
868 }
869 }
870 };
871}
872
873macro_rules! impl_native_integer_binary_codec {
874 ($ty:ty, $len:expr) => {
875 impl BinaryCodec<$ty, NativeEndian> {
876 /// Minimum number of bytes required to encode or decode this type.
877 pub const MIN_UNITS_PER_VALUE: usize =
878 <Self as Codec>::MIN_UNITS_PER_VALUE;
879 /// Maximum number of bytes emitted when encoding this type.
880 pub const MAX_ENCODE_UNITS_PER_VALUE: usize =
881 <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
882 /// Maximum number of bytes consumed when decoding this type.
883 pub const MAX_DECODE_UNITS_PER_VALUE: usize =
884 <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
885
886 /// Decodes a native-endian value without bounds checks.
887 ///
888 /// # Parameters
889 ///
890 /// - `input`: Byte slice containing the encoded value.
891 /// - `input_index`: Absolute byte index where decoding starts.
892 ///
893 /// # Returns
894 ///
895 /// Returns the decoded value and the fixed number of bytes read.
896 ///
897 /// # Safety
898 /// `input_index..input_index + size_of::<$ty>()` must be a valid
899 /// readable range within `input`.
900 #[must_use]
901 #[inline(always)]
902 pub unsafe fn decode(
903 input: &[u8],
904 input_index: usize,
905 ) -> ($ty, core::num::NonZeroUsize) {
906 let raw = unsafe {
907 UncheckedSlice::read_ne_unaligned(input, input_index)
908 };
909 (raw, qubit_codec::nz!(Self::MIN_UNITS_PER_VALUE))
910 }
911
912 /// Encodes a native-endian value without bounds checks.
913 ///
914 /// # Parameters
915 ///
916 /// - `value`: Value to encode.
917 /// - `output`: Destination byte slice.
918 /// - `output_index`: Absolute byte index where encoding starts.
919 ///
920 /// # Returns
921 ///
922 /// Returns the fixed number of bytes written.
923 ///
924 /// # Safety
925 /// `output_index..output_index + size_of::<$ty>()` must be a valid
926 /// writable range within `output`.
927 #[inline(always)]
928 pub unsafe fn encode(
929 value: $ty,
930 output: &mut [u8],
931 output_index: usize,
932 ) -> usize {
933 unsafe {
934 UncheckedSlice::write_ne_unaligned(
935 output,
936 output_index,
937 value,
938 )
939 };
940 Self::MAX_ENCODE_UNITS_PER_VALUE
941 }
942 }
943
944 impl Codec for BinaryCodec<$ty, NativeEndian> {
945 type Value = $ty;
946 type Unit = u8;
947 type DecodeError = Infallible;
948 type EncodeError = Infallible;
949 const MIN_UNITS_PER_VALUE: usize = $len;
950 const MAX_ENCODE_UNITS_PER_VALUE: usize = $len;
951 const MAX_DECODE_UNITS_PER_VALUE: usize = $len;
952
953 #[inline(always)]
954 unsafe fn decode(
955 &mut self,
956 input: &[u8],
957 input_index: usize,
958 ) -> Result<
959 ($ty, core::num::NonZeroUsize),
960 qubit_codec::DecodeFailure<Self::DecodeError>,
961 > {
962 Ok(unsafe { Self::decode(input, input_index) })
963 }
964
965 #[inline(always)]
966 unsafe fn encode(
967 &mut self,
968 value: &$ty,
969 output: &mut [u8],
970 output_index: usize,
971 ) -> Result<usize, Self::EncodeError> {
972 unsafe { Self::encode(*value, output, output_index) };
973 Ok(Self::MAX_ENCODE_UNITS_PER_VALUE)
974 }
975 }
976 };
977}
978
979macro_rules! impl_native_float_binary_codec {
980 ($ty:ty, $bits:ty, $len:expr) => {
981 impl BinaryCodec<$ty, NativeEndian> {
982 /// Minimum number of bytes required to encode or decode this type.
983 pub const MIN_UNITS_PER_VALUE: usize =
984 <Self as Codec>::MIN_UNITS_PER_VALUE;
985 /// Maximum number of bytes emitted when encoding this type.
986 pub const MAX_ENCODE_UNITS_PER_VALUE: usize =
987 <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
988 /// Maximum number of bytes consumed when decoding this type.
989 pub const MAX_DECODE_UNITS_PER_VALUE: usize =
990 <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
991
992 /// Decodes a native-endian floating-point value without bounds
993 /// checks.
994 ///
995 /// # Parameters
996 ///
997 /// - `input`: Byte slice containing the encoded value.
998 /// - `input_index`: Absolute byte index where decoding starts.
999 ///
1000 /// # Returns
1001 ///
1002 /// Returns the decoded floating-point value and fixed byte count.
1003 ///
1004 /// # Safety
1005 /// `input_index..input_index + size_of::<$ty>()` must be a valid
1006 /// readable range within `input`.
1007 #[must_use]
1008 #[inline(always)]
1009 pub unsafe fn decode(
1010 input: &[u8],
1011 input_index: usize,
1012 ) -> ($ty, core::num::NonZeroUsize) {
1013 let raw = unsafe {
1014 UncheckedSlice::read_ne_unaligned(input, input_index)
1015 };
1016 (
1017 <$ty>::from_bits(raw),
1018 qubit_codec::nz!(Self::MIN_UNITS_PER_VALUE),
1019 )
1020 }
1021
1022 /// Encodes a native-endian floating-point value without bounds
1023 /// checks.
1024 ///
1025 /// # Parameters
1026 ///
1027 /// - `value`: Floating-point value to encode.
1028 /// - `output`: Destination byte slice.
1029 /// - `output_index`: Absolute byte index where encoding starts.
1030 ///
1031 /// # Returns
1032 ///
1033 /// Returns the fixed number of bytes written.
1034 ///
1035 /// # Safety
1036 /// `output_index..output_index + size_of::<$ty>()` must be a valid
1037 /// writable range within `output`.
1038 #[inline(always)]
1039 pub unsafe fn encode(
1040 value: $ty,
1041 output: &mut [u8],
1042 output_index: usize,
1043 ) -> usize {
1044 unsafe {
1045 UncheckedSlice::write_ne_unaligned(
1046 output,
1047 output_index,
1048 value.to_bits(),
1049 )
1050 };
1051 Self::MAX_ENCODE_UNITS_PER_VALUE
1052 }
1053 }
1054
1055 impl Codec for BinaryCodec<$ty, NativeEndian> {
1056 type Value = $ty;
1057 type Unit = u8;
1058 type DecodeError = Infallible;
1059 type EncodeError = Infallible;
1060 const MIN_UNITS_PER_VALUE: usize = $len;
1061 const MAX_ENCODE_UNITS_PER_VALUE: usize = $len;
1062 const MAX_DECODE_UNITS_PER_VALUE: usize = $len;
1063
1064 #[inline(always)]
1065 unsafe fn decode(
1066 &mut self,
1067 input: &[u8],
1068 input_index: usize,
1069 ) -> Result<
1070 ($ty, core::num::NonZeroUsize),
1071 qubit_codec::DecodeFailure<Self::DecodeError>,
1072 > {
1073 Ok(unsafe { Self::decode(input, input_index) })
1074 }
1075
1076 #[inline(always)]
1077 unsafe fn encode(
1078 &mut self,
1079 value: &$ty,
1080 output: &mut [u8],
1081 output_index: usize,
1082 ) -> Result<usize, Self::EncodeError> {
1083 unsafe { Self::encode(*value, output, output_index) };
1084 Ok(Self::MAX_ENCODE_UNITS_PER_VALUE)
1085 }
1086 }
1087 };
1088}
1089
1090impl_integer_binary_codec!(u16, 2);
1091impl_integer_binary_codec!(u32, 4);
1092impl_integer_binary_codec!(u64, 8);
1093impl_integer_binary_codec!(u128, 16);
1094impl_integer_binary_codec!(i16, 2);
1095impl_integer_binary_codec!(i32, 4);
1096impl_integer_binary_codec!(i64, 8);
1097impl_integer_binary_codec!(i128, 16);
1098impl_float_binary_codec!(f32, u32, 4);
1099impl_float_binary_codec!(f64, u64, 8);
1100impl_native_integer_binary_codec!(u16, 2);
1101impl_native_integer_binary_codec!(u32, 4);
1102impl_native_integer_binary_codec!(u64, 8);
1103impl_native_integer_binary_codec!(u128, 16);
1104impl_native_integer_binary_codec!(i16, 2);
1105impl_native_integer_binary_codec!(i32, 4);
1106impl_native_integer_binary_codec!(i64, 8);
1107impl_native_integer_binary_codec!(i128, 16);
1108impl_native_float_binary_codec!(f32, u32, 4);
1109impl_native_float_binary_codec!(f64, u64, 8);