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