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    ///
107    /// # Panics
108    ///
109    /// Panics if `capacity` exceeds the maximum capacity supported by `Vec`.
110    #[must_use]
111    #[inline]
112    pub fn with_capacity(inner: W, capacity: usize) -> Self {
113        Self {
114            output: TranscodeEncodeOutput::with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY)),
115        }
116    }
117
118    /// Tries to create a buffered ZigZag writer with at least `capacity` bytes.
119    ///
120    /// # Parameters
121    ///
122    /// - `inner`: Underlying byte output to wrap.
123    /// - `capacity`: Requested internal buffer capacity in bytes. The request
124    ///   is raised when necessary to fit the largest supported codec payload.
125    ///
126    /// # Returns
127    ///
128    /// Returns a buffered writer on successful allocation. Its capacity
129    /// satisfies both the request and the minimum required by the supported
130    /// codecs.
131    ///
132    /// # Errors
133    ///
134    /// Returns a [`TryReserveError`] if the buffer capacity overflows or its
135    /// allocation fails.
136    #[inline]
137    pub fn try_with_capacity(inner: W, capacity: usize) -> std::result::Result<Self, TryReserveError> {
138        Ok(Self {
139            output: TranscodeEncodeOutput::try_with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY))?,
140        })
141    }
142
143    /// Returns a shared reference to the underlying writer.
144    ///
145    /// Pending bytes may still be held in this wrapper's internal buffer.
146    ///
147    /// # Returns
148    ///
149    /// Returns the wrapped writer.
150    #[must_use]
151    #[inline(always)]
152    pub const fn inner(&self) -> &W {
153        self.output.inner()
154    }
155
156    /// Recovers the wrapped writer and the status of bytes retained by this
157    /// writer.
158    ///
159    /// This method performs no I/O and does not call [`Self::flush`]. `Pending`
160    /// bytes were not reported as written and may be retried. `Indeterminate`
161    /// means an inner write panicked and may have produced an external prefix;
162    /// do not replay it automatically. Flush first for normal completion.
163    ///
164    /// # Returns
165    ///
166    /// Returns the wrapped writer and pending or indeterminate bytes in logical
167    /// write order.
168    #[must_use = "the wrapped writer and recovery status must be handled"]
169    #[inline(always)]
170    pub fn into_parts(self) -> (W, BufferedOutputRecovery<u8>) {
171        self.output.into_parts()
172    }
173}
174
175/// Defines an inherent writer method for one signed integer width.
176macro_rules! impl_write_value {
177    ($method:ident, $ty:ty, $doc:literal) => {
178        #[doc = $doc]
179        #[doc = ""]
180        #[doc = "# Parameters"]
181        #[doc = ""]
182        #[doc = "- `value`: Signed integer to encode and buffer."]
183        #[doc = ""]
184        #[doc = "# Returns"]
185        #[doc = ""]
186        #[doc = "Returns after the canonical payload has been accepted."]
187        #[doc = ""]
188        #[doc = "# Errors"]
189        #[doc = ""]
190        #[doc = "Returns an output error encountered while making buffer \
191                 space."]
192        #[inline(always)]
193        pub fn $method(&mut self, value: $ty) -> Result<()> {
194            /// Codec that maps this integer width to canonical ZigZag bytes.
195            type Codec = ZigZagCodec<$ty, NonStrict>;
196
197            self.output.write_encoded::<Codec>(value)
198        }
199    };
200}
201
202impl<W> BufferedZigZagWriter<W>
203where
204    W: ByteOutput,
205{
206    impl_write_value!(write_i8, i8, "Writes a ZigZag `i8`.");
207    impl_write_value!(write_i16, i16, "Writes a ZigZag `i16`.");
208    impl_write_value!(write_i32, i32, "Writes a ZigZag `i32`.");
209    impl_write_value!(write_i64, i64, "Writes a ZigZag `i64`.");
210    impl_write_value!(write_i128, i128, "Writes a ZigZag `i128`.");
211    impl_write_value!(write_isize, isize, "Writes a ZigZag `isize`.");
212}
213
214impl<W> Output for BufferedZigZagWriter<W>
215where
216    W: ByteOutput,
217{
218    /// Byte type accepted by this writer's output methods.
219    type Item = u8;
220
221    /// Reports that this adapter buffers output.
222    ///
223    /// # Returns
224    ///
225    /// Always returns `true`.
226    #[inline(always)]
227    fn is_buffered(&self) -> bool {
228        true
229    }
230
231    /// Writes up to `count` bytes from an indexed input range.
232    ///
233    /// # Parameters
234    ///
235    /// - `input`: Source slice.
236    /// - `index`: First source index.
237    /// - `count`: Maximum number of bytes to write.
238    ///
239    /// # Returns
240    ///
241    /// Returns the number of bytes accepted.
242    ///
243    /// # Errors
244    ///
245    /// Returns an output error encountered while draining pending bytes.
246    ///
247    /// # Safety
248    ///
249    /// `index..index + count` must be a valid range within `input`.
250    #[inline(always)]
251    unsafe fn write_unchecked(&mut self, input: &[u8], index: usize, count: usize) -> Result<usize> {
252        // SAFETY: The caller upholds the indexed source range contract.
253        unsafe { self.output.write_unchecked(input, index, count) }
254    }
255
256    /// Flushes the internal buffer and then the wrapped writer.
257    ///
258    /// # Returns
259    ///
260    /// Returns after buffered and wrapped output have flushed.
261    ///
262    /// # Errors
263    ///
264    /// Returns an error encountered while draining or flushing.
265    #[inline(always)]
266    fn flush(&mut self) -> Result<()> {
267        self.output.flush()
268    }
269}
270
271impl<W> Seekable for BufferedZigZagWriter<W>
272where
273    W: SeekableByteOutput,
274{
275    /// Position unit used by this byte-oriented writer.
276    type Unit = u8;
277
278    /// Seeks relative to this writer's logical position.
279    /// For `SeekFrom::Current(0)`, returns the logical position including
280    /// pending bytes without draining them. Other requests drain pending bytes
281    /// before repositioning the wrapped output, but do not flush that output.
282    /// Call [`Self::flush`] explicitly when buffered data and the wrapped
283    /// output must be flushed.
284    ///
285    /// # Parameters
286    ///
287    /// - `position`: Target seek position.
288    ///
289    /// # Returns
290    ///
291    /// Returns the new logical stream position in bytes.
292    ///
293    /// # Errors
294    ///
295    /// Returns an error encountered while draining pending bytes or seeking.
296    #[inline(always)]
297    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
298        self.output.seek(position)
299    }
300}