Skip to main content

qubit_io_binary/stream/
leb128_writer.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::{
10    Result,
11    SeekFrom,
12};
13
14use crate::util::{
15    MIN_CODEC_BUFFER_CAPACITY,
16    checked_u64_len,
17    encode_infallible_unchecked,
18    write_all,
19};
20use qubit_codec_binary::{
21    Leb128Codec,
22    NonStrict,
23};
24use qubit_io::{
25    Output,
26    Seekable,
27};
28
29/// Writer wrapper for canonical LEB128 integers.
30///
31/// # Target-width integers
32///
33/// `usize` and `isize` methods use the current Rust target's pointer width.
34/// Prefer fixed-width integer methods such as `write_u64` or `write_i64` for
35/// persistent files and cross-platform protocols.
36///
37/// # Type Parameters
38///
39/// - `W`: Underlying byte output.
40pub struct Leb128Writer<W> {
41    /// Wrapped byte output.
42    inner: W,
43    /// Scratch storage for the largest LEB128 payload.
44    buffer: [u8; MIN_CODEC_BUFFER_CAPACITY],
45}
46
47impl<W> Leb128Writer<W> {
48    /// Creates a LEB128 writer.
49    ///
50    /// # Parameters
51    ///
52    /// - `inner`: Underlying byte output.
53    ///
54    /// # Returns
55    ///
56    /// Returns a canonical LEB128 writer.
57    #[must_use]
58    #[inline]
59    pub const fn new(inner: W) -> Self {
60        Self {
61            inner,
62            buffer: [0; MIN_CODEC_BUFFER_CAPACITY],
63        }
64    }
65
66    /// Returns a shared reference to the underlying writer.
67    ///
68    /// # Returns
69    ///
70    /// Returns the wrapped writer.
71    #[must_use]
72    #[inline(always)]
73    pub const fn inner(&self) -> &W {
74        &self.inner
75    }
76
77    /// Returns an exclusive reference to the underlying writer.
78    ///
79    /// # Returns
80    ///
81    /// Returns mutable access to the wrapped writer.
82    #[must_use]
83    #[inline(always)]
84    pub fn inner_mut(&mut self) -> &mut W {
85        &mut self.inner
86    }
87
88    /// Consumes this wrapper and returns the underlying writer.
89    ///
90    /// # Returns
91    ///
92    /// Returns the wrapped writer.
93    #[must_use]
94    #[inline(always)]
95    pub fn into_inner(self) -> W {
96        self.inner
97    }
98}
99
100macro_rules! impl_write_value {
101    ($method:ident, $ty:ty, $doc:literal) => {
102        #[doc = $doc]
103        #[doc = ""]
104        #[doc = "# Parameters"]
105        #[doc = ""]
106        #[doc = "- `value`: Integer to encode and write."]
107        #[doc = ""]
108        #[doc = "# Returns"]
109        #[doc = ""]
110        #[doc = "Returns after the canonical payload has been written."]
111        #[doc = ""]
112        #[doc = "# Errors"]
113        #[doc = ""]
114        #[doc = "Returns an output error, including a write-zero error when \
115                 the output stops making progress."]
116        #[inline(always)]
117        pub fn $method(&mut self, value: $ty) -> Result<()> {
118            type Codec = Leb128Codec<$ty, NonStrict>;
119
120            self.write_leb128::<$ty, { Codec::MAX_ENCODE_UNITS_PER_VALUE }, _>(
121                value,
122                |bytes, value| unsafe {
123                    encode_infallible_unchecked::<Codec>(value, bytes, 0)
124                },
125            )
126        }
127    };
128}
129
130impl<W> Leb128Writer<W>
131where
132    W: Output<Item = u8>,
133{
134    impl_write_value!(write_u8, u8, "Writes an unsigned LEB128 `u8`.");
135    impl_write_value!(write_u16, u16, "Writes an unsigned LEB128 `u16`.");
136    impl_write_value!(write_u32, u32, "Writes an unsigned LEB128 `u32`.");
137    impl_write_value!(write_u64, u64, "Writes an unsigned LEB128 `u64`.");
138    impl_write_value!(write_u128, u128, "Writes an unsigned LEB128 `u128`.");
139    impl_write_value!(write_usize, usize, "Writes an unsigned LEB128 `usize`.");
140    impl_write_value!(write_i8, i8, "Writes a signed LEB128 `i8`.");
141    impl_write_value!(write_i16, i16, "Writes a signed LEB128 `i16`.");
142    impl_write_value!(write_i32, i32, "Writes a signed LEB128 `i32`.");
143    impl_write_value!(write_i64, i64, "Writes a signed LEB128 `i64`.");
144    impl_write_value!(write_i128, i128, "Writes a signed LEB128 `i128`.");
145    impl_write_value!(write_isize, isize, "Writes a signed LEB128 `isize`.");
146
147    /// Writes a UTF-8 string prefixed by an unsigned LEB128 byte length.
148    ///
149    /// The length prefix is encoded as `usize`, so this format is target-width
150    /// dependent. Prefer a fixed-width length prefix for persistent files and
151    /// cross-platform protocols.
152    ///
153    /// # Parameters
154    ///
155    /// - `value`: String slice to write.
156    ///
157    /// # Returns
158    ///
159    /// Returns after the length and payload have been written.
160    ///
161    /// # Errors
162    ///
163    /// Returns an I/O error from the underlying writer.
164    #[inline]
165    pub fn write_utf8_string_usize(&mut self, value: &str) -> Result<()> {
166        self.write_usize(value.len())?;
167        let bytes = value.as_bytes();
168        write_all(&mut self.inner, bytes)
169    }
170
171    /// Writes a UTF-8 string prefixed by an unsigned LEB128 `u64` byte length.
172    ///
173    /// Prefer this method over [`Self::write_utf8_string_usize`] for persistent
174    /// files and cross-platform protocols because the length field is
175    /// independent of the current Rust target's pointer width.
176    ///
177    /// # Parameters
178    ///
179    /// - `value`: String slice to write.
180    ///
181    /// # Returns
182    ///
183    /// Returns after the length and payload have been written.
184    ///
185    /// # Errors
186    ///
187    /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8 byte length
188    /// cannot be represented as `u64`, or an I/O error from the underlying
189    /// writer.
190    #[inline]
191    pub fn write_utf8_string_u64(&mut self, value: &str) -> Result<()> {
192        self.write_u64(checked_u64_len(value.len())?)?;
193        let bytes = value.as_bytes();
194        write_all(&mut self.inner, bytes)
195    }
196
197    /// Encodes one value into the scratch buffer and writes its payload.
198    ///
199    /// # Type Parameters
200    ///
201    /// - `T`: Value type accepted by the encoder.
202    /// - `N`: Maximum payload length declared by the codec.
203    /// - `F`: Infallible encoding callback.
204    ///
205    /// # Parameters
206    ///
207    /// - `value`: Value passed to the encoder.
208    /// - `encode`: Callback that fills the scratch buffer and returns the
209    ///   encoded length.
210    ///
211    /// # Returns
212    ///
213    /// Returns after the encoded payload has been written.
214    ///
215    /// # Errors
216    ///
217    /// Returns an output error, including a write-zero error when the output
218    /// stops making progress.
219    #[inline]
220    fn write_leb128<T, const N: usize, F>(
221        &mut self,
222        value: T,
223        encode: F,
224    ) -> Result<()>
225    where
226        F: FnOnce(&mut [u8; MIN_CODEC_BUFFER_CAPACITY], T) -> usize,
227    {
228        let len = encode(&mut self.buffer, value);
229        write_all(&mut self.inner, &self.buffer[..len])
230    }
231}
232
233impl<W> Output for Leb128Writer<W>
234where
235    W: Output<Item = u8>,
236{
237    type Item = u8;
238
239    /// Reports whether the wrapped output is buffered.
240    ///
241    /// # Returns
242    ///
243    /// Returns the wrapped output's buffering state.
244    #[inline(always)]
245    fn is_buffered(&self) -> bool {
246        self.inner.is_buffered()
247    }
248
249    /// Writes up to `count` bytes from an indexed input range.
250    ///
251    /// # Parameters
252    ///
253    /// - `input`: Source slice.
254    /// - `index`: First source index.
255    /// - `count`: Maximum number of bytes to write.
256    ///
257    /// # Returns
258    ///
259    /// Returns the number of bytes written.
260    ///
261    /// # Errors
262    ///
263    /// Returns an error reported by the wrapped output.
264    ///
265    /// # Safety
266    ///
267    /// `index..index + count` must be a valid range within `input`.
268    #[inline(always)]
269    unsafe fn write_unchecked(
270        &mut self,
271        input: &[u8],
272        index: usize,
273        count: usize,
274    ) -> Result<usize> {
275        // SAFETY: The caller upholds the wrapped output's range contract.
276        unsafe { self.inner.write_unchecked(input, index, count) }
277    }
278
279    /// Flushes the wrapped writer.
280    ///
281    /// # Returns
282    ///
283    /// Returns after the wrapped output has flushed.
284    ///
285    /// # Errors
286    ///
287    /// Returns the I/O error reported by the wrapped writer.
288    #[inline(always)]
289    fn flush(&mut self) -> Result<()> {
290        Output::flush(&mut self.inner)
291    }
292}
293
294impl<W> Seekable for Leb128Writer<W>
295where
296    W: Seekable<Unit = u8>,
297{
298    type Unit = u8;
299
300    /// Seeks the wrapped writer.
301    ///
302    /// # Parameters
303    ///
304    /// - `position`: Target seek position.
305    ///
306    /// # Returns
307    ///
308    /// Returns the new stream position.
309    ///
310    /// # Errors
311    ///
312    /// Returns the seek error reported by the wrapped writer.
313    #[inline(always)]
314    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
315        self.inner.seek_to(position)
316    }
317}