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