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