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
20/// Encodes a signed integer into a stack buffer and writes its ZigZag payload.
21macro_rules! write_zig_zag_value {
22 ($writer:expr, $value:expr, $ty:ty) => {
23 write_zig_zag::<{ ZigZagCodec::<$ty, NonStrict>::MAX_ENCODE_UNITS_PER_VALUE }, _, _, _>(
24 $writer,
25 $value,
26 |bytes, value| {
27 type Codec = ZigZagCodec<$ty, NonStrict>;
28 // SAFETY: The local buffer is exactly the codec's maximum buffer
29 // length.
30 unsafe { encode_infallible_unchecked::<Codec>(value, bytes, 0) }
31 },
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.
43///
44/// # Partial writes
45///
46/// These methods are not transactional. An output error may occur after the
47/// output has accepted a byte prefix of the encoded value, and those bytes are
48/// not rolled back. Calling a method again encodes the entire value from the
49/// output's current position and may duplicate that prefix. Recovery requires
50/// outer framing, a trusted seek or rollback strategy, or a transactional
51/// transport. Output acceptance does not imply durable persistence.
52///
53/// # Examples
54///
55/// ```
56/// use qubit_io_binary::ZigZagWriteExt;
57///
58/// let mut bytes = Vec::new();
59/// bytes.write_zig_zag_i32(-300).expect("value should be written");
60/// assert_eq!(bytes, [0xD7, 0x04]);
61/// ```
62pub trait ZigZagWriteExt: ByteOutput {
63 /// Writes a ZigZag `i8`.
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_i8(&mut self, value: i8) -> Result<()> {
79 write_zig_zag_value!(self, value, i8)
80 }
81
82 /// Writes a ZigZag `i16`.
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_i16(&mut self, value: i16) -> Result<()> {
98 write_zig_zag_value!(self, value, i16)
99 }
100
101 /// Writes a ZigZag `i32`.
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_i32(&mut self, value: i32) -> Result<()> {
117 write_zig_zag_value!(self, value, i32)
118 }
119
120 /// Writes a ZigZag `i64`.
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_i64(&mut self, value: i64) -> Result<()> {
136 write_zig_zag_value!(self, value, i64)
137 }
138
139 /// Writes a ZigZag `i128`.
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_i128(&mut self, value: i128) -> Result<()> {
155 write_zig_zag_value!(self, value, i128)
156 }
157
158 /// Writes a ZigZag `isize`.
159 ///
160 /// # Parameters
161 ///
162 /// - `value`: Integer to encode and write.
163 ///
164 /// # Returns
165 ///
166 /// Returns after the canonical payload has been written.
167 ///
168 /// # Errors
169 ///
170 /// Returns an output error, including a write-zero error when the output
171 /// stops making progress.
172 #[inline(always)]
173 fn write_zig_zag_isize(&mut self, value: isize) -> Result<()> {
174 write_zig_zag_value!(self, value, isize)
175 }
176}
177
178impl<W> ZigZagWriteExt for W where W: ByteOutput + ?Sized {}
179
180/// Encodes and writes one canonical ZigZag value.
181///
182/// # Type Parameters
183///
184/// - `N`: Maximum encoded payload length in bytes.
185/// - `T`: Value type accepted by the encoder.
186/// - `W`: Destination byte output.
187/// - `F`: Infallible encoding callback.
188///
189/// # Parameters
190///
191/// - `writer`: Destination for the encoded payload.
192/// - `value`: Value passed to `encode`.
193/// - `encode`: Callback that fills the local buffer and returns its used
194/// length.
195///
196/// # Returns
197///
198/// Returns after the complete payload has been written.
199///
200/// # Errors
201///
202/// Returns an output error, including a write-zero error when the output stops
203/// making progress.
204#[inline]
205fn write_zig_zag<const N: usize, T, W, F>(writer: &mut W, value: T, encode: F) -> Result<()>
206where
207 W: ByteOutput + ?Sized,
208 F: FnOnce(&mut [u8], T) -> usize,
209{
210 let mut bytes = [0u8; N];
211 let len = encode(&mut bytes, value);
212 write_all(writer, &bytes[..len])
213}