qubit_io_binary/stream/buffered_binary_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 fixed-width binary values.
10
11use core::marker::PhantomData;
12use std::collections::TryReserveError;
13use std::io::Result;
14use std::io::SeekFrom;
15
16use qubit_codec::BigEndian;
17use qubit_codec::ByteOrder;
18use qubit_codec::ByteOrderSpec;
19use qubit_codec::LittleEndian;
20use qubit_codec::NativeEndian;
21use qubit_codec::TranscodeEncodeOutput;
22use qubit_codec_binary::BinaryCodec;
23use qubit_io::BufferedOutputRecovery;
24use qubit_io::ByteOutput;
25use qubit_io::Output;
26use qubit_io::Seekable;
27use qubit_io::SeekableByteOutput;
28
29use super::internal::TranscodeEncodeOutputExt;
30use crate::util::MIN_CODEC_BUFFER_CAPACITY;
31use crate::util::checked_u16_len;
32use crate::util::checked_u32_len;
33use crate::util::write_all;
34
35/// Buffered writer for fixed-width binary values.
36///
37/// Scalar writes encode directly into the internal output buffer and flush that
38/// buffer to the wrapped writer only when it becomes full or when explicitly
39/// flushed.
40///
41/// # Flush contract
42///
43/// Dropping this writer delegates to `qubit_io::BufferedOutput`, which makes a
44/// best-effort attempt to drain pending bytes, ignores drop-time errors, and
45/// does not guarantee that the wrapped writer itself is flushed. Call
46/// [`Output::flush`] to guarantee that all bytes reach the wrapped output.
47/// [`Self::inner`] can observe the wrapped writer before pending bytes have
48/// been flushed.
49///
50/// # Type Parameters
51///
52/// - `W`: Underlying byte output.
53/// - `O`: Compile-time byte-order specification.
54///
55/// # Examples
56///
57/// ```
58/// use qubit_codec::BigEndian;
59/// use qubit_io_binary::BufferedBinaryWriter;
60///
61/// let mut writer = BufferedBinaryWriter::<_, BigEndian>::new(Vec::new());
62/// writer.write_u16(0x1234)?;
63/// writer.flush()?;
64/// # Ok::<(), std::io::Error>(())
65/// ```
66pub struct BufferedBinaryWriter<W, O = BigEndian>
67where
68 W: ByteOutput,
69{
70 /// Buffered codec output and wrapped writer.
71 output: TranscodeEncodeOutput<W>,
72 /// Associates the selected byte order without storing a value.
73 marker: PhantomData<fn() -> O>,
74}
75
76impl_output_methods!(BufferedBinaryWriter<W, O> where W: ByteOutput);
77impl_seekable_methods!(BufferedBinaryWriter<W, O> where W: SeekableByteOutput);
78
79impl<W, O> BufferedBinaryWriter<W, O>
80where
81 W: ByteOutput,
82 O: ByteOrderSpec,
83{
84 /// Creates a buffered binary writer with the default buffer capacity.
85 ///
86 /// # Parameters
87 ///
88 /// - `inner`: Underlying byte output.
89 ///
90 /// # Returns
91 ///
92 /// Returns a buffered writer using byte order `O`.
93 #[must_use]
94 #[inline]
95 pub fn new(inner: W) -> Self {
96 Self {
97 output: TranscodeEncodeOutput::new(inner),
98 marker: PhantomData,
99 }
100 }
101
102 /// Creates a buffered binary writer with at least `capacity` bytes.
103 ///
104 /// # Parameters
105 ///
106 /// - `inner`: Underlying byte output.
107 /// - `capacity`: Requested internal buffer capacity in bytes.
108 ///
109 /// # Returns
110 ///
111 /// Returns a buffered writer whose capacity also satisfies the largest
112 /// supported codec payload.
113 #[must_use]
114 #[inline]
115 pub fn with_capacity(inner: W, capacity: usize) -> Self {
116 Self {
117 output: TranscodeEncodeOutput::with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY)),
118 marker: PhantomData,
119 }
120 }
121
122 /// Tries to create a buffered binary writer with at least `capacity` bytes.
123 ///
124 /// # Errors
125 ///
126 /// Returns an allocation error when the requested buffer cannot be
127 /// allocated.
128 #[inline]
129 pub fn try_with_capacity(inner: W, capacity: usize) -> std::result::Result<Self, TryReserveError> {
130 Ok(Self {
131 output: TranscodeEncodeOutput::try_with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY))?,
132 marker: PhantomData,
133 })
134 }
135
136 /// Returns the byte order selected by this writer.
137 ///
138 /// # Returns
139 ///
140 /// Returns the compile-time byte order as a runtime value.
141 #[must_use]
142 #[inline(always)]
143 pub const fn byte_order(&self) -> ByteOrder {
144 O::ORDER
145 }
146
147 /// Returns a shared reference to the underlying writer.
148 ///
149 /// Pending bytes may still be held in this wrapper's internal buffer.
150 ///
151 /// # Returns
152 ///
153 /// Returns the wrapped writer.
154 #[must_use]
155 #[inline(always)]
156 pub const fn inner(&self) -> &W {
157 self.output.inner()
158 }
159 /// Recovers the wrapped writer and the status of bytes retained by this
160 /// writer.
161 ///
162 /// This method performs no I/O and does not call [`Self::flush`]. `Pending`
163 /// bytes were not reported as written and may be retried. `Indeterminate`
164 /// means an inner write panicked and may have produced an external prefix;
165 /// do not replay it automatically. Flush first for normal completion.
166 ///
167 /// Pending contains only bytes retained by this buffer. It does not include
168 /// payload bytes that a failed high-level write never accepted. An empty
169 /// pending buffer, or a successful later flush, does not mean that such a
170 /// failed field was completed.
171 ///
172 /// # Returns
173 ///
174 /// Returns the wrapped writer and pending or indeterminate bytes in logical
175 /// write order.
176 #[must_use = "the wrapped writer and recovery status must be handled"]
177 #[inline(always)]
178 pub fn into_parts(self) -> (W, BufferedOutputRecovery<u8>) {
179 self.output.into_parts()
180 }
181}
182
183macro_rules! impl_value_write {
184 ($order:ty, $method:ident, $ty:ty, $doc:literal) => {
185 #[doc = $doc]
186 #[doc = ""]
187 #[doc = "# Parameters"]
188 #[doc = ""]
189 #[doc = "- `value`: Scalar to encode and buffer."]
190 #[doc = ""]
191 #[doc = "# Returns"]
192 #[doc = ""]
193 #[doc = "Returns after the encoded bytes have been accepted."]
194 #[doc = ""]
195 #[doc = "# Errors"]
196 #[doc = ""]
197 #[doc = "Returns an output error encountered while making buffer \
198 space."]
199 #[inline(always)]
200 pub fn $method(&mut self, value: $ty) -> Result<()> {
201 type Codec = BinaryCodec<$ty, $order>;
202
203 self.output.write_encoded::<Codec>(value)
204 }
205 };
206}
207
208macro_rules! impl_for_order {
209 ($order:ty) => {
210 impl<W> BufferedBinaryWriter<W, $order>
211 where
212 W: ByteOutput,
213 {
214 impl_value_write!($order, write_u8, u8, "Writes an unsigned 8-bit integer.");
215 impl_value_write!($order, write_i8, i8, "Writes a signed 8-bit integer.");
216 impl_value_write!($order, write_u16, u16, "Writes an unsigned 16-bit integer.");
217 impl_value_write!($order, write_u32, u32, "Writes an unsigned 32-bit integer.");
218 impl_value_write!($order, write_u64, u64, "Writes an unsigned 64-bit integer.");
219 impl_value_write!($order, write_u128, u128, "Writes an unsigned 128-bit integer.");
220 impl_value_write!($order, write_i16, i16, "Writes a signed 16-bit integer.");
221 impl_value_write!($order, write_i32, i32, "Writes a signed 32-bit integer.");
222 impl_value_write!($order, write_i64, i64, "Writes a signed 64-bit integer.");
223 impl_value_write!($order, write_i128, i128, "Writes a signed 128-bit integer.");
224 impl_value_write!($order, write_f32, f32, "Writes a 32-bit float.");
225 impl_value_write!($order, write_f64, f64, "Writes a 64-bit float.");
226
227 /// Writes a UTF-8 string prefixed by a `u16` byte length.
228 ///
229 /// # Errors
230 ///
231 /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8
232 /// byte length does not fit `u16`, or an output error.
233 ///
234 /// # Partial writes
235 ///
236 /// This operation is not transactional. An I/O error may leave the length
237 /// prefix and part of the payload retained by this writer or already
238 /// accepted by the wrapped output. Retrying
239 /// this whole method can write a second prefix; recover using the enclosing
240 /// protocol's framing or transaction boundary instead.
241 pub fn write_string_with_u16_len(&mut self, value: &str) -> Result<()> {
242 self.write_u16(checked_u16_len(value.len())?)?;
243 write_all(self, value.as_bytes())
244 }
245
246 /// Writes a UTF-8 string prefixed by a `u32` byte length.
247 ///
248 /// # Errors
249 ///
250 /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8
251 /// byte length does not fit `u32`, or an output error.
252 ///
253 /// # Partial writes
254 ///
255 /// This operation is not transactional. An I/O error may leave the length
256 /// prefix and part of the payload retained by this writer or already
257 /// accepted by the wrapped output. Retrying
258 /// this whole method can write a second prefix; recover using the enclosing
259 /// protocol's framing or transaction boundary instead.
260 pub fn write_string_with_u32_len(&mut self, value: &str) -> Result<()> {
261 self.write_u32(checked_u32_len(value.len())?)?;
262 write_all(self, value.as_bytes())
263 }
264 }
265 };
266}
267
268impl_for_order!(BigEndian);
269impl_for_order!(LittleEndian);
270impl_for_order!(NativeEndian);
271
272impl<W, O> Output for BufferedBinaryWriter<W, O>
273where
274 W: ByteOutput,
275{
276 type Item = u8;
277
278 /// Reports that this adapter buffers output.
279 ///
280 /// # Returns
281 ///
282 /// Always returns `true`.
283 #[inline(always)]
284 fn is_buffered(&self) -> bool {
285 true
286 }
287
288 /// Writes up to `count` bytes from an indexed input range.
289 ///
290 /// # Parameters
291 ///
292 /// - `input`: Source slice.
293 /// - `index`: First source index.
294 /// - `count`: Maximum number of bytes to write.
295 ///
296 /// # Returns
297 ///
298 /// Returns the number of bytes accepted.
299 ///
300 /// # Errors
301 ///
302 /// Returns an output error encountered while draining pending bytes.
303 ///
304 /// # Safety
305 ///
306 /// `index..index + count` must be a valid range within `input`.
307 #[inline(always)]
308 unsafe fn write_unchecked(&mut self, input: &[u8], index: usize, count: usize) -> Result<usize> {
309 // SAFETY: The caller upholds the indexed source range contract.
310 unsafe { self.output.write_unchecked(input, index, count) }
311 }
312
313 /// Flushes the internal buffer and then the wrapped writer.
314 ///
315 /// # Returns
316 ///
317 /// Returns after buffered and wrapped output have flushed.
318 ///
319 /// # Errors
320 ///
321 /// Returns an error encountered while draining or flushing.
322 #[inline(always)]
323 fn flush(&mut self) -> Result<()> {
324 self.output.flush()
325 }
326}
327
328impl<W, O> Seekable for BufferedBinaryWriter<W, O>
329where
330 W: SeekableByteOutput,
331{
332 type Unit = u8;
333
334 /// Seeks relative to this writer's logical position.
335 /// For `SeekFrom::Current(0)`, returns the logical position including
336 /// pending bytes without draining them. Other requests drain pending bytes
337 /// before repositioning the wrapped output, but do not flush that output.
338 /// Call [`Self::flush`] explicitly when buffered data and the wrapped
339 /// output must be flushed.
340 ///
341 /// # Parameters
342 ///
343 /// - `position`: Target seek position.
344 ///
345 /// # Returns
346 ///
347 /// Returns the new logical stream position in bytes.
348 ///
349 /// # Errors
350 ///
351 /// Returns an error encountered while draining pending bytes or seeking.
352 #[inline(always)]
353 fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
354 self.output.seek(position)
355 }
356}