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