Skip to main content

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    /// The byte item type emitted by this ZigZag writer.
190    type Item = u8;
191
192    /// Reports whether the wrapped output is buffered.
193    ///
194    /// # Returns
195    ///
196    /// Returns the wrapped output's buffering state.
197    #[inline(always)]
198    fn is_buffered(&self) -> bool {
199        self.inner.is_buffered()
200    }
201
202    /// Writes up to `count` bytes from an indexed input range.
203    ///
204    /// # Parameters
205    ///
206    /// - `input`: Source slice.
207    /// - `index`: First source index.
208    /// - `count`: Maximum number of bytes to write.
209    ///
210    /// # Returns
211    ///
212    /// Returns the number of bytes written.
213    ///
214    /// # Errors
215    ///
216    /// Returns an error reported by the wrapped output.
217    ///
218    /// # Safety
219    ///
220    /// `index..index + count` must be a valid range within `input`.
221    #[inline(always)]
222    unsafe fn write_unchecked(&mut self, input: &[u8], index: usize, count: usize) -> Result<usize> {
223        // SAFETY: The caller upholds the wrapped output's range contract.
224        unsafe { self.inner.write_unchecked(input, index, count) }
225    }
226
227    /// Flushes the wrapped writer.
228    ///
229    /// # Returns
230    ///
231    /// Returns after the wrapped output has flushed.
232    ///
233    /// # Errors
234    ///
235    /// Returns the I/O error reported by the wrapped writer.
236    #[inline(always)]
237    fn flush(&mut self) -> Result<()> {
238        Output::flush(&mut self.inner)
239    }
240}
241
242impl<W> Seekable for ZigZagWriter<W>
243where
244    W: SeekableByteOutput,
245{
246    /// The byte unit used to measure positions in the wrapped writer.
247    type Unit = u8;
248
249    /// Seeks the wrapped writer.
250    ///
251    /// # Parameters
252    ///
253    /// - `position`: Target seek position.
254    ///
255    /// # Returns
256    ///
257    /// Returns the new stream position.
258    ///
259    /// # Errors
260    ///
261    /// Returns the seek error reported by the wrapped writer.
262    #[inline(always)]
263    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
264        self.inner.seek_to(position)
265    }
266}
267
268impl_output_methods!(ZigZagWriter<W> where W: ByteOutput);
269impl_seekable_methods!(ZigZagWriter<W> where W: SeekableByteOutput);