qubit_io_binary/stream/zig_zag_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 ZigZag-encoded integer values.
10
11use std::io::Result;
12use std::io::SeekFrom;
13
14use qubit_codec_binary::NonStrict;
15use qubit_codec_binary::ZigZagCodec;
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::encode_infallible_unchecked;
23use crate::util::write_all;
24
25/// Writer wrapper for canonical ZigZag + unsigned LEB128 integers.
26///
27/// # Target-width integers
28///
29/// `isize` methods use the current Rust target's pointer width. Prefer
30/// fixed-width integer methods such as `write_i64` for persistent files and
31/// cross-platform protocols.
32///
33/// # Type Parameters
34///
35/// - `W`: Underlying byte output.
36///
37/// # Partial writes
38///
39/// These methods are not transactional. An output error may occur after the
40/// output has accepted a byte prefix of the encoded value, and those bytes are
41/// not rolled back. Calling a method again encodes the entire value from the
42/// output's current position and may duplicate that prefix. Recovery requires
43/// outer framing, a trusted seek or rollback strategy, or a transactional
44/// transport. Output acceptance does not imply durable persistence.
45///
46/// # Examples
47///
48/// ```
49/// use qubit_io_binary::ZigZagWriter;
50///
51/// let mut writer = ZigZagWriter::new(Vec::new());
52/// writer.write_i8(-1).expect("value should be written");
53/// assert_eq!(writer.into_inner(), vec![1]);
54/// ```
55pub struct ZigZagWriter<W> {
56 /// Wrapped byte output.
57 inner: W,
58 /// Scratch storage for the largest encoded ZigZag payload.
59 buffer: [u8; MIN_CODEC_BUFFER_CAPACITY],
60}
61
62impl<W> ZigZagWriter<W> {
63 /// Creates a ZigZag writer.
64 ///
65 /// # Parameters
66 ///
67 /// - `inner`: Underlying byte output.
68 ///
69 /// # Returns
70 ///
71 /// Returns a canonical ZigZag writer.
72 #[must_use]
73 #[inline]
74 pub const fn new(inner: W) -> Self {
75 Self {
76 inner,
77 buffer: [0; MIN_CODEC_BUFFER_CAPACITY],
78 }
79 }
80
81 /// Returns a shared reference to the underlying writer.
82 ///
83 /// # Returns
84 ///
85 /// Returns the wrapped writer.
86 #[must_use]
87 #[inline(always)]
88 pub const fn inner(&self) -> &W {
89 &self.inner
90 }
91
92 /// Returns an exclusive reference to the underlying writer.
93 ///
94 /// # Returns
95 ///
96 /// Returns mutable access to the wrapped writer.
97 #[must_use]
98 #[inline(always)]
99 pub fn inner_mut(&mut self) -> &mut W {
100 &mut self.inner
101 }
102
103 /// Consumes this wrapper and returns the underlying writer.
104 ///
105 /// # Returns
106 ///
107 /// Returns the wrapped writer.
108 #[must_use]
109 #[inline(always)]
110 pub fn into_inner(self) -> W {
111 self.inner
112 }
113}
114
115macro_rules! impl_write_value {
116 ($method:ident, $ty:ty, $doc:literal) => {
117 #[doc = $doc]
118 #[doc = ""]
119 #[doc = "# Parameters"]
120 #[doc = ""]
121 #[doc = "- `value`: Signed integer to encode and write."]
122 #[doc = ""]
123 #[doc = "# Returns"]
124 #[doc = ""]
125 #[doc = "Returns after the canonical payload has been written."]
126 #[doc = ""]
127 #[doc = "# Errors"]
128 #[doc = ""]
129 #[doc = "Returns an output error, including a write-zero error when \
130 the output stops making progress."]
131 #[inline(always)]
132 pub fn $method(&mut self, value: $ty) -> Result<()> {
133 type Codec = ZigZagCodec<$ty, NonStrict>;
134
135 self.write_zig_zag::<$ty, { Codec::MAX_ENCODE_UNITS_PER_VALUE }, _>(value, |bytes, value| unsafe {
136 encode_infallible_unchecked::<Codec>(value, bytes, 0)
137 })
138 }
139 };
140}
141
142impl<W> ZigZagWriter<W>
143where
144 W: ByteOutput,
145{
146 impl_write_value!(write_i8, i8, "Writes a ZigZag `i8`.");
147 impl_write_value!(write_i16, i16, "Writes a ZigZag `i16`.");
148 impl_write_value!(write_i32, i32, "Writes a ZigZag `i32`.");
149 impl_write_value!(write_i64, i64, "Writes a ZigZag `i64`.");
150 impl_write_value!(write_i128, i128, "Writes a ZigZag `i128`.");
151 impl_write_value!(write_isize, isize, "Writes a ZigZag `isize`.");
152
153 /// Encodes one value into the scratch buffer and writes its payload.
154 ///
155 /// # Type Parameters
156 ///
157 /// - `T`: Value type accepted by the encoder.
158 /// - `N`: Maximum payload length declared by the codec.
159 /// - `F`: Infallible encoding callback.
160 ///
161 /// # Parameters
162 ///
163 /// - `value`: Value passed to the encoder.
164 /// - `encode`: Callback that fills the scratch buffer and returns the
165 /// encoded length.
166 ///
167 /// # Returns
168 ///
169 /// Returns after the encoded payload has been written.
170 ///
171 /// # Errors
172 ///
173 /// Returns an output error, including a write-zero error when the output
174 /// stops making progress.
175 #[inline]
176 fn write_zig_zag<T, const N: usize, F>(&mut self, value: T, encode: F) -> Result<()>
177 where
178 F: FnOnce(&mut [u8; MIN_CODEC_BUFFER_CAPACITY], T) -> usize,
179 {
180 let len = encode(&mut self.buffer, value);
181 write_all(&mut self.inner, &self.buffer[..len])
182 }
183}
184
185impl<W> Output for ZigZagWriter<W>
186where
187 W: ByteOutput,
188{
189 type Item = u8;
190
191 /// Reports whether the wrapped output is buffered.
192 ///
193 /// # Returns
194 ///
195 /// Returns the wrapped output's buffering state.
196 #[inline(always)]
197 fn is_buffered(&self) -> bool {
198 self.inner.is_buffered()
199 }
200
201 /// Writes up to `count` bytes from an indexed input range.
202 ///
203 /// # Parameters
204 ///
205 /// - `input`: Source slice.
206 /// - `index`: First source index.
207 /// - `count`: Maximum number of bytes to write.
208 ///
209 /// # Returns
210 ///
211 /// Returns the number of bytes written.
212 ///
213 /// # Errors
214 ///
215 /// Returns an error reported by the wrapped output.
216 ///
217 /// # Safety
218 ///
219 /// `index..index + count` must be a valid range within `input`.
220 #[inline(always)]
221 unsafe fn write_unchecked(&mut self, input: &[u8], index: usize, count: usize) -> Result<usize> {
222 // SAFETY: The caller upholds the wrapped output's range contract.
223 unsafe { self.inner.write_unchecked(input, index, count) }
224 }
225
226 /// Flushes the wrapped writer.
227 ///
228 /// # Returns
229 ///
230 /// Returns after the wrapped output has flushed.
231 ///
232 /// # Errors
233 ///
234 /// Returns the I/O error reported by the wrapped writer.
235 #[inline(always)]
236 fn flush(&mut self) -> Result<()> {
237 Output::flush(&mut self.inner)
238 }
239}
240
241impl<W> Seekable for ZigZagWriter<W>
242where
243 W: SeekableByteOutput,
244{
245 type Unit = u8;
246
247 /// Seeks the wrapped writer.
248 ///
249 /// # Parameters
250 ///
251 /// - `position`: Target seek position.
252 ///
253 /// # Returns
254 ///
255 /// Returns the new stream position.
256 ///
257 /// # Errors
258 ///
259 /// Returns the seek error reported by the wrapped writer.
260 #[inline(always)]
261 fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
262 self.inner.seek_to(position)
263 }
264}
265
266impl_output_methods!(ZigZagWriter<W> where W: ByteOutput);
267impl_seekable_methods!(ZigZagWriter<W> where W: SeekableByteOutput);