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