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