Skip to main content

qubit_io_binary/stream/
buffered_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//! Buffered writer for ZigZag-encoded integer values.
10
11use std::collections::TryReserveError;
12use std::io::Result;
13use std::io::SeekFrom;
14
15use qubit_codec::TranscodeEncodeOutput;
16use qubit_codec_binary::NonStrict;
17use qubit_codec_binary::ZigZagCodec;
18use qubit_io::BufferedOutputRecovery;
19use qubit_io::ByteOutput;
20use qubit_io::Output;
21use qubit_io::Seekable;
22use qubit_io::SeekableByteOutput;
23
24use super::internal::TranscodeEncodeOutputExt;
25use crate::util::MIN_CODEC_BUFFER_CAPACITY;
26
27/// Buffered writer for canonical ZigZag + unsigned LEB128 integers.
28///
29/// Values are encoded directly into the internal output buffer and flushed to
30/// the wrapped writer in larger chunks.
31///
32/// # Flush contract
33///
34/// Dropping this writer delegates to `qubit_io::BufferedOutput`, which makes a
35/// best-effort attempt to drain pending bytes, ignores drop-time errors, and
36/// does not guarantee that the wrapped writer itself is flushed. Call
37/// [`Output::flush`] to guarantee that all bytes reach the wrapped output.
38/// [`Self::inner`] can observe the wrapped writer before pending bytes have
39/// been flushed.
40///
41/// # Target-width integers
42///
43/// `isize` methods use the current Rust target's pointer width. Prefer
44/// fixed-width integer methods such as `write_i64` for persistent files and
45/// cross-platform protocols.
46///
47/// # Type Parameters
48///
49/// - `W`: Underlying byte output.
50///
51/// # Examples
52///
53/// ```
54/// use qubit_io::ByteOutput;
55/// use qubit_io_binary::BufferedZigZagWriter;
56///
57/// let mut writer = BufferedZigZagWriter::new(Vec::new());
58/// writer.write_i32(-123)?;
59/// writer.flush()?;
60/// assert_eq!(writer.inner(), &[0xF5, 0x01]);
61/// # Ok::<(), std::io::Error>(())
62/// ```
63pub struct BufferedZigZagWriter<W>
64where
65    W: ByteOutput,
66{
67    /// Buffered codec output and wrapped writer.
68    output: TranscodeEncodeOutput<W>,
69}
70
71impl_output_methods!(BufferedZigZagWriter<W> where W: ByteOutput);
72impl_seekable_methods!(BufferedZigZagWriter<W> where W: SeekableByteOutput);
73
74impl<W> BufferedZigZagWriter<W>
75where
76    W: ByteOutput,
77{
78    /// Creates a buffered ZigZag writer with the default buffer capacity.
79    ///
80    /// # Parameters
81    ///
82    /// - `inner`: Underlying byte output.
83    ///
84    /// # Returns
85    ///
86    /// Returns a buffered canonical ZigZag writer.
87    #[must_use]
88    #[inline]
89    pub fn new(inner: W) -> Self {
90        Self {
91            output: TranscodeEncodeOutput::new(inner),
92        }
93    }
94
95    /// Creates a buffered ZigZag writer with at least `capacity` bytes.
96    ///
97    /// # Parameters
98    ///
99    /// - `inner`: Underlying byte output.
100    /// - `capacity`: Requested internal buffer capacity in bytes.
101    ///
102    /// # Returns
103    ///
104    /// Returns a buffered writer whose capacity also satisfies the largest
105    /// supported codec payload.
106    #[must_use]
107    #[inline]
108    pub fn with_capacity(inner: W, capacity: usize) -> Self {
109        Self {
110            output: TranscodeEncodeOutput::with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY)),
111        }
112    }
113
114    /// Tries to create a buffered ZigZag writer with at least `capacity` bytes.
115    ///
116    /// # Parameters
117    ///
118    /// - `inner`: Underlying byte output to wrap.
119    /// - `capacity`: Requested internal buffer capacity in bytes. The request
120    ///   is raised when necessary to fit the largest supported codec payload.
121    ///
122    /// # Returns
123    ///
124    /// Returns a buffered writer on successful allocation. Its capacity
125    /// satisfies both the request and the minimum required by the supported
126    /// codecs.
127    ///
128    /// # Errors
129    ///
130    /// Returns a [`TryReserveError`] if the buffer capacity overflows or its
131    /// allocation fails.
132    #[inline]
133    pub fn try_with_capacity(inner: W, capacity: usize) -> std::result::Result<Self, TryReserveError> {
134        Ok(Self {
135            output: TranscodeEncodeOutput::try_with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY))?,
136        })
137    }
138
139    /// Returns a shared reference to the underlying writer.
140    ///
141    /// Pending bytes may still be held in this wrapper's internal buffer.
142    ///
143    /// # Returns
144    ///
145    /// Returns the wrapped writer.
146    #[must_use]
147    #[inline(always)]
148    pub const fn inner(&self) -> &W {
149        self.output.inner()
150    }
151
152    /// Recovers the wrapped writer and the status of bytes retained by this
153    /// writer.
154    ///
155    /// This method performs no I/O and does not call [`Self::flush`]. `Pending`
156    /// bytes were not reported as written and may be retried. `Indeterminate`
157    /// means an inner write panicked and may have produced an external prefix;
158    /// do not replay it automatically. Flush first for normal completion.
159    ///
160    /// # Returns
161    ///
162    /// Returns the wrapped writer and pending or indeterminate bytes in logical
163    /// write order.
164    #[must_use = "the wrapped writer and recovery status must be handled"]
165    #[inline(always)]
166    pub fn into_parts(self) -> (W, BufferedOutputRecovery<u8>) {
167        self.output.into_parts()
168    }
169}
170
171macro_rules! impl_write_value {
172    ($method:ident, $ty:ty, $doc:literal) => {
173        #[doc = $doc]
174        #[doc = ""]
175        #[doc = "# Parameters"]
176        #[doc = ""]
177        #[doc = "- `value`: Signed integer to encode and buffer."]
178        #[doc = ""]
179        #[doc = "# Returns"]
180        #[doc = ""]
181        #[doc = "Returns after the canonical payload has been accepted."]
182        #[doc = ""]
183        #[doc = "# Errors"]
184        #[doc = ""]
185        #[doc = "Returns an output error encountered while making buffer \
186                 space."]
187        #[inline(always)]
188        pub fn $method(&mut self, value: $ty) -> Result<()> {
189            type Codec = ZigZagCodec<$ty, NonStrict>;
190
191            self.output.write_encoded::<Codec>(value)
192        }
193    };
194}
195
196impl<W> BufferedZigZagWriter<W>
197where
198    W: ByteOutput,
199{
200    impl_write_value!(write_i8, i8, "Writes a ZigZag `i8`.");
201    impl_write_value!(write_i16, i16, "Writes a ZigZag `i16`.");
202    impl_write_value!(write_i32, i32, "Writes a ZigZag `i32`.");
203    impl_write_value!(write_i64, i64, "Writes a ZigZag `i64`.");
204    impl_write_value!(write_i128, i128, "Writes a ZigZag `i128`.");
205    impl_write_value!(write_isize, isize, "Writes a ZigZag `isize`.");
206}
207
208impl<W> Output for BufferedZigZagWriter<W>
209where
210    W: ByteOutput,
211{
212    type Item = u8;
213
214    /// Reports that this adapter buffers output.
215    ///
216    /// # Returns
217    ///
218    /// Always returns `true`.
219    #[inline(always)]
220    fn is_buffered(&self) -> bool {
221        true
222    }
223
224    /// Writes up to `count` bytes from an indexed input range.
225    ///
226    /// # Parameters
227    ///
228    /// - `input`: Source slice.
229    /// - `index`: First source index.
230    /// - `count`: Maximum number of bytes to write.
231    ///
232    /// # Returns
233    ///
234    /// Returns the number of bytes accepted.
235    ///
236    /// # Errors
237    ///
238    /// Returns an output error encountered while draining pending bytes.
239    ///
240    /// # Safety
241    ///
242    /// `index..index + count` must be a valid range within `input`.
243    #[inline(always)]
244    unsafe fn write_unchecked(&mut self, input: &[u8], index: usize, count: usize) -> Result<usize> {
245        // SAFETY: The caller upholds the indexed source range contract.
246        unsafe { self.output.write_unchecked(input, index, count) }
247    }
248
249    /// Flushes the internal buffer and then the wrapped writer.
250    ///
251    /// # Returns
252    ///
253    /// Returns after buffered and wrapped output have flushed.
254    ///
255    /// # Errors
256    ///
257    /// Returns an error encountered while draining or flushing.
258    #[inline(always)]
259    fn flush(&mut self) -> Result<()> {
260        self.output.flush()
261    }
262}
263
264impl<W> Seekable for BufferedZigZagWriter<W>
265where
266    W: SeekableByteOutput,
267{
268    type Unit = u8;
269
270    /// Seeks relative to this writer's logical position.
271    /// For `SeekFrom::Current(0)`, returns the logical position including
272    /// pending bytes without draining them. Other requests drain pending bytes
273    /// before repositioning the wrapped output, but do not flush that output.
274    /// Call [`Self::flush`] explicitly when buffered data and the wrapped
275    /// output must be flushed.
276    ///
277    /// # Parameters
278    ///
279    /// - `position`: Target seek position.
280    ///
281    /// # Returns
282    ///
283    /// Returns the new logical stream position in bytes.
284    ///
285    /// # Errors
286    ///
287    /// Returns an error encountered while draining pending bytes or seeking.
288    #[inline(always)]
289    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
290        self.output.seek(position)
291    }
292}