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