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