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