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::Output;
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::<
23            { ZigZagCodec::<$ty, NonStrict>::MAX_ENCODE_UNITS_PER_VALUE },
24            _,
25            _,
26            _,
27        >($writer, $value, |bytes, value| {
28            type Codec = ZigZagCodec<$ty, NonStrict>;
29            // SAFETY: The local buffer is exactly the codec's maximum buffer
30            // length.
31            unsafe { encode_infallible_unchecked::<Codec>(value, bytes, 0) }
32        })
33    };
34}
35
36/// Extension methods for writing ZigZag + unsigned LEB128 integers.
37///
38/// # Target-width integers
39///
40/// `isize` methods use the current Rust target's pointer width. Prefer
41/// fixed-width integer methods such as [`Self::write_zig_zag_i64`] for
42/// persistent files and cross-platform protocols.
43pub trait ZigZagWriteExt: Output<Item = u8> {
44    /// Writes a ZigZag `i8`.
45    ///
46    /// # Parameters
47    ///
48    /// - `value`: Integer to encode and write.
49    ///
50    /// # Returns
51    ///
52    /// Returns after the canonical payload has been written.
53    ///
54    /// # Errors
55    ///
56    /// Returns an output error, including a write-zero error when the output
57    /// stops making progress.
58    #[inline(always)]
59    fn write_zig_zag_i8(&mut self, value: i8) -> Result<()> {
60        write_zig_zag_value!(self, value, i8)
61    }
62
63    /// Writes a ZigZag `i16`.
64    ///
65    /// # Parameters
66    ///
67    /// - `value`: Integer to encode and write.
68    ///
69    /// # Returns
70    ///
71    /// Returns after the canonical payload has been written.
72    ///
73    /// # Errors
74    ///
75    /// Returns an output error, including a write-zero error when the output
76    /// stops making progress.
77    #[inline(always)]
78    fn write_zig_zag_i16(&mut self, value: i16) -> Result<()> {
79        write_zig_zag_value!(self, value, i16)
80    }
81
82    /// Writes a ZigZag `i32`.
83    ///
84    /// # Parameters
85    ///
86    /// - `value`: Integer to encode and write.
87    ///
88    /// # Returns
89    ///
90    /// Returns after the canonical payload has been written.
91    ///
92    /// # Errors
93    ///
94    /// Returns an output error, including a write-zero error when the output
95    /// stops making progress.
96    #[inline(always)]
97    fn write_zig_zag_i32(&mut self, value: i32) -> Result<()> {
98        write_zig_zag_value!(self, value, i32)
99    }
100
101    /// Writes a ZigZag `i64`.
102    ///
103    /// # Parameters
104    ///
105    /// - `value`: Integer to encode and write.
106    ///
107    /// # Returns
108    ///
109    /// Returns after the canonical payload has been written.
110    ///
111    /// # Errors
112    ///
113    /// Returns an output error, including a write-zero error when the output
114    /// stops making progress.
115    #[inline(always)]
116    fn write_zig_zag_i64(&mut self, value: i64) -> Result<()> {
117        write_zig_zag_value!(self, value, i64)
118    }
119
120    /// Writes a ZigZag `i128`.
121    ///
122    /// # Parameters
123    ///
124    /// - `value`: Integer to encode and write.
125    ///
126    /// # Returns
127    ///
128    /// Returns after the canonical payload has been written.
129    ///
130    /// # Errors
131    ///
132    /// Returns an output error, including a write-zero error when the output
133    /// stops making progress.
134    #[inline(always)]
135    fn write_zig_zag_i128(&mut self, value: i128) -> Result<()> {
136        write_zig_zag_value!(self, value, i128)
137    }
138
139    /// Writes a ZigZag `isize`.
140    ///
141    /// # Parameters
142    ///
143    /// - `value`: Integer to encode and write.
144    ///
145    /// # Returns
146    ///
147    /// Returns after the canonical payload has been written.
148    ///
149    /// # Errors
150    ///
151    /// Returns an output error, including a write-zero error when the output
152    /// stops making progress.
153    #[inline(always)]
154    fn write_zig_zag_isize(&mut self, value: isize) -> Result<()> {
155        write_zig_zag_value!(self, value, isize)
156    }
157}
158
159impl<W> ZigZagWriteExt for W where W: Output<Item = u8> + ?Sized {}
160
161/// Encodes and writes one canonical ZigZag value.
162///
163/// # Type Parameters
164///
165/// - `N`: Maximum encoded payload length in bytes.
166/// - `T`: Value type accepted by the encoder.
167/// - `W`: Destination byte output.
168/// - `F`: Infallible encoding callback.
169///
170/// # Parameters
171///
172/// - `writer`: Destination for the encoded payload.
173/// - `value`: Value passed to `encode`.
174/// - `encode`: Callback that fills the local buffer and returns its used
175///   length.
176///
177/// # Returns
178///
179/// Returns after the complete payload has been written.
180///
181/// # Errors
182///
183/// Returns an output error, including a write-zero error when the output stops
184/// making progress.
185#[inline]
186fn write_zig_zag<const N: usize, T, W, F>(
187    writer: &mut W,
188    value: T,
189    encode: F,
190) -> Result<()>
191where
192    W: Output<Item = u8> + ?Sized,
193    F: FnOnce(&mut [u8], T) -> usize,
194{
195    let mut bytes = [0u8; N];
196    let len = encode(&mut bytes, value);
197    write_all(writer, &bytes[..len])
198}