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///
41/// ```compile_fail
42/// use qubit_codec_binary::ZigZagCodec;
43///
44/// let _ = ZigZagCodec::<i64>::default();
45/// ```
46///
47/// # Examples
48///
49/// ```
50/// use qubit_codec_binary::{
51///     NonStrict,
52///     ZigZagCodec,
53/// };
54///
55/// let mut output = [0_u8; ZigZagCodec::<i64, NonStrict>::MAX_ENCODE_UNITS_PER_VALUE];
56/// let written = unsafe {
57///     ZigZagCodec::<i64, NonStrict>::encode(-42, &mut output, 0)
58/// };
59/// assert_eq!(1, written);
60///
61/// let (decoded, consumed) = unsafe {
62///     ZigZagCodec::<i64, NonStrict>::decode(&output[..written], 0)
63/// }.expect("canonical ZigZag LEB128 value should decode");
64/// assert_eq!(-42, decoded);
65/// assert_eq!(1, consumed.get());
66/// ```
67#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
68pub struct ZigZagCodec<T, P> {
69    /// Associates the value and decode-policy types without storing either.
70    marker: PhantomData<fn() -> (T, P)>,
71}
72
73macro_rules! impl_zig_zag_codec {
74    ($signed:ty, $unsigned:ty, $shift:expr) => {
75        impl<P> ZigZagCodec<$signed, P>
76        where
77            P: Leb128DecodePolicy,
78        {
79            /// Minimum number of bytes that can represent a complete value.
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 = <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
84
85            /// Maximum number of bytes consumed when decoding this type.
86            pub const MAX_DECODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_DECODE_UNITS_PER_VALUE;
87
88            /// Decodes a value from `input` starting at `input_index` without
89            /// bounds checks.
90            ///
91            /// # Parameters
92            ///
93            /// - `input`: Source byte buffer.
94            /// - `input_index`: Start index in `input`.
95            ///
96            /// # Returns
97            ///
98            /// Returns the decoded value and the non-zero number of consumed
99            /// bytes.
100            ///
101            /// # Errors
102            ///
103            /// Returns [`Leb128DecodeError`] if the underlying LEB128 bytes are
104            /// incomplete, malformed, or non-canonical under strict policy.
105            ///
106            /// # Safety
107            ///
108            /// The caller must guarantee that `input_index` is a valid boundary
109            /// and at least [`Self::MIN_UNITS_PER_VALUE`] byte is readable
110            /// from `input_index`.
111            #[inline(always)]
112            pub unsafe fn decode(
113                input: &[u8],
114                input_index: usize,
115            ) -> Result<($signed, core::num::NonZeroUsize), Leb128DecodeError> {
116                debug_assert!(input.len().saturating_sub(input_index) >= Self::MIN_UNITS_PER_VALUE);
117
118                // SAFETY: The caller guarantees enough readable bytes for this
119                // type.
120                let (encoded, consumed) = unsafe { Leb128Codec::<$unsigned, P>::decode(input, input_index)? };
121                let value = ((encoded >> 1) as $signed) ^ (-((encoded & 1) as $signed));
122                Ok((value, consumed))
123            }
124
125            /// Encodes `value` into `output` starting at `output_index` without
126            /// bounds checks.
127            ///
128            /// # Parameters
129            ///
130            /// - `value`: Value to encode.
131            /// - `output`: Destination byte buffer.
132            /// - `output_index`: Start index in `output`.
133            ///
134            /// # Returns
135            ///
136            /// Returns the number of written bytes.
137            ///
138            /// # Safety
139            ///
140            /// The caller must guarantee that the canonical ZigZag LEB128 byte
141            /// width of `value` is writable starting at `output_index`.
142            /// Reserving [`Self::MAX_ENCODE_UNITS_PER_VALUE`] bytes always satisfies
143            /// this requirement; for a known value, the exact
144            /// [`Codec::encode_len`] is sufficient.
145            #[must_use = "the returned byte count determines the encoded payload range"]
146            #[inline(always)]
147            pub unsafe fn encode(value: $signed, output: &mut [u8], output_index: usize) -> usize {
148                let encoded = ((value as $unsigned) << 1) ^ ((value >> $shift) as $unsigned);
149                // SAFETY: The caller guarantees enough writable bytes for the
150                // canonical representation of this value.
151                unsafe { Leb128Codec::<$unsigned, NonStrict>::encode(encoded, output, output_index) }
152            }
153        }
154
155        impl<P> Codec for ZigZagCodec<$signed, P>
156        where
157            P: Leb128DecodePolicy,
158        {
159            type Value = $signed;
160            type Unit = u8;
161            type DecodeError = Leb128DecodeError;
162            type EncodeError = Infallible;
163
164            const MIN_UNITS_PER_VALUE: usize = 1;
165            const MAX_ENCODE_UNITS_PER_VALUE: usize = Leb128Codec::<$unsigned, NonStrict>::MAX_ENCODE_UNITS_PER_VALUE;
166            const MAX_DECODE_UNITS_PER_VALUE: usize = Leb128Codec::<$unsigned, NonStrict>::MAX_DECODE_UNITS_PER_VALUE;
167
168            #[inline(always)]
169            fn encode_len(&self, value: &$signed) -> usize {
170                let encoded = ((*value as $unsigned) << 1) ^ ((*value >> $shift) as $unsigned);
171                uleb_encoded_len(encoded as u128)
172            }
173
174            #[inline(always)]
175            unsafe fn decode(
176                &mut self,
177                input: &[u8],
178                input_index: usize,
179            ) -> Result<($signed, core::num::NonZeroUsize), DecodeFailure<Self::DecodeError>> {
180                debug_assert!(input.len().saturating_sub(input_index) >= Self::MIN_UNITS_PER_VALUE);
181
182                // SAFETY: The caller upholds the `Codec::decode`
183                // contract.
184                unsafe { Self::decode(input, input_index) }.map_err(map_leb128_decode_failure)
185            }
186
187            #[inline(always)]
188            unsafe fn encode(
189                &mut self,
190                value: &$signed,
191                output: &mut [u8],
192                output_index: usize,
193            ) -> Result<usize, Self::EncodeError> {
194                let required = self.encode_len(value);
195                debug_assert!(output.len().saturating_sub(output_index) >= required);
196
197                // SAFETY: The `Codec::encode` contract provides either the
198                // exact canonical width or this type's maximum width.
199                let written = unsafe { Self::encode(*value, output, output_index) };
200                Ok(written)
201            }
202        }
203    };
204}
205
206impl_zig_zag_codec!(i8, u8, 7);
207impl_zig_zag_codec!(i16, u16, 15);
208impl_zig_zag_codec!(i32, u32, 31);
209impl_zig_zag_codec!(i64, u64, 63);
210impl_zig_zag_codec!(i128, u128, 127);
211impl_zig_zag_codec!(isize, usize, isize::BITS - 1);