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::<{ 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.
42pub trait ZigZagWriteExt: Output<Item = u8> {
43    /// Writes a ZigZag `i8`.
44    ///
45    /// # Parameters
46    ///
47    /// - `value`: Integer to encode and write.
48    ///
49    /// # Returns
50    ///
51    /// Returns after the canonical payload has been written.
52    ///
53    /// # Errors
54    ///
55    /// Returns an output error, including a write-zero error when the output
56    /// stops making progress.
57    #[inline(always)]
58    fn write_zig_zag_i8(&mut self, value: i8) -> Result<()> {
59        write_zig_zag_value!(self, value, i8)
60    }
61
62    /// Writes a ZigZag `i16`.
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_i16(&mut self, value: i16) -> Result<()> {
78        write_zig_zag_value!(self, value, i16)
79    }
80
81    /// Writes a ZigZag `i32`.
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_i32(&mut self, value: i32) -> Result<()> {
97        write_zig_zag_value!(self, value, i32)
98    }
99
100    /// Writes a ZigZag `i64`.
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_i64(&mut self, value: i64) -> Result<()> {
116        write_zig_zag_value!(self, value, i64)
117    }
118
119    /// Writes a ZigZag `i128`.
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_i128(&mut self, value: i128) -> Result<()> {
135        write_zig_zag_value!(self, value, i128)
136    }
137
138    /// Writes a ZigZag `isize`.
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_isize(&mut self, value: isize) -> Result<()> {
154        write_zig_zag_value!(self, value, isize)
155    }
156}
157
158impl<W> ZigZagWriteExt for W where W: Output<Item = u8> + ?Sized {}
159
160/// Encodes and writes one canonical ZigZag value.
161///
162/// # Type Parameters
163///
164/// - `N`: Maximum encoded payload length in bytes.
165/// - `T`: Value type accepted by the encoder.
166/// - `W`: Destination byte output.
167/// - `F`: Infallible encoding callback.
168///
169/// # Parameters
170///
171/// - `writer`: Destination for the encoded payload.
172/// - `value`: Value passed to `encode`.
173/// - `encode`: Callback that fills the local buffer and returns its used
174///   length.
175///
176/// # Returns
177///
178/// Returns after the complete payload has been written.
179///
180/// # Errors
181///
182/// Returns an output error, including a write-zero error when the output stops
183/// making progress.
184#[inline]
185fn write_zig_zag<const N: usize, T, W, F>(writer: &mut W, value: T, encode: F) -> Result<()>
186where
187    W: Output<Item = u8> + ?Sized,
188    F: FnOnce(&mut [u8], T) -> usize,
189{
190    let mut bytes = [0u8; N];
191    let len = encode(&mut bytes, value);
192    write_all(writer, &bytes[..len])
193}