qubit_io_binary/ext/leb128_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 LEB128 values into byte streams.
10
11use std::io::Result;
12
13use qubit_codec_binary::Leb128Codec;
14use qubit_codec_binary::NonStrict;
15use qubit_io::Output;
16
17use crate::util::encode_infallible_unchecked;
18use crate::util::write_all;
19
20macro_rules! write_leb128_value {
21 ($writer:expr, $value:expr, $ty:ty) => {
22 write_leb128::<{ Leb128Codec::<$ty, NonStrict>::MAX_ENCODE_UNITS_PER_VALUE }, _, _, _>(
23 $writer,
24 $value,
25 |bytes, value| {
26 type Codec = Leb128Codec<$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 canonical LEB128 integers to byte streams.
36///
37/// # Target-width integers
38///
39/// `usize` and `isize` methods use the current Rust target's pointer width.
40/// Prefer fixed-width integer methods such as [`Self::write_uleb_u64`] or
41/// [`Self::write_sleb_i64`] for persistent files and cross-platform protocols.
42pub trait Leb128WriteExt: Output<Item = u8> {
43 /// Writes an unsigned LEB128 `u8`.
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_uleb_u8(&mut self, value: u8) -> Result<()> {
59 write_leb128_value!(self, value, u8)
60 }
61
62 /// Writes an unsigned LEB128 `u16`.
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_uleb_u16(&mut self, value: u16) -> Result<()> {
78 write_leb128_value!(self, value, u16)
79 }
80
81 /// Writes an unsigned LEB128 `u32`.
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_uleb_u32(&mut self, value: u32) -> Result<()> {
97 write_leb128_value!(self, value, u32)
98 }
99
100 /// Writes an unsigned LEB128 `u64`.
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_uleb_u64(&mut self, value: u64) -> Result<()> {
116 write_leb128_value!(self, value, u64)
117 }
118
119 /// Writes an unsigned LEB128 `u128`.
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_uleb_u128(&mut self, value: u128) -> Result<()> {
135 write_leb128_value!(self, value, u128)
136 }
137
138 /// Writes an unsigned LEB128 `usize`.
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_uleb_usize(&mut self, value: usize) -> Result<()> {
154 write_leb128_value!(self, value, usize)
155 }
156
157 /// Writes a signed LEB128 `i8`.
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_sleb_i8(&mut self, value: i8) -> Result<()> {
173 write_leb128_value!(self, value, i8)
174 }
175
176 /// Writes a signed LEB128 `i16`.
177 ///
178 /// # Parameters
179 ///
180 /// - `value`: Integer to encode and write.
181 ///
182 /// # Returns
183 ///
184 /// Returns after the canonical payload has been written.
185 ///
186 /// # Errors
187 ///
188 /// Returns an output error, including a write-zero error when the output
189 /// stops making progress.
190 #[inline(always)]
191 fn write_sleb_i16(&mut self, value: i16) -> Result<()> {
192 write_leb128_value!(self, value, i16)
193 }
194
195 /// Writes a signed LEB128 `i32`.
196 ///
197 /// # Parameters
198 ///
199 /// - `value`: Integer to encode and write.
200 ///
201 /// # Returns
202 ///
203 /// Returns after the canonical payload has been written.
204 ///
205 /// # Errors
206 ///
207 /// Returns an output error, including a write-zero error when the output
208 /// stops making progress.
209 #[inline(always)]
210 fn write_sleb_i32(&mut self, value: i32) -> Result<()> {
211 write_leb128_value!(self, value, i32)
212 }
213
214 /// Writes a signed LEB128 `i64`.
215 ///
216 /// # Parameters
217 ///
218 /// - `value`: Integer to encode and write.
219 ///
220 /// # Returns
221 ///
222 /// Returns after the canonical payload has been written.
223 ///
224 /// # Errors
225 ///
226 /// Returns an output error, including a write-zero error when the output
227 /// stops making progress.
228 #[inline(always)]
229 fn write_sleb_i64(&mut self, value: i64) -> Result<()> {
230 write_leb128_value!(self, value, i64)
231 }
232
233 /// Writes a signed LEB128 `i128`.
234 ///
235 /// # Parameters
236 ///
237 /// - `value`: Integer to encode and write.
238 ///
239 /// # Returns
240 ///
241 /// Returns after the canonical payload has been written.
242 ///
243 /// # Errors
244 ///
245 /// Returns an output error, including a write-zero error when the output
246 /// stops making progress.
247 #[inline(always)]
248 fn write_sleb_i128(&mut self, value: i128) -> Result<()> {
249 write_leb128_value!(self, value, i128)
250 }
251
252 /// Writes a signed LEB128 `isize`.
253 ///
254 /// # Parameters
255 ///
256 /// - `value`: Integer to encode and write.
257 ///
258 /// # Returns
259 ///
260 /// Returns after the canonical payload has been written.
261 ///
262 /// # Errors
263 ///
264 /// Returns an output error, including a write-zero error when the output
265 /// stops making progress.
266 #[inline(always)]
267 fn write_sleb_isize(&mut self, value: isize) -> Result<()> {
268 write_leb128_value!(self, value, isize)
269 }
270}
271
272impl<W> Leb128WriteExt for W where W: Output<Item = u8> + ?Sized {}
273
274/// Encodes and writes one canonical LEB128 value.
275///
276/// # Type Parameters
277///
278/// - `N`: Maximum encoded payload length in bytes.
279/// - `T`: Value type accepted by the encoder.
280/// - `W`: Destination byte output.
281/// - `F`: Infallible encoding callback.
282///
283/// # Parameters
284///
285/// - `writer`: Destination for the encoded payload.
286/// - `value`: Value passed to `encode`.
287/// - `encode`: Callback that fills the local buffer and returns its used
288/// length.
289///
290/// # Returns
291///
292/// Returns after the complete payload has been written.
293///
294/// # Errors
295///
296/// Returns an output error, including a write-zero error when the output stops
297/// making progress.
298#[inline]
299fn write_leb128<const N: usize, T, W, F>(writer: &mut W, value: T, encode: F) -> Result<()>
300where
301 W: Output<Item = u8> + ?Sized,
302 F: FnOnce(&mut [u8], T) -> usize,
303{
304 let mut bytes = [0u8; N];
305 let len = encode(&mut bytes, value);
306 write_all(writer, &bytes[..len])
307}