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
9use std::io::Result;
10
11use crate::util::{
12    encode_infallible_unchecked,
13    write_all,
14};
15use qubit_codec_binary::{
16    Leb128Codec,
17    NonStrict,
18};
19use qubit_io::Output;
20
21macro_rules! write_leb128_value {
22    ($writer:expr, $value:expr, $ty:ty) => {
23        write_leb128::<
24            { Leb128Codec::<$ty, NonStrict>::MAX_ENCODE_UNITS_PER_VALUE },
25            _,
26            _,
27            _,
28        >($writer, $value, |bytes, value| {
29            type Codec = Leb128Codec<$ty, NonStrict>;
30            // SAFETY: The local buffer is exactly the codec's maximum buffer
31            // length.
32            unsafe { encode_infallible_unchecked::<Codec>(value, bytes, 0) }
33        })
34    };
35}
36
37/// Extension methods for writing canonical LEB128 integers to byte streams.
38///
39/// # Target-width integers
40///
41/// `usize` and `isize` methods use the current Rust target's pointer width.
42/// Prefer fixed-width integer methods such as [`Self::write_uleb_u64`] or
43/// [`Self::write_sleb_i64`] for persistent files and cross-platform protocols.
44pub trait Leb128WriteExt: Output<Item = u8> {
45    /// Writes an unsigned LEB128 `u8`.
46    ///
47    /// # Parameters
48    ///
49    /// - `value`: Integer to encode and write.
50    ///
51    /// # Returns
52    ///
53    /// Returns after the canonical payload has been written.
54    ///
55    /// # Errors
56    ///
57    /// Returns an output error, including a write-zero error when the output
58    /// stops making progress.
59    #[inline(always)]
60    fn write_uleb_u8(&mut self, value: u8) -> Result<()> {
61        write_leb128_value!(self, value, u8)
62    }
63
64    /// Writes an unsigned LEB128 `u16`.
65    ///
66    /// # Parameters
67    ///
68    /// - `value`: Integer to encode and write.
69    ///
70    /// # Returns
71    ///
72    /// Returns after the canonical payload has been written.
73    ///
74    /// # Errors
75    ///
76    /// Returns an output error, including a write-zero error when the output
77    /// stops making progress.
78    #[inline(always)]
79    fn write_uleb_u16(&mut self, value: u16) -> Result<()> {
80        write_leb128_value!(self, value, u16)
81    }
82
83    /// Writes an unsigned LEB128 `u32`.
84    ///
85    /// # Parameters
86    ///
87    /// - `value`: Integer to encode and write.
88    ///
89    /// # Returns
90    ///
91    /// Returns after the canonical payload has been written.
92    ///
93    /// # Errors
94    ///
95    /// Returns an output error, including a write-zero error when the output
96    /// stops making progress.
97    #[inline(always)]
98    fn write_uleb_u32(&mut self, value: u32) -> Result<()> {
99        write_leb128_value!(self, value, u32)
100    }
101
102    /// Writes an unsigned LEB128 `u64`.
103    ///
104    /// # Parameters
105    ///
106    /// - `value`: Integer to encode and write.
107    ///
108    /// # Returns
109    ///
110    /// Returns after the canonical payload has been written.
111    ///
112    /// # Errors
113    ///
114    /// Returns an output error, including a write-zero error when the output
115    /// stops making progress.
116    #[inline(always)]
117    fn write_uleb_u64(&mut self, value: u64) -> Result<()> {
118        write_leb128_value!(self, value, u64)
119    }
120
121    /// Writes an unsigned LEB128 `u128`.
122    ///
123    /// # Parameters
124    ///
125    /// - `value`: Integer to encode and write.
126    ///
127    /// # Returns
128    ///
129    /// Returns after the canonical payload has been written.
130    ///
131    /// # Errors
132    ///
133    /// Returns an output error, including a write-zero error when the output
134    /// stops making progress.
135    #[inline(always)]
136    fn write_uleb_u128(&mut self, value: u128) -> Result<()> {
137        write_leb128_value!(self, value, u128)
138    }
139
140    /// Writes an unsigned LEB128 `usize`.
141    ///
142    /// # Parameters
143    ///
144    /// - `value`: Integer to encode and write.
145    ///
146    /// # Returns
147    ///
148    /// Returns after the canonical payload has been written.
149    ///
150    /// # Errors
151    ///
152    /// Returns an output error, including a write-zero error when the output
153    /// stops making progress.
154    #[inline(always)]
155    fn write_uleb_usize(&mut self, value: usize) -> Result<()> {
156        write_leb128_value!(self, value, usize)
157    }
158
159    /// Writes a signed LEB128 `i8`.
160    ///
161    /// # Parameters
162    ///
163    /// - `value`: Integer to encode and write.
164    ///
165    /// # Returns
166    ///
167    /// Returns after the canonical payload has been written.
168    ///
169    /// # Errors
170    ///
171    /// Returns an output error, including a write-zero error when the output
172    /// stops making progress.
173    #[inline(always)]
174    fn write_sleb_i8(&mut self, value: i8) -> Result<()> {
175        write_leb128_value!(self, value, i8)
176    }
177
178    /// Writes a signed LEB128 `i16`.
179    ///
180    /// # Parameters
181    ///
182    /// - `value`: Integer to encode and write.
183    ///
184    /// # Returns
185    ///
186    /// Returns after the canonical payload has been written.
187    ///
188    /// # Errors
189    ///
190    /// Returns an output error, including a write-zero error when the output
191    /// stops making progress.
192    #[inline(always)]
193    fn write_sleb_i16(&mut self, value: i16) -> Result<()> {
194        write_leb128_value!(self, value, i16)
195    }
196
197    /// Writes a signed LEB128 `i32`.
198    ///
199    /// # Parameters
200    ///
201    /// - `value`: Integer to encode and write.
202    ///
203    /// # Returns
204    ///
205    /// Returns after the canonical payload has been written.
206    ///
207    /// # Errors
208    ///
209    /// Returns an output error, including a write-zero error when the output
210    /// stops making progress.
211    #[inline(always)]
212    fn write_sleb_i32(&mut self, value: i32) -> Result<()> {
213        write_leb128_value!(self, value, i32)
214    }
215
216    /// Writes a signed LEB128 `i64`.
217    ///
218    /// # Parameters
219    ///
220    /// - `value`: Integer to encode and write.
221    ///
222    /// # Returns
223    ///
224    /// Returns after the canonical payload has been written.
225    ///
226    /// # Errors
227    ///
228    /// Returns an output error, including a write-zero error when the output
229    /// stops making progress.
230    #[inline(always)]
231    fn write_sleb_i64(&mut self, value: i64) -> Result<()> {
232        write_leb128_value!(self, value, i64)
233    }
234
235    /// Writes a signed LEB128 `i128`.
236    ///
237    /// # Parameters
238    ///
239    /// - `value`: Integer to encode and write.
240    ///
241    /// # Returns
242    ///
243    /// Returns after the canonical payload has been written.
244    ///
245    /// # Errors
246    ///
247    /// Returns an output error, including a write-zero error when the output
248    /// stops making progress.
249    #[inline(always)]
250    fn write_sleb_i128(&mut self, value: i128) -> Result<()> {
251        write_leb128_value!(self, value, i128)
252    }
253
254    /// Writes a signed LEB128 `isize`.
255    ///
256    /// # Parameters
257    ///
258    /// - `value`: Integer to encode and write.
259    ///
260    /// # Returns
261    ///
262    /// Returns after the canonical payload has been written.
263    ///
264    /// # Errors
265    ///
266    /// Returns an output error, including a write-zero error when the output
267    /// stops making progress.
268    #[inline(always)]
269    fn write_sleb_isize(&mut self, value: isize) -> Result<()> {
270        write_leb128_value!(self, value, isize)
271    }
272}
273
274impl<W> Leb128WriteExt for W where W: Output<Item = u8> + ?Sized {}
275
276/// Encodes and writes one canonical LEB128 value.
277///
278/// # Type Parameters
279///
280/// - `N`: Maximum encoded payload length in bytes.
281/// - `T`: Value type accepted by the encoder.
282/// - `W`: Destination byte output.
283/// - `F`: Infallible encoding callback.
284///
285/// # Parameters
286///
287/// - `writer`: Destination for the encoded payload.
288/// - `value`: Value passed to `encode`.
289/// - `encode`: Callback that fills the local buffer and returns its used
290///   length.
291///
292/// # Returns
293///
294/// Returns after the complete payload has been written.
295///
296/// # Errors
297///
298/// Returns an output error, including a write-zero error when the output stops
299/// making progress.
300#[inline]
301fn write_leb128<const N: usize, T, W, F>(
302    writer: &mut W,
303    value: T,
304    encode: F,
305) -> Result<()>
306where
307    W: Output<Item = u8> + ?Sized,
308    F: FnOnce(&mut [u8], T) -> usize,
309{
310    let mut bytes = [0u8; N];
311    let len = encode(&mut bytes, value);
312    write_all(writer, &bytes[..len])
313}