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