qubit_io_binary/stream/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//! Writer for LEB128-encoded values.
10
11use std::io::Result;
12use std::io::SeekFrom;
13
14use qubit_codec_binary::Leb128Codec;
15use qubit_codec_binary::NonStrict;
16use qubit_io::ByteOutput;
17use qubit_io::Output;
18use qubit_io::Seekable;
19use qubit_io::SeekableByteOutput;
20
21use crate::util::MIN_CODEC_BUFFER_CAPACITY;
22use crate::util::checked_u64_len;
23use crate::util::encode_infallible_unchecked;
24use crate::util::write_all;
25
26/// Writer wrapper for canonical LEB128 integers.
27///
28/// # Target-width integers
29///
30/// `usize` and `isize` methods use the current Rust target's pointer width.
31/// Prefer fixed-width integer methods such as `write_u64` or `write_i64` for
32/// persistent files and cross-platform protocols.
33///
34/// # Type Parameters
35///
36/// - `W`: Underlying byte output.
37///
38/// # Partial writes
39///
40/// These methods are not transactional. An output error may occur after the
41/// output has accepted a byte prefix of the encoded value, and those bytes are
42/// not rolled back. Calling a method again encodes the entire value from the
43/// output's current position and may duplicate that prefix. Recovery requires
44/// outer framing, a trusted seek or rollback strategy, or a transactional
45/// transport. Output acceptance does not imply durable persistence.
46///
47/// # Examples
48///
49/// ```
50/// use qubit_io_binary::Leb128Writer;
51///
52/// let mut writer = Leb128Writer::new(Vec::new());
53/// writer.write_u16(300).expect("unsigned value should encode");
54/// writer.write_i8(-1).expect("signed value should encode");
55/// assert_eq!(vec![0xac, 0x02, 0x7f], writer.into_inner());
56/// ```
57pub struct Leb128Writer<W> {
58 /// Wrapped byte output.
59 inner: W,
60 /// Scratch storage for the largest LEB128 payload.
61 buffer: [u8; MIN_CODEC_BUFFER_CAPACITY],
62}
63
64impl<W> Leb128Writer<W> {
65 /// Creates a LEB128 writer.
66 ///
67 /// # Parameters
68 ///
69 /// - `inner`: Underlying byte output.
70 ///
71 /// # Returns
72 ///
73 /// Returns a canonical LEB128 writer.
74 #[must_use]
75 #[inline]
76 pub const fn new(inner: W) -> Self {
77 Self {
78 inner,
79 buffer: [0; MIN_CODEC_BUFFER_CAPACITY],
80 }
81 }
82
83 /// Returns a shared reference to the underlying writer.
84 ///
85 /// # Returns
86 ///
87 /// Returns the wrapped writer.
88 #[must_use]
89 #[inline(always)]
90 pub const fn inner(&self) -> &W {
91 &self.inner
92 }
93
94 /// Returns an exclusive reference to the underlying writer.
95 ///
96 /// # Returns
97 ///
98 /// Returns mutable access to the wrapped writer.
99 #[must_use]
100 #[inline(always)]
101 pub fn inner_mut(&mut self) -> &mut W {
102 &mut self.inner
103 }
104
105 /// Consumes this wrapper and returns the underlying writer.
106 ///
107 /// # Returns
108 ///
109 /// Returns the wrapped writer.
110 #[must_use]
111 #[inline(always)]
112 pub fn into_inner(self) -> W {
113 self.inner
114 }
115}
116
117macro_rules! impl_write_value {
118 ($method:ident, $ty:ty, $doc:literal) => {
119 #[doc = $doc]
120 #[doc = ""]
121 #[doc = "# Parameters"]
122 #[doc = ""]
123 #[doc = "- `value`: Integer to encode and write."]
124 #[doc = ""]
125 #[doc = "# Returns"]
126 #[doc = ""]
127 #[doc = "Returns after the canonical payload has been written."]
128 #[doc = ""]
129 #[doc = "# Errors"]
130 #[doc = ""]
131 #[doc = "Returns an output error, including a write-zero error when \
132 the output stops making progress."]
133 #[inline(always)]
134 pub fn $method(&mut self, value: $ty) -> Result<()> {
135 type Codec = Leb128Codec<$ty, NonStrict>;
136
137 self.write_leb128::<$ty, { Codec::MAX_ENCODE_UNITS_PER_VALUE }, _>(value, |bytes, value| unsafe {
138 encode_infallible_unchecked::<Codec>(value, bytes, 0)
139 })
140 }
141 };
142}
143
144impl<W> Leb128Writer<W>
145where
146 W: ByteOutput,
147{
148 impl_write_value!(write_u8, u8, "Writes an unsigned LEB128 `u8`.");
149 impl_write_value!(write_u16, u16, "Writes an unsigned LEB128 `u16`.");
150 impl_write_value!(write_u32, u32, "Writes an unsigned LEB128 `u32`.");
151 impl_write_value!(write_u64, u64, "Writes an unsigned LEB128 `u64`.");
152 impl_write_value!(write_u128, u128, "Writes an unsigned LEB128 `u128`.");
153 impl_write_value!(write_usize, usize, "Writes an unsigned LEB128 `usize`.");
154 impl_write_value!(write_i8, i8, "Writes a signed LEB128 `i8`.");
155 impl_write_value!(write_i16, i16, "Writes a signed LEB128 `i16`.");
156 impl_write_value!(write_i32, i32, "Writes a signed LEB128 `i32`.");
157 impl_write_value!(write_i64, i64, "Writes a signed LEB128 `i64`.");
158 impl_write_value!(write_i128, i128, "Writes a signed LEB128 `i128`.");
159 impl_write_value!(write_isize, isize, "Writes a signed LEB128 `isize`.");
160
161 /// Writes a UTF-8 string prefixed by an unsigned LEB128 byte length.
162 ///
163 /// The length prefix is encoded as `usize`, so this format is target-width
164 /// dependent. Prefer a fixed-width length prefix for persistent files and
165 /// cross-platform protocols.
166 ///
167 /// # Parameters
168 ///
169 /// - `value`: String slice to write.
170 ///
171 /// # Returns
172 ///
173 /// Returns after the length and payload have been written.
174 ///
175 /// # Errors
176 ///
177 /// Returns an I/O error from the underlying writer.
178 ///
179 /// # Partial writes
180 ///
181 /// This operation is not transactional. An I/O error may leave the length
182 /// prefix and part of the payload already accepted by the output. Retrying
183 /// this whole method can write a second prefix; recover using the enclosing
184 /// protocol's framing or transaction boundary instead.
185 #[inline]
186 pub fn write_utf8_string_usize(&mut self, value: &str) -> Result<()> {
187 self.write_usize(value.len())?;
188 let bytes = value.as_bytes();
189 write_all(&mut self.inner, bytes)
190 }
191
192 /// Writes a UTF-8 string prefixed by an unsigned LEB128 `u64` byte length.
193 ///
194 /// Prefer this method over [`Self::write_utf8_string_usize`] for persistent
195 /// files and cross-platform protocols because the length field is
196 /// independent of the current Rust target's pointer width.
197 ///
198 /// # Parameters
199 ///
200 /// - `value`: String slice to write.
201 ///
202 /// # Returns
203 ///
204 /// Returns after the length and payload have been written.
205 ///
206 /// # Errors
207 ///
208 /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8 byte length
209 /// cannot be represented as `u64`, or an I/O error from the underlying
210 /// writer.
211 ///
212 /// # Partial writes
213 ///
214 /// This operation is not transactional. An I/O error may leave the length
215 /// prefix and part of the payload already accepted by the output. Retrying
216 /// this whole method can write a second prefix; recover using the enclosing
217 /// protocol's framing or transaction boundary instead.
218 #[inline]
219 pub fn write_utf8_string_u64(&mut self, value: &str) -> Result<()> {
220 self.write_u64(checked_u64_len(value.len())?)?;
221 let bytes = value.as_bytes();
222 write_all(&mut self.inner, bytes)
223 }
224
225 /// Encodes one value into the scratch buffer and writes its payload.
226 ///
227 /// # Type Parameters
228 ///
229 /// - `T`: Value type accepted by the encoder.
230 /// - `N`: Maximum payload length declared by the codec.
231 /// - `F`: Infallible encoding callback.
232 ///
233 /// # Parameters
234 ///
235 /// - `value`: Value passed to the encoder.
236 /// - `encode`: Callback that fills the scratch buffer and returns the
237 /// encoded length.
238 ///
239 /// # Returns
240 ///
241 /// Returns after the encoded payload has been written.
242 ///
243 /// # Errors
244 ///
245 /// Returns an output error, including a write-zero error when the output
246 /// stops making progress.
247 #[inline]
248 fn write_leb128<T, const N: usize, F>(&mut self, value: T, encode: F) -> Result<()>
249 where
250 F: FnOnce(&mut [u8; MIN_CODEC_BUFFER_CAPACITY], T) -> usize,
251 {
252 let len = encode(&mut self.buffer, value);
253 write_all(&mut self.inner, &self.buffer[..len])
254 }
255}
256
257impl<W> Output for Leb128Writer<W>
258where
259 W: ByteOutput,
260{
261 /// The byte unit accepted by this writer's output operations.
262 type Item = u8;
263
264 /// Reports whether the wrapped output is buffered.
265 ///
266 /// # Returns
267 ///
268 /// Returns the wrapped output's buffering state.
269 #[inline(always)]
270 fn is_buffered(&self) -> bool {
271 self.inner.is_buffered()
272 }
273
274 /// Writes up to `count` bytes from an indexed input range.
275 ///
276 /// # Parameters
277 ///
278 /// - `input`: Source slice.
279 /// - `index`: First source index.
280 /// - `count`: Maximum number of bytes to write.
281 ///
282 /// # Returns
283 ///
284 /// Returns the number of bytes written.
285 ///
286 /// # Errors
287 ///
288 /// Returns an error reported by the wrapped output.
289 ///
290 /// # Safety
291 ///
292 /// `index..index + count` must be a valid range within `input`.
293 #[inline(always)]
294 unsafe fn write_unchecked(&mut self, input: &[u8], index: usize, count: usize) -> Result<usize> {
295 // SAFETY: The caller upholds the wrapped output's range contract.
296 unsafe { self.inner.write_unchecked(input, index, count) }
297 }
298
299 /// Flushes the wrapped writer.
300 ///
301 /// # Returns
302 ///
303 /// Returns after the wrapped output has flushed.
304 ///
305 /// # Errors
306 ///
307 /// Returns the I/O error reported by the wrapped writer.
308 #[inline(always)]
309 fn flush(&mut self) -> Result<()> {
310 Output::flush(&mut self.inner)
311 }
312}
313
314impl<W> Seekable for Leb128Writer<W>
315where
316 W: SeekableByteOutput,
317{
318 /// The byte unit used to express seek positions in the wrapped writer.
319 type Unit = u8;
320
321 /// Seeks the wrapped writer.
322 ///
323 /// # Parameters
324 ///
325 /// - `position`: Target seek position.
326 ///
327 /// # Returns
328 ///
329 /// Returns the new stream position.
330 ///
331 /// # Errors
332 ///
333 /// Returns the seek error reported by the wrapped writer.
334 #[inline(always)]
335 fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
336 self.inner.seek_to(position)
337 }
338}
339
340impl_output_methods!(Leb128Writer<W> where W: ByteOutput);
341impl_seekable_methods!(Leb128Writer<W> where W: SeekableByteOutput);