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