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