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