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