Skip to main content

qubit_codec_binary/codec/
zig_zag_codec.rs

1// =============================================================================
2//    Copyright (c) 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8
9use core::convert::Infallible;
10use core::marker::PhantomData;
11
12use qubit_codec::Codec;
13use qubit_codec::DecodeFailure;
14
15use crate::Leb128Codec;
16use crate::Leb128DecodeError;
17use crate::Leb128DecodePolicy;
18use crate::NonStrict;
19use crate::codec::leb128_codec::map_leb128_decode_failure;
20use crate::codec::leb128_codec::uleb_encoded_len;
21
22/// Type-level unchecked ZigZag + unsigned LEB128 codec.
23///
24/// Encoding is always canonical; `P` only affects decoding. Encoding-only
25/// callers should conventionally use [`NonStrict`] because no decoding policy
26/// is applied on that path.
27///
28/// # Type Parameters
29///
30/// - `T`: Signed integer value type to decode from ZigZag-encoded LEB128 bytes
31///   and encode into ZigZag-encoded LEB128 bytes.
32/// - `P`: Required type-level decoding policy implementing
33///   [`Leb128DecodePolicy`] for the underlying unsigned LEB128 payload. Use
34///   [`crate::Strict`] to reject non-canonical inputs, or [`NonStrict`] to
35///   accept non-canonical inputs. This parameter does not affect canonical
36///   encoding.
37///
38/// The decoding policy is intentionally required so wire-format callers make
39/// the canonicality contract explicit.
40/// The underlying unsigned LEB128 payload remains subject to its target
41/// integer's maximum decode width and terminal payload bits, including under
42/// [`NonStrict`]. See that policy's documentation for the width limits.
43///
44/// ```compile_fail
45/// use qubit_codec_binary::ZigZagCodec;
46///
47/// let _ = ZigZagCodec::<i64>::default();
48/// ```
49///
50/// # Examples
51///
52/// ```
53/// use qubit_codec_binary::{
54///     NonStrict,
55///     ZigZagCodec,
56/// };
57///
58/// let mut output = [0_u8; ZigZagCodec::<i64, NonStrict>::MAX_ENCODE_UNITS_PER_VALUE];
59/// let written = unsafe {
60///     ZigZagCodec::<i64, NonStrict>::encode(-42, &mut output, 0)
61/// };
62/// assert_eq!(1, written);
63///
64/// let (decoded, consumed) = unsafe {
65///     ZigZagCodec::<i64, NonStrict>::decode(&output[..written], 0)
66/// }.expect("canonical ZigZag LEB128 value should decode");
67/// assert_eq!(-42, decoded);
68/// assert_eq!(1, consumed.get());
69/// ```
70#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
71pub struct ZigZagCodec<T, P> {
72    /// Associates the value and decode-policy types without storing either.
73    marker: PhantomData<fn() -> (T, P)>,
74}
75
76/// Implements the ZigZag codec for one signed and unsigned integer pair.
77///
78/// The expansion defines the unchecked helpers and the [`Codec`] implementation
79/// while keeping their arithmetic tied to the integer type's bit width.
80macro_rules! impl_zig_zag_codec {
81    ($signed:ty, $unsigned:ty, $shift:expr) => {
82        impl<P> ZigZagCodec<$signed, P>
83        where
84            P: Leb128DecodePolicy,
85        {
86            /// Minimum number of bytes that can represent a complete value.
87            pub const MIN_UNITS_PER_VALUE: usize = <Self as Codec>::MIN_UNITS_PER_VALUE;
88
89            /// Maximum number of bytes emitted when encoding this type.
90            pub const MAX_ENCODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
91
92            /// Maximum number of bytes consumed when decoding this type.
93            pub const MAX_DECODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
94
95            /// Decodes a value from `input` starting at `input_index` without
96            /// bounds checks.
97            ///
98            /// # Parameters
99            ///
100            /// - `input`: Source byte buffer.
101            /// - `input_index`: Start index in `input`.
102            ///
103            /// # Returns
104            ///
105            /// Returns the decoded value and the non-zero number of consumed
106            /// bytes.
107            ///
108            /// # Errors
109            ///
110            /// Returns [`Leb128DecodeError`] if the underlying LEB128 bytes are
111            /// incomplete, malformed, or non-canonical under strict policy.
112            ///
113            /// # Safety
114            ///
115            /// The caller must guarantee that `input_index` is a valid boundary
116            /// and at least [`Self::MIN_UNITS_PER_VALUE`] byte is readable
117            /// from `input_index`.
118            #[inline]
119            pub unsafe fn decode(
120                input: &[u8],
121                input_index: usize,
122            ) -> Result<($signed, core::num::NonZeroUsize), Leb128DecodeError> {
123                debug_assert!(input.len().saturating_sub(input_index) >= Self::MIN_UNITS_PER_VALUE);
124
125                // SAFETY: The caller guarantees enough readable bytes for this
126                // type.
127                let (encoded, consumed) = unsafe { Leb128Codec::<$unsigned, P>::decode(input, input_index)? };
128                let value = ((encoded >> 1) as $signed) ^ (-((encoded & 1) as $signed));
129                Ok((value, consumed))
130            }
131
132            /// Encodes `value` into `output` starting at `output_index` without
133            /// bounds checks.
134            ///
135            /// # Parameters
136            ///
137            /// - `value`: Value to encode.
138            /// - `output`: Destination byte buffer.
139            /// - `output_index`: Start index in `output`.
140            ///
141            /// # Returns
142            ///
143            /// Returns the number of written bytes.
144            ///
145            /// # Safety
146            ///
147            /// The caller must guarantee that the canonical ZigZag LEB128 byte
148            /// width of `value` is writable starting at `output_index`.
149            /// Reserving [`Self::MAX_ENCODE_UNITS_PER_VALUE`] bytes always satisfies
150            /// this requirement; for a known value, the exact
151            /// [`Codec::encode_len`] is sufficient.
152            #[must_use = "the returned byte count determines the encoded payload range"]
153            #[inline]
154            pub unsafe fn encode(value: $signed, output: &mut [u8], output_index: usize) -> usize {
155                let encoded = ((value as $unsigned) << 1) ^ ((value >> $shift) as $unsigned);
156                // SAFETY: The caller guarantees enough writable bytes for the
157                // canonical representation of this value.
158                unsafe { Leb128Codec::<$unsigned, NonStrict>::encode(encoded, output, output_index) }
159            }
160        }
161
162        impl<P> Codec for ZigZagCodec<$signed, P>
163        where
164            P: Leb128DecodePolicy,
165        {
166            type Value = $signed;
167            type Unit = u8;
168            type DecodeError = Leb128DecodeError;
169            type EncodeError = Infallible;
170
171            const MIN_UNITS_PER_VALUE: usize = 1;
172            const MAX_ENCODE_UNITS_PER_VALUE: usize = Leb128Codec::<$unsigned, NonStrict>::MAX_ENCODE_UNITS_PER_VALUE;
173            const MAX_DECODE_UNITS_PER_VALUE: usize = Leb128Codec::<$unsigned, NonStrict>::MAX_DECODE_UNITS_PER_VALUE;
174
175            #[inline]
176            fn encode_len(&self, value: &$signed) -> usize {
177                let encoded = ((*value as $unsigned) << 1) ^ ((*value >> $shift) as $unsigned);
178                uleb_encoded_len(encoded as u128)
179            }
180
181            #[inline]
182            unsafe fn decode(
183                &mut self,
184                input: &[u8],
185                input_index: usize,
186            ) -> Result<($signed, core::num::NonZeroUsize), DecodeFailure<Self::DecodeError>> {
187                debug_assert!(input.len().saturating_sub(input_index) >= Self::MIN_UNITS_PER_VALUE);
188
189                // SAFETY: The caller upholds the `Codec::decode`
190                // contract.
191                unsafe { Self::decode(input, input_index) }.map_err(map_leb128_decode_failure)
192            }
193
194            #[inline]
195            unsafe fn encode(
196                &mut self,
197                value: &$signed,
198                output: &mut [u8],
199                output_index: usize,
200            ) -> Result<usize, Self::EncodeError> {
201                let required = self.encode_len(value);
202                debug_assert!(output.len().saturating_sub(output_index) >= required);
203
204                // SAFETY: The `Codec::encode` contract provides either the
205                // exact canonical width or this type's maximum width.
206                let written = unsafe { Self::encode(*value, output, output_index) };
207                Ok(written)
208            }
209        }
210    };
211}
212
213impl_zig_zag_codec!(i8, u8, 7);
214impl_zig_zag_codec!(i16, u16, 15);
215impl_zig_zag_codec!(i32, u32, 31);
216impl_zig_zag_codec!(i64, u64, 63);
217impl_zig_zag_codec!(i128, u128, 127);
218impl_zig_zag_codec!(isize, usize, isize::BITS - 1);