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