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