Skip to main content

qubit_io_binary/stream/
buffered_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//! Buffered writer for LEB128-encoded values.
10
11use std::collections::TryReserveError;
12use std::io::Result;
13use std::io::SeekFrom;
14
15use qubit_codec::TranscodeEncodeOutput;
16use qubit_codec_binary::Leb128Codec;
17use qubit_codec_binary::NonStrict;
18use qubit_io::Buffer;
19use qubit_io::Output;
20use qubit_io::Seekable;
21
22use super::internal::TranscodeEncodeOutputExt;
23use crate::util::MIN_CODEC_BUFFER_CAPACITY;
24use crate::util::checked_u64_len;
25use crate::util::write_all;
26
27/// Buffered writer for canonical LEB128 integers.
28///
29/// Values are encoded directly into the internal output buffer and flushed to
30/// the wrapped writer in larger chunks.
31///
32/// # Flush contract
33///
34/// Dropping this writer delegates to `qubit_io::BufferedOutput`, which makes a
35/// best-effort attempt to drain pending bytes, ignores drop-time errors, and
36/// does not guarantee that the wrapped writer itself is flushed. Call
37/// [`Output::flush`] to guarantee that all bytes reach the wrapped output.
38/// [`Self::inner`] can observe the wrapped writer before pending bytes have
39/// been flushed.
40///
41/// # Target-width integers
42///
43/// `usize` and `isize` methods use the current Rust target's pointer width.
44/// Prefer fixed-width integer methods such as `write_u64` or `write_i64` for
45/// persistent files and cross-platform protocols.
46///
47/// # Type Parameters
48///
49/// - `W`: Underlying byte output.
50pub struct BufferedLeb128Writer<W>
51where
52    W: Output<Item = u8>,
53{
54    /// Buffered codec output and wrapped writer.
55    output: TranscodeEncodeOutput<W>,
56}
57
58impl<W> BufferedLeb128Writer<W>
59where
60    W: Output<Item = u8>,
61{
62    /// Creates a buffered LEB128 writer with the default buffer capacity.
63    ///
64    /// # Parameters
65    ///
66    /// - `inner`: Underlying byte output.
67    ///
68    /// # Returns
69    ///
70    /// Returns a buffered canonical LEB128 writer.
71    #[must_use]
72    #[inline]
73    pub fn new(inner: W) -> Self {
74        Self {
75            output: TranscodeEncodeOutput::new(inner),
76        }
77    }
78
79    /// Creates a buffered LEB128 writer with at least `capacity` bytes.
80    ///
81    /// # Parameters
82    ///
83    /// - `inner`: Underlying byte output.
84    /// - `capacity`: Requested internal buffer capacity in bytes.
85    ///
86    /// # Returns
87    ///
88    /// Returns a buffered writer whose capacity also satisfies the largest
89    /// supported codec payload.
90    #[must_use]
91    #[inline]
92    pub fn with_capacity(inner: W, capacity: usize) -> Self {
93        Self {
94            output: TranscodeEncodeOutput::with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY)),
95        }
96    }
97
98    /// Tries to create a buffered LEB128 writer with at least `capacity` bytes.
99    ///
100    /// # Errors
101    ///
102    /// Returns an allocation error when the requested buffer cannot be
103    /// allocated.
104    #[inline]
105    pub fn try_with_capacity(inner: W, capacity: usize) -> std::result::Result<Self, TryReserveError> {
106        Ok(Self {
107            output: TranscodeEncodeOutput::try_with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY))?,
108        })
109    }
110
111    /// Returns a shared reference to the underlying writer.
112    ///
113    /// Pending bytes may still be held in this wrapper's internal buffer.
114    ///
115    /// # Returns
116    ///
117    /// Returns the wrapped writer.
118    #[must_use]
119    #[inline(always)]
120    pub const fn inner(&self) -> &W {
121        self.output.inner()
122    }
123
124    /// Provides access to the underlying writer.
125    ///
126    /// Direct writes through the returned writer bypass pending bytes in this
127    /// wrapper and can reorder the physical byte stream. Flush this wrapper
128    /// before using the returned writer directly.
129    ///
130    /// Returns the underlying writer and every encoded byte still pending.
131    ///
132    /// This method does not call [`Self::flush`] and performs no I/O. Call
133    /// [`Self::flush`] first for normal completion; a successful flush leaves
134    /// the returned buffer empty. Otherwise, the returned buffer transfers
135    /// responsibility for pending bytes to the caller.
136    ///
137    /// # Returns
138    ///
139    /// Returns the wrapped writer and pending bytes in logical write order.
140    #[must_use = "the returned inner writer and pending buffer must be handled"]
141    #[inline(always)]
142    pub fn into_parts(self) -> (W, Buffer<u8>) {
143        self.output.into_parts()
144    }
145
146    /// Writes a UTF-8 string prefixed by an unsigned LEB128 byte length.
147    ///
148    /// The length prefix is encoded as `usize`, so this format is target-width
149    /// dependent. Prefer a fixed-width length prefix for persistent files and
150    /// cross-platform protocols.
151    ///
152    /// # Parameters
153    ///
154    /// - `value`: String to length-prefix and buffer.
155    ///
156    /// # Returns
157    ///
158    /// Returns after the length and payload have been accepted.
159    ///
160    /// # Errors
161    ///
162    /// Returns an output error encountered while making buffer space.
163    #[inline]
164    pub fn write_utf8_string_usize(&mut self, value: &str) -> Result<()> {
165        self.write_usize(value.len())?;
166        write_all(&mut self.output, value.as_bytes())
167    }
168
169    /// Writes a UTF-8 string prefixed by an unsigned LEB128 `u64` byte length.
170    ///
171    /// Prefer this method over [`Self::write_utf8_string_usize`] for persistent
172    /// files and cross-platform protocols because the length field is
173    /// independent of the current Rust target's pointer width.
174    ///
175    /// # Parameters
176    ///
177    /// - `value`: String to length-prefix and buffer.
178    ///
179    /// # Returns
180    ///
181    /// Returns after the length and payload have been accepted.
182    ///
183    /// # Errors
184    ///
185    /// Returns an invalid-input error when the length cannot fit in `u64`, or
186    /// an output error encountered while making buffer space.
187    #[inline]
188    pub fn write_utf8_string_u64(&mut self, value: &str) -> Result<()> {
189        self.write_u64(checked_u64_len(value.len())?)?;
190        write_all(&mut self.output, value.as_bytes())
191    }
192}
193
194macro_rules! impl_write_value {
195    ($method:ident, $ty:ty, $doc:literal) => {
196        #[doc = $doc]
197        #[doc = ""]
198        #[doc = "# Parameters"]
199        #[doc = ""]
200        #[doc = "- `value`: Integer to encode and buffer."]
201        #[doc = ""]
202        #[doc = "# Returns"]
203        #[doc = ""]
204        #[doc = "Returns after the canonical payload has been accepted."]
205        #[doc = ""]
206        #[doc = "# Errors"]
207        #[doc = ""]
208        #[doc = "Returns an output error encountered while making buffer \
209                 space."]
210        #[inline(always)]
211        pub fn $method(&mut self, value: $ty) -> Result<()> {
212            type Codec = Leb128Codec<$ty, NonStrict>;
213
214            self.output.write_encoded::<Codec>(value)
215        }
216    };
217}
218
219impl<W> BufferedLeb128Writer<W>
220where
221    W: Output<Item = u8>,
222{
223    impl_write_value!(write_u8, u8, "Writes an unsigned LEB128 `u8`.");
224    impl_write_value!(write_u16, u16, "Writes an unsigned LEB128 `u16`.");
225    impl_write_value!(write_u32, u32, "Writes an unsigned LEB128 `u32`.");
226    impl_write_value!(write_u64, u64, "Writes an unsigned LEB128 `u64`.");
227    impl_write_value!(write_u128, u128, "Writes an unsigned LEB128 `u128`.");
228    impl_write_value!(write_usize, usize, "Writes an unsigned LEB128 `usize`.");
229    impl_write_value!(write_i8, i8, "Writes a signed LEB128 `i8`.");
230    impl_write_value!(write_i16, i16, "Writes a signed LEB128 `i16`.");
231    impl_write_value!(write_i32, i32, "Writes a signed LEB128 `i32`.");
232    impl_write_value!(write_i64, i64, "Writes a signed LEB128 `i64`.");
233    impl_write_value!(write_i128, i128, "Writes a signed LEB128 `i128`.");
234    impl_write_value!(write_isize, isize, "Writes a signed LEB128 `isize`.");
235}
236
237impl<W> Output for BufferedLeb128Writer<W>
238where
239    W: Output<Item = u8>,
240{
241    type Item = u8;
242
243    /// Reports that this adapter buffers output.
244    ///
245    /// # Returns
246    ///
247    /// Always returns `true`.
248    #[inline(always)]
249    fn is_buffered(&self) -> bool {
250        true
251    }
252
253    /// Writes up to `count` bytes from an indexed input range.
254    ///
255    /// # Parameters
256    ///
257    /// - `input`: Source slice.
258    /// - `index`: First source index.
259    /// - `count`: Maximum number of bytes to write.
260    ///
261    /// # Returns
262    ///
263    /// Returns the number of bytes accepted.
264    ///
265    /// # Errors
266    ///
267    /// Returns an output error encountered while draining pending bytes.
268    ///
269    /// # Safety
270    ///
271    /// `index..index + count` must be a valid range within `input`.
272    #[inline(always)]
273    unsafe fn write_unchecked(&mut self, input: &[u8], index: usize, count: usize) -> Result<usize> {
274        // SAFETY: The caller upholds the indexed source range contract.
275        unsafe { self.output.write_unchecked(input, index, count) }
276    }
277
278    /// Flushes the internal buffer and then the wrapped writer.
279    ///
280    /// # Returns
281    ///
282    /// Returns after buffered and wrapped output have flushed.
283    ///
284    /// # Errors
285    ///
286    /// Returns an error encountered while draining or flushing.
287    #[inline(always)]
288    fn flush(&mut self) -> Result<()> {
289        self.output.flush()
290    }
291}
292
293impl<W> Seekable for BufferedLeb128Writer<W>
294where
295    W: Output<Item = u8> + Seekable<Unit = u8>,
296{
297    type Unit = u8;
298
299    /// Flushes pending bytes before seeking the wrapped writer.
300    ///
301    /// # Parameters
302    ///
303    /// - `position`: Target seek position.
304    ///
305    /// # Returns
306    ///
307    /// Returns the new physical stream position.
308    ///
309    /// # Errors
310    ///
311    /// Returns an error encountered while flushing or seeking.
312    #[inline(always)]
313    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
314        self.output.seek(position)
315    }
316}