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