Skip to main content

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::ByteOutput;
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.
42///
43/// # Partial writes
44///
45/// These methods are not transactional. An output error may occur after the
46/// output has accepted a byte prefix of the encoded value, and those bytes are
47/// not rolled back. Calling a method again encodes the entire value from the
48/// output's current position and may duplicate that prefix. Recovery requires
49/// outer framing, a trusted seek or rollback strategy, or a transactional
50/// transport. Output acceptance does not imply durable persistence.
51///
52/// # Examples
53///
54/// Write a canonical unsigned LEB128 value:
55///
56/// ```
57/// use qubit_io_binary::Leb128WriteExt;
58///
59/// let mut bytes = Vec::new();
60/// bytes.write_uleb_u64(300)?;
61/// assert_eq!(bytes, [0xac, 0x02]);
62/// # Ok::<(), std::io::Error>(())
63/// ```
64pub trait Leb128WriteExt: ByteOutput {
65    /// Writes an unsigned LEB128 `u8`.
66    ///
67    /// # Parameters
68    ///
69    /// - `value`: Integer to encode and write.
70    ///
71    /// # Returns
72    ///
73    /// Returns after the canonical payload has been written.
74    ///
75    /// # Errors
76    ///
77    /// Returns an output error, including a write-zero error when the output
78    /// stops making progress.
79    #[inline(always)]
80    fn write_uleb_u8(&mut self, value: u8) -> Result<()> {
81        write_leb128_value!(self, value, u8)
82    }
83
84    /// Writes an unsigned LEB128 `u16`.
85    ///
86    /// # Parameters
87    ///
88    /// - `value`: Integer to encode and write.
89    ///
90    /// # Returns
91    ///
92    /// Returns after the canonical payload has been written.
93    ///
94    /// # Errors
95    ///
96    /// Returns an output error, including a write-zero error when the output
97    /// stops making progress.
98    #[inline(always)]
99    fn write_uleb_u16(&mut self, value: u16) -> Result<()> {
100        write_leb128_value!(self, value, u16)
101    }
102
103    /// Writes an unsigned LEB128 `u32`.
104    ///
105    /// # Parameters
106    ///
107    /// - `value`: Integer to encode and write.
108    ///
109    /// # Returns
110    ///
111    /// Returns after the canonical payload has been written.
112    ///
113    /// # Errors
114    ///
115    /// Returns an output error, including a write-zero error when the output
116    /// stops making progress.
117    #[inline(always)]
118    fn write_uleb_u32(&mut self, value: u32) -> Result<()> {
119        write_leb128_value!(self, value, u32)
120    }
121
122    /// Writes an unsigned LEB128 `u64`.
123    ///
124    /// # Parameters
125    ///
126    /// - `value`: Integer to encode and write.
127    ///
128    /// # Returns
129    ///
130    /// Returns after the canonical payload has been written.
131    ///
132    /// # Errors
133    ///
134    /// Returns an output error, including a write-zero error when the output
135    /// stops making progress.
136    #[inline(always)]
137    fn write_uleb_u64(&mut self, value: u64) -> Result<()> {
138        write_leb128_value!(self, value, u64)
139    }
140
141    /// Writes an unsigned LEB128 `u128`.
142    ///
143    /// # Parameters
144    ///
145    /// - `value`: Integer to encode and write.
146    ///
147    /// # Returns
148    ///
149    /// Returns after the canonical payload has been written.
150    ///
151    /// # Errors
152    ///
153    /// Returns an output error, including a write-zero error when the output
154    /// stops making progress.
155    #[inline(always)]
156    fn write_uleb_u128(&mut self, value: u128) -> Result<()> {
157        write_leb128_value!(self, value, u128)
158    }
159
160    /// Writes an unsigned LEB128 `usize`.
161    ///
162    /// # Parameters
163    ///
164    /// - `value`: Integer to encode and write.
165    ///
166    /// # Returns
167    ///
168    /// Returns after the canonical payload has been written.
169    ///
170    /// # Errors
171    ///
172    /// Returns an output error, including a write-zero error when the output
173    /// stops making progress.
174    #[inline(always)]
175    fn write_uleb_usize(&mut self, value: usize) -> Result<()> {
176        write_leb128_value!(self, value, usize)
177    }
178
179    /// Writes a signed LEB128 `i8`.
180    ///
181    /// # Parameters
182    ///
183    /// - `value`: Integer to encode and write.
184    ///
185    /// # Returns
186    ///
187    /// Returns after the canonical payload has been written.
188    ///
189    /// # Errors
190    ///
191    /// Returns an output error, including a write-zero error when the output
192    /// stops making progress.
193    #[inline(always)]
194    fn write_sleb_i8(&mut self, value: i8) -> Result<()> {
195        write_leb128_value!(self, value, i8)
196    }
197
198    /// Writes a signed LEB128 `i16`.
199    ///
200    /// # Parameters
201    ///
202    /// - `value`: Integer to encode and write.
203    ///
204    /// # Returns
205    ///
206    /// Returns after the canonical payload has been written.
207    ///
208    /// # Errors
209    ///
210    /// Returns an output error, including a write-zero error when the output
211    /// stops making progress.
212    #[inline(always)]
213    fn write_sleb_i16(&mut self, value: i16) -> Result<()> {
214        write_leb128_value!(self, value, i16)
215    }
216
217    /// Writes a signed LEB128 `i32`.
218    ///
219    /// # Parameters
220    ///
221    /// - `value`: Integer to encode and write.
222    ///
223    /// # Returns
224    ///
225    /// Returns after the canonical payload has been written.
226    ///
227    /// # Errors
228    ///
229    /// Returns an output error, including a write-zero error when the output
230    /// stops making progress.
231    #[inline(always)]
232    fn write_sleb_i32(&mut self, value: i32) -> Result<()> {
233        write_leb128_value!(self, value, i32)
234    }
235
236    /// Writes a signed LEB128 `i64`.
237    ///
238    /// # Parameters
239    ///
240    /// - `value`: Integer to encode and write.
241    ///
242    /// # Returns
243    ///
244    /// Returns after the canonical payload has been written.
245    ///
246    /// # Errors
247    ///
248    /// Returns an output error, including a write-zero error when the output
249    /// stops making progress.
250    #[inline(always)]
251    fn write_sleb_i64(&mut self, value: i64) -> Result<()> {
252        write_leb128_value!(self, value, i64)
253    }
254
255    /// Writes a signed LEB128 `i128`.
256    ///
257    /// # Parameters
258    ///
259    /// - `value`: Integer to encode and write.
260    ///
261    /// # Returns
262    ///
263    /// Returns after the canonical payload has been written.
264    ///
265    /// # Errors
266    ///
267    /// Returns an output error, including a write-zero error when the output
268    /// stops making progress.
269    #[inline(always)]
270    fn write_sleb_i128(&mut self, value: i128) -> Result<()> {
271        write_leb128_value!(self, value, i128)
272    }
273
274    /// Writes a signed LEB128 `isize`.
275    ///
276    /// # Parameters
277    ///
278    /// - `value`: Integer to encode and write.
279    ///
280    /// # Returns
281    ///
282    /// Returns after the canonical payload has been written.
283    ///
284    /// # Errors
285    ///
286    /// Returns an output error, including a write-zero error when the output
287    /// stops making progress.
288    #[inline(always)]
289    fn write_sleb_isize(&mut self, value: isize) -> Result<()> {
290        write_leb128_value!(self, value, isize)
291    }
292}
293
294impl<W> Leb128WriteExt for W where W: ByteOutput + ?Sized {}
295
296/// Encodes and writes one canonical LEB128 value.
297///
298/// # Type Parameters
299///
300/// - `N`: Maximum encoded payload length in bytes.
301/// - `T`: Value type accepted by the encoder.
302/// - `W`: Destination byte output.
303/// - `F`: Infallible encoding callback.
304///
305/// # Parameters
306///
307/// - `writer`: Destination for the encoded payload.
308/// - `value`: Value passed to `encode`.
309/// - `encode`: Callback that fills the local buffer and returns its used
310///   length.
311///
312/// # Returns
313///
314/// Returns after the complete payload has been written.
315///
316/// # Errors
317///
318/// Returns an output error, including a write-zero error when the output stops
319/// making progress.
320#[inline]
321fn write_leb128<const N: usize, T, W, F>(writer: &mut W, value: T, encode: F) -> Result<()>
322where
323    W: ByteOutput + ?Sized,
324    F: FnOnce(&mut [u8], T) -> usize,
325{
326    let mut bytes = [0u8; N];
327    let len = encode(&mut bytes, value);
328    write_all(writer, &bytes[..len])
329}