Skip to main content

qubit_io_binary/ext/
zig_zag_write_ext.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
9//! Extension methods for encoding ZigZag-encoded integers into streams.
10
11use std::io::Result;
12
13use qubit_codec_binary::NonStrict;
14use qubit_codec_binary::ZigZagCodec;
15use qubit_io::ByteOutput;
16
17use crate::util::encode_infallible_unchecked;
18use crate::util::write_all;
19
20macro_rules! write_zig_zag_value {
21    ($writer:expr, $value:expr, $ty:ty) => {
22        write_zig_zag::<{ ZigZagCodec::<$ty, NonStrict>::MAX_ENCODE_UNITS_PER_VALUE }, _, _, _>(
23            $writer,
24            $value,
25            |bytes, value| {
26                type Codec = ZigZagCodec<$ty, NonStrict>;
27                // SAFETY: The local buffer is exactly the codec's maximum buffer
28                // length.
29                unsafe { encode_infallible_unchecked::<Codec>(value, bytes, 0) }
30            },
31        )
32    };
33}
34
35/// Extension methods for writing ZigZag + unsigned LEB128 integers.
36///
37/// # Target-width integers
38///
39/// `isize` methods use the current Rust target's pointer width. Prefer
40/// fixed-width integer methods such as [`Self::write_zig_zag_i64`] for
41/// persistent files and cross-platform protocols.
42///
43/// # Partial writes
44///
45/// These methods are not transactional. An output error may occur after the
46/// output has accepted a byte prefix of the encoded value, and those bytes are
47/// not rolled back. Calling a method again encodes the entire value from the
48/// output's current position and may duplicate that prefix. Recovery requires
49/// outer framing, a trusted seek or rollback strategy, or a transactional
50/// transport. Output acceptance does not imply durable persistence.
51///
52/// # Examples
53///
54/// ```
55/// use qubit_io_binary::ZigZagWriteExt;
56///
57/// let mut bytes = Vec::new();
58/// bytes.write_zig_zag_i32(-300).expect("value should be written");
59/// assert_eq!(bytes, [0xD7, 0x04]);
60/// ```
61pub trait ZigZagWriteExt: ByteOutput {
62    /// Writes a ZigZag `i8`.
63    ///
64    /// # Parameters
65    ///
66    /// - `value`: Integer to encode and write.
67    ///
68    /// # Returns
69    ///
70    /// Returns after the canonical payload has been written.
71    ///
72    /// # Errors
73    ///
74    /// Returns an output error, including a write-zero error when the output
75    /// stops making progress.
76    #[inline(always)]
77    fn write_zig_zag_i8(&mut self, value: i8) -> Result<()> {
78        write_zig_zag_value!(self, value, i8)
79    }
80
81    /// Writes a ZigZag `i16`.
82    ///
83    /// # Parameters
84    ///
85    /// - `value`: Integer to encode and write.
86    ///
87    /// # Returns
88    ///
89    /// Returns after the canonical payload has been written.
90    ///
91    /// # Errors
92    ///
93    /// Returns an output error, including a write-zero error when the output
94    /// stops making progress.
95    #[inline(always)]
96    fn write_zig_zag_i16(&mut self, value: i16) -> Result<()> {
97        write_zig_zag_value!(self, value, i16)
98    }
99
100    /// Writes a ZigZag `i32`.
101    ///
102    /// # Parameters
103    ///
104    /// - `value`: Integer to encode and write.
105    ///
106    /// # Returns
107    ///
108    /// Returns after the canonical payload has been written.
109    ///
110    /// # Errors
111    ///
112    /// Returns an output error, including a write-zero error when the output
113    /// stops making progress.
114    #[inline(always)]
115    fn write_zig_zag_i32(&mut self, value: i32) -> Result<()> {
116        write_zig_zag_value!(self, value, i32)
117    }
118
119    /// Writes a ZigZag `i64`.
120    ///
121    /// # Parameters
122    ///
123    /// - `value`: Integer to encode and write.
124    ///
125    /// # Returns
126    ///
127    /// Returns after the canonical payload has been written.
128    ///
129    /// # Errors
130    ///
131    /// Returns an output error, including a write-zero error when the output
132    /// stops making progress.
133    #[inline(always)]
134    fn write_zig_zag_i64(&mut self, value: i64) -> Result<()> {
135        write_zig_zag_value!(self, value, i64)
136    }
137
138    /// Writes a ZigZag `i128`.
139    ///
140    /// # Parameters
141    ///
142    /// - `value`: Integer to encode and write.
143    ///
144    /// # Returns
145    ///
146    /// Returns after the canonical payload has been written.
147    ///
148    /// # Errors
149    ///
150    /// Returns an output error, including a write-zero error when the output
151    /// stops making progress.
152    #[inline(always)]
153    fn write_zig_zag_i128(&mut self, value: i128) -> Result<()> {
154        write_zig_zag_value!(self, value, i128)
155    }
156
157    /// Writes a ZigZag `isize`.
158    ///
159    /// # Parameters
160    ///
161    /// - `value`: Integer to encode and write.
162    ///
163    /// # Returns
164    ///
165    /// Returns after the canonical payload has been written.
166    ///
167    /// # Errors
168    ///
169    /// Returns an output error, including a write-zero error when the output
170    /// stops making progress.
171    #[inline(always)]
172    fn write_zig_zag_isize(&mut self, value: isize) -> Result<()> {
173        write_zig_zag_value!(self, value, isize)
174    }
175}
176
177impl<W> ZigZagWriteExt for W where W: ByteOutput + ?Sized {}
178
179/// Encodes and writes one canonical ZigZag value.
180///
181/// # Type Parameters
182///
183/// - `N`: Maximum encoded payload length in bytes.
184/// - `T`: Value type accepted by the encoder.
185/// - `W`: Destination byte output.
186/// - `F`: Infallible encoding callback.
187///
188/// # Parameters
189///
190/// - `writer`: Destination for the encoded payload.
191/// - `value`: Value passed to `encode`.
192/// - `encode`: Callback that fills the local buffer and returns its used
193///   length.
194///
195/// # Returns
196///
197/// Returns after the complete payload has been written.
198///
199/// # Errors
200///
201/// Returns an output error, including a write-zero error when the output stops
202/// making progress.
203#[inline]
204fn write_zig_zag<const N: usize, T, W, F>(writer: &mut W, value: T, encode: F) -> Result<()>
205where
206    W: ByteOutput + ?Sized,
207    F: FnOnce(&mut [u8], T) -> usize,
208{
209    let mut bytes = [0u8; N];
210    let len = encode(&mut bytes, value);
211    write_all(writer, &bytes[..len])
212}