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
73/// Implements the ZigZag codec for one signed and unsigned integer pair.
74///
75/// The expansion defines the unchecked helpers and the [`Codec`] implementation
76/// while keeping their arithmetic tied to the integer type's bit width.
77macro_rules! impl_zig_zag_codec {
78 ($signed:ty, $unsigned:ty, $shift:expr) => {
79 impl<P> ZigZagCodec<$signed, P>
80 where
81 P: Leb128DecodePolicy,
82 {
83 /// Minimum number of bytes that can represent a complete value.
84 pub const MIN_UNITS_PER_VALUE: usize = <Self as Codec>::MIN_UNITS_PER_VALUE;
85
86 /// Maximum number of bytes emitted when encoding this type.
87 pub const MAX_ENCODE_UNITS_PER_VALUE: usize = <Self as Codec>::MAX_ENCODE_UNITS_PER_VALUE;
88
89 /// Maximum number of bytes consumed when decoding this type.
90 pub const MAX_DECODE_UNITS_PER_VALUE: usize = <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]
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) = unsafe { Leb128Codec::<$unsigned, P>::decode(input, input_index)? };
125 let value = ((encoded >> 1) as $signed) ^ (-((encoded & 1) as $signed));
126 Ok((value, consumed))
127 }
128
129 /// Encodes `value` into `output` starting at `output_index` without
130 /// bounds checks.
131 ///
132 /// # Parameters
133 ///
134 /// - `value`: Value to encode.
135 /// - `output`: Destination byte buffer.
136 /// - `output_index`: Start index in `output`.
137 ///
138 /// # Returns
139 ///
140 /// Returns the number of written bytes.
141 ///
142 /// # Safety
143 ///
144 /// The caller must guarantee that the canonical ZigZag LEB128 byte
145 /// width of `value` is writable starting at `output_index`.
146 /// Reserving [`Self::MAX_ENCODE_UNITS_PER_VALUE`] bytes always satisfies
147 /// this requirement; for a known value, the exact
148 /// [`Codec::encode_len`] is sufficient.
149 #[must_use = "the returned byte count determines the encoded payload range"]
150 #[inline]
151 pub unsafe fn encode(value: $signed, output: &mut [u8], output_index: usize) -> usize {
152 let encoded = ((value as $unsigned) << 1) ^ ((value >> $shift) as $unsigned);
153 // SAFETY: The caller guarantees enough writable bytes for the
154 // canonical representation of this value.
155 unsafe { Leb128Codec::<$unsigned, NonStrict>::encode(encoded, output, output_index) }
156 }
157 }
158
159 impl<P> Codec for ZigZagCodec<$signed, P>
160 where
161 P: Leb128DecodePolicy,
162 {
163 type Value = $signed;
164 type Unit = u8;
165 type DecodeError = Leb128DecodeError;
166 type EncodeError = Infallible;
167
168 const MIN_UNITS_PER_VALUE: usize = 1;
169 const MAX_ENCODE_UNITS_PER_VALUE: usize = Leb128Codec::<$unsigned, NonStrict>::MAX_ENCODE_UNITS_PER_VALUE;
170 const MAX_DECODE_UNITS_PER_VALUE: usize = Leb128Codec::<$unsigned, NonStrict>::MAX_DECODE_UNITS_PER_VALUE;
171
172 #[inline]
173 fn encode_len(&self, value: &$signed) -> usize {
174 let encoded = ((*value as $unsigned) << 1) ^ ((*value >> $shift) as $unsigned);
175 uleb_encoded_len(encoded as u128)
176 }
177
178 #[inline]
179 unsafe fn decode(
180 &mut self,
181 input: &[u8],
182 input_index: usize,
183 ) -> Result<($signed, core::num::NonZeroUsize), DecodeFailure<Self::DecodeError>> {
184 debug_assert!(input.len().saturating_sub(input_index) >= Self::MIN_UNITS_PER_VALUE);
185
186 // SAFETY: The caller upholds the `Codec::decode`
187 // contract.
188 unsafe { Self::decode(input, input_index) }.map_err(map_leb128_decode_failure)
189 }
190
191 #[inline]
192 unsafe fn encode(
193 &mut self,
194 value: &$signed,
195 output: &mut [u8],
196 output_index: usize,
197 ) -> Result<usize, Self::EncodeError> {
198 let required = self.encode_len(value);
199 debug_assert!(output.len().saturating_sub(output_index) >= required);
200
201 // SAFETY: The `Codec::encode` contract provides either the
202 // exact canonical width or this type's maximum width.
203 let written = unsafe { Self::encode(*value, output, output_index) };
204 Ok(written)
205 }
206 }
207 };
208}
209
210impl_zig_zag_codec!(i8, u8, 7);
211impl_zig_zag_codec!(i16, u16, 15);
212impl_zig_zag_codec!(i32, u32, 31);
213impl_zig_zag_codec!(i64, u64, 63);
214impl_zig_zag_codec!(i128, u128, 127);
215impl_zig_zag_codec!(isize, usize, isize::BITS - 1);