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 }, _>(value, |bytes, value| unsafe {
115 encode_infallible_unchecked::<Codec>(value, bytes, 0)
116 })
117 }
118 };
119}
120
121impl<W> ZigZagWriter<W>
122where
123 W: Output<Item = u8>,
124{
125 impl_write_value!(write_i8, i8, "Writes a ZigZag `i8`.");
126 impl_write_value!(write_i16, i16, "Writes a ZigZag `i16`.");
127 impl_write_value!(write_i32, i32, "Writes a ZigZag `i32`.");
128 impl_write_value!(write_i64, i64, "Writes a ZigZag `i64`.");
129 impl_write_value!(write_i128, i128, "Writes a ZigZag `i128`.");
130 impl_write_value!(write_isize, isize, "Writes a ZigZag `isize`.");
131
132 /// Encodes one value into the scratch buffer and writes its payload.
133 ///
134 /// # Type Parameters
135 ///
136 /// - `T`: Value type accepted by the encoder.
137 /// - `N`: Maximum payload length declared by the codec.
138 /// - `F`: Infallible encoding callback.
139 ///
140 /// # Parameters
141 ///
142 /// - `value`: Value passed to the encoder.
143 /// - `encode`: Callback that fills the scratch buffer and returns the
144 /// encoded length.
145 ///
146 /// # Returns
147 ///
148 /// Returns after the encoded payload has been written.
149 ///
150 /// # Errors
151 ///
152 /// Returns an output error, including a write-zero error when the output
153 /// stops making progress.
154 #[inline]
155 fn write_zig_zag<T, const N: usize, F>(&mut self, value: T, encode: F) -> Result<()>
156 where
157 F: FnOnce(&mut [u8; MIN_CODEC_BUFFER_CAPACITY], T) -> usize,
158 {
159 let len = encode(&mut self.buffer, value);
160 write_all(&mut self.inner, &self.buffer[..len])
161 }
162}
163
164impl<W> Output for ZigZagWriter<W>
165where
166 W: Output<Item = u8>,
167{
168 type Item = u8;
169
170 /// Reports whether the wrapped output is buffered.
171 ///
172 /// # Returns
173 ///
174 /// Returns the wrapped output's buffering state.
175 #[inline(always)]
176 fn is_buffered(&self) -> bool {
177 self.inner.is_buffered()
178 }
179
180 /// Writes up to `count` bytes from an indexed input range.
181 ///
182 /// # Parameters
183 ///
184 /// - `input`: Source slice.
185 /// - `index`: First source index.
186 /// - `count`: Maximum number of bytes to write.
187 ///
188 /// # Returns
189 ///
190 /// Returns the number of bytes written.
191 ///
192 /// # Errors
193 ///
194 /// Returns an error reported by the wrapped output.
195 ///
196 /// # Safety
197 ///
198 /// `index..index + count` must be a valid range within `input`.
199 #[inline(always)]
200 unsafe fn write_unchecked(&mut self, input: &[u8], index: usize, count: usize) -> Result<usize> {
201 // SAFETY: The caller upholds the wrapped output's range contract.
202 unsafe { self.inner.write_unchecked(input, index, count) }
203 }
204
205 /// Flushes the wrapped writer.
206 ///
207 /// # Returns
208 ///
209 /// Returns after the wrapped output has flushed.
210 ///
211 /// # Errors
212 ///
213 /// Returns the I/O error reported by the wrapped writer.
214 #[inline(always)]
215 fn flush(&mut self) -> Result<()> {
216 Output::flush(&mut self.inner)
217 }
218}
219
220impl<W> Seekable for ZigZagWriter<W>
221where
222 W: Seekable<Unit = u8>,
223{
224 type Unit = u8;
225
226 /// Seeks the wrapped writer.
227 ///
228 /// # Parameters
229 ///
230 /// - `position`: Target seek position.
231 ///
232 /// # Returns
233 ///
234 /// Returns the new stream position.
235 ///
236 /// # Errors
237 ///
238 /// Returns the seek error reported by the wrapped writer.
239 #[inline(always)]
240 fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
241 self.inner.seek_to(position)
242 }
243}