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 /// # Parameters
119 ///
120 /// - `inner`: Underlying byte output to wrap.
121 /// - `capacity`: Requested internal buffer capacity in bytes. The request
122 /// is raised when necessary to fit the largest supported codec payload.
123 ///
124 /// # Returns
125 ///
126 /// Returns a buffered writer on successful allocation. Its capacity
127 /// satisfies both the request and the minimum required by the supported
128 /// codecs.
129 ///
130 /// # Errors
131 ///
132 /// Returns a [`TryReserveError`] if the buffer capacity overflows or its
133 /// allocation fails.
134 #[inline]
135 pub fn try_with_capacity(inner: W, capacity: usize) -> std::result::Result<Self, TryReserveError> {
136 Ok(Self {
137 output: TranscodeEncodeOutput::try_with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY))?,
138 })
139 }
140
141 /// Returns a shared reference to the underlying writer.
142 ///
143 /// Pending bytes may still be held in this wrapper's internal buffer.
144 ///
145 /// # Returns
146 ///
147 /// Returns the wrapped writer.
148 #[must_use]
149 #[inline(always)]
150 pub const fn inner(&self) -> &W {
151 self.output.inner()
152 }
153 /// Recovers the wrapped writer and the status of bytes retained by this
154 /// writer.
155 ///
156 /// This method performs no I/O and does not call [`Self::flush`]. `Pending`
157 /// bytes were not reported as written and may be retried. `Indeterminate`
158 /// means an inner write panicked and may have produced an external prefix;
159 /// do not replay it automatically. Flush first for normal completion.
160 ///
161 /// Pending contains only bytes retained by this buffer. It does not include
162 /// payload bytes that a failed high-level write never accepted. An empty
163 /// pending buffer, or a successful later flush, does not mean that such a
164 /// failed field was completed.
165 ///
166 /// # Returns
167 ///
168 /// Returns the wrapped writer and pending or indeterminate bytes in logical
169 /// write order.
170 #[must_use = "the wrapped writer and recovery status must be handled"]
171 #[inline(always)]
172 pub fn into_parts(self) -> (W, BufferedOutputRecovery<u8>) {
173 self.output.into_parts()
174 }
175
176 /// Writes a UTF-8 string prefixed by an unsigned LEB128 byte length.
177 ///
178 /// The length prefix is encoded as `usize`, so this format is target-width
179 /// dependent. Prefer a fixed-width length prefix for persistent files and
180 /// cross-platform protocols.
181 ///
182 /// # Parameters
183 ///
184 /// - `value`: String to length-prefix and buffer.
185 ///
186 /// # Returns
187 ///
188 /// Returns after the length and payload have been accepted.
189 ///
190 /// # Errors
191 ///
192 /// Returns an output error encountered while making buffer space.
193 ///
194 /// # Partial writes
195 ///
196 /// This operation is not transactional. An I/O error may leave the length
197 /// prefix and part of the payload retained by this writer or already
198 /// accepted by the wrapped output. Retrying
199 /// this whole method can write a second prefix; recover using the enclosing
200 /// protocol's framing or transaction boundary instead.
201 #[inline]
202 pub fn write_utf8_string_usize(&mut self, value: &str) -> Result<()> {
203 self.write_usize(value.len())?;
204 write_all(&mut self.output, value.as_bytes())
205 }
206
207 /// Writes a UTF-8 string prefixed by an unsigned LEB128 `u64` byte length.
208 ///
209 /// Prefer this method over [`Self::write_utf8_string_usize`] for persistent
210 /// files and cross-platform protocols because the length field is
211 /// independent of the current Rust target's pointer width.
212 ///
213 /// # Parameters
214 ///
215 /// - `value`: String to length-prefix and buffer.
216 ///
217 /// # Returns
218 ///
219 /// Returns after the length and payload have been accepted.
220 ///
221 /// # Errors
222 ///
223 /// Returns an invalid-input error when the length cannot fit in `u64`, or
224 /// an output error encountered while making buffer space.
225 ///
226 /// # Partial writes
227 ///
228 /// This operation is not transactional. An I/O error may leave the length
229 /// prefix and part of the payload retained by this writer or already
230 /// accepted by the wrapped output. Retrying
231 /// this whole method can write a second prefix; recover using the enclosing
232 /// protocol's framing or transaction boundary instead.
233 #[inline]
234 pub fn write_utf8_string_u64(&mut self, value: &str) -> Result<()> {
235 self.write_u64(checked_u64_len(value.len())?)?;
236 write_all(&mut self.output, value.as_bytes())
237 }
238}
239
240macro_rules! impl_write_value {
241 ($method:ident, $ty:ty, $doc:literal) => {
242 #[doc = $doc]
243 #[doc = ""]
244 #[doc = "# Parameters"]
245 #[doc = ""]
246 #[doc = "- `value`: Integer to encode and buffer."]
247 #[doc = ""]
248 #[doc = "# Returns"]
249 #[doc = ""]
250 #[doc = "Returns after the canonical payload has been accepted."]
251 #[doc = ""]
252 #[doc = "# Errors"]
253 #[doc = ""]
254 #[doc = "Returns an output error encountered while making buffer \
255 space."]
256 #[inline(always)]
257 pub fn $method(&mut self, value: $ty) -> Result<()> {
258 type Codec = Leb128Codec<$ty, NonStrict>;
259
260 self.output.write_encoded::<Codec>(value)
261 }
262 };
263}
264
265impl<W> BufferedLeb128Writer<W>
266where
267 W: ByteOutput,
268{
269 impl_write_value!(write_u8, u8, "Writes an unsigned LEB128 `u8`.");
270 impl_write_value!(write_u16, u16, "Writes an unsigned LEB128 `u16`.");
271 impl_write_value!(write_u32, u32, "Writes an unsigned LEB128 `u32`.");
272 impl_write_value!(write_u64, u64, "Writes an unsigned LEB128 `u64`.");
273 impl_write_value!(write_u128, u128, "Writes an unsigned LEB128 `u128`.");
274 impl_write_value!(write_usize, usize, "Writes an unsigned LEB128 `usize`.");
275 impl_write_value!(write_i8, i8, "Writes a signed LEB128 `i8`.");
276 impl_write_value!(write_i16, i16, "Writes a signed LEB128 `i16`.");
277 impl_write_value!(write_i32, i32, "Writes a signed LEB128 `i32`.");
278 impl_write_value!(write_i64, i64, "Writes a signed LEB128 `i64`.");
279 impl_write_value!(write_i128, i128, "Writes a signed LEB128 `i128`.");
280 impl_write_value!(write_isize, isize, "Writes a signed LEB128 `isize`.");
281}
282
283impl<W> Output for BufferedLeb128Writer<W>
284where
285 W: ByteOutput,
286{
287 /// Byte elements accepted by this writer.
288 type Item = u8;
289
290 /// Reports that this adapter buffers output.
291 ///
292 /// # Returns
293 ///
294 /// Always returns `true`.
295 #[inline(always)]
296 fn is_buffered(&self) -> bool {
297 true
298 }
299
300 /// Writes up to `count` bytes from an indexed input range.
301 ///
302 /// # Parameters
303 ///
304 /// - `input`: Source slice.
305 /// - `index`: First source index.
306 /// - `count`: Maximum number of bytes to write.
307 ///
308 /// # Returns
309 ///
310 /// Returns the number of bytes accepted.
311 ///
312 /// # Errors
313 ///
314 /// Returns an output error encountered while draining pending bytes.
315 ///
316 /// # Safety
317 ///
318 /// `index..index + count` must be a valid range within `input`.
319 #[inline(always)]
320 unsafe fn write_unchecked(&mut self, input: &[u8], index: usize, count: usize) -> Result<usize> {
321 // SAFETY: The caller upholds the indexed source range contract.
322 unsafe { self.output.write_unchecked(input, index, count) }
323 }
324
325 /// Flushes the internal buffer and then the wrapped writer.
326 ///
327 /// # Returns
328 ///
329 /// Returns after buffered and wrapped output have flushed.
330 ///
331 /// # Errors
332 ///
333 /// Returns an error encountered while draining or flushing.
334 #[inline(always)]
335 fn flush(&mut self) -> Result<()> {
336 self.output.flush()
337 }
338}
339
340impl<W> Seekable for BufferedLeb128Writer<W>
341where
342 W: SeekableByteOutput,
343{
344 /// Positioning unit used by the byte-oriented seek interface.
345 type Unit = u8;
346
347 /// Seeks relative to this writer's logical position.
348 /// For `SeekFrom::Current(0)`, returns the logical position including
349 /// pending bytes without draining them. Other requests drain pending bytes
350 /// before repositioning the wrapped output, but do not flush that output.
351 /// Call [`Self::flush`] explicitly when buffered data and the wrapped
352 /// output must be flushed.
353 ///
354 /// # Parameters
355 ///
356 /// - `position`: Target seek position.
357 ///
358 /// # Returns
359 ///
360 /// Returns the new logical stream position in bytes.
361 ///
362 /// # Errors
363 ///
364 /// Returns an error encountered while draining pending bytes or seeking.
365 #[inline(always)]
366 fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
367 self.output.seek(position)
368 }
369}