Skip to main content

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    /// # Parameters
125    ///
126    /// - `inner`: Underlying byte output to wrap.
127    /// - `capacity`: Requested internal buffer capacity in bytes. The request
128    ///   is raised when necessary to fit the largest supported codec payload.
129    ///
130    /// # Returns
131    ///
132    /// Returns a buffered writer on successful allocation. Its capacity
133    /// satisfies both the request and the minimum required by the supported
134    /// codecs.
135    ///
136    /// # Errors
137    ///
138    /// Returns a [`TryReserveError`] if the buffer capacity overflows or its
139    /// allocation fails.
140    #[inline]
141    pub fn try_with_capacity(inner: W, capacity: usize) -> std::result::Result<Self, TryReserveError> {
142        Ok(Self {
143            output: TranscodeEncodeOutput::try_with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY))?,
144            marker: PhantomData,
145        })
146    }
147
148    /// Returns the byte order selected by this writer.
149    ///
150    /// # Returns
151    ///
152    /// Returns the compile-time byte order as a runtime value.
153    #[must_use]
154    #[inline(always)]
155    pub const fn byte_order(&self) -> ByteOrder {
156        O::ORDER
157    }
158
159    /// Returns a shared reference to the underlying writer.
160    ///
161    /// Pending bytes may still be held in this wrapper's internal buffer.
162    ///
163    /// # Returns
164    ///
165    /// Returns the wrapped writer.
166    #[must_use]
167    #[inline(always)]
168    pub const fn inner(&self) -> &W {
169        self.output.inner()
170    }
171    /// Recovers the wrapped writer and the status of bytes retained by this
172    /// writer.
173    ///
174    /// This method performs no I/O and does not call [`Self::flush`]. `Pending`
175    /// bytes were not reported as written and may be retried. `Indeterminate`
176    /// means an inner write panicked and may have produced an external prefix;
177    /// do not replay it automatically. Flush first for normal completion.
178    ///
179    /// Pending contains only bytes retained by this buffer. It does not include
180    /// payload bytes that a failed high-level write never accepted. An empty
181    /// pending buffer, or a successful later flush, does not mean that such a
182    /// failed field was completed.
183    ///
184    /// # Returns
185    ///
186    /// Returns the wrapped writer and pending or indeterminate bytes in logical
187    /// write order.
188    #[must_use = "the wrapped writer and recovery status must be handled"]
189    #[inline(always)]
190    pub fn into_parts(self) -> (W, BufferedOutputRecovery<u8>) {
191        self.output.into_parts()
192    }
193}
194
195macro_rules! impl_value_write {
196    ($order:ty, $method:ident, $ty:ty, $doc:literal) => {
197        #[doc = $doc]
198        #[doc = ""]
199        #[doc = "# Parameters"]
200        #[doc = ""]
201        #[doc = "- `value`: Scalar to encode and buffer."]
202        #[doc = ""]
203        #[doc = "# Returns"]
204        #[doc = ""]
205        #[doc = "Returns after the encoded bytes have been accepted."]
206        #[doc = ""]
207        #[doc = "# Errors"]
208        #[doc = ""]
209        #[doc = "Returns an output error encountered while making buffer \
210                 space."]
211        #[inline(always)]
212        pub fn $method(&mut self, value: $ty) -> Result<()> {
213            type Codec = BinaryCodec<$ty, $order>;
214
215            self.output.write_encoded::<Codec>(value)
216        }
217    };
218}
219
220macro_rules! impl_for_order {
221    ($order:ty) => {
222        impl<W> BufferedBinaryWriter<W, $order>
223        where
224            W: ByteOutput,
225        {
226            impl_value_write!($order, write_u8, u8, "Writes an unsigned 8-bit integer.");
227            impl_value_write!($order, write_i8, i8, "Writes a signed 8-bit integer.");
228            impl_value_write!($order, write_u16, u16, "Writes an unsigned 16-bit integer.");
229            impl_value_write!($order, write_u32, u32, "Writes an unsigned 32-bit integer.");
230            impl_value_write!($order, write_u64, u64, "Writes an unsigned 64-bit integer.");
231            impl_value_write!($order, write_u128, u128, "Writes an unsigned 128-bit integer.");
232            impl_value_write!($order, write_i16, i16, "Writes a signed 16-bit integer.");
233            impl_value_write!($order, write_i32, i32, "Writes a signed 32-bit integer.");
234            impl_value_write!($order, write_i64, i64, "Writes a signed 64-bit integer.");
235            impl_value_write!($order, write_i128, i128, "Writes a signed 128-bit integer.");
236            impl_value_write!($order, write_f32, f32, "Writes a 32-bit float.");
237            impl_value_write!($order, write_f64, f64, "Writes a 64-bit float.");
238
239            /// Writes a UTF-8 string prefixed by a `u16` byte length.
240            ///
241            /// # Errors
242            ///
243            /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8
244            /// byte length does not fit `u16`, or an output error.
245            ///
246            /// # Returns
247            ///
248            /// Returns `()` after the length prefix and string bytes are accepted.
249            ///
250            /// # Partial writes
251            ///
252            /// This operation is not transactional. An I/O error may leave the length
253            /// prefix and part of the payload retained by this writer or already
254            /// accepted by the wrapped output. Retrying
255            /// this whole method can write a second prefix; recover using the enclosing
256            /// protocol's framing or transaction boundary instead.
257            pub fn write_string_with_u16_len(&mut self, value: &str) -> Result<()> {
258                self.write_u16(checked_u16_len(value.len())?)?;
259                write_all(self, value.as_bytes())
260            }
261
262            /// Writes a UTF-8 string prefixed by a `u32` byte length.
263            ///
264            /// # Errors
265            ///
266            /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8
267            /// byte length does not fit `u32`, or an output error.
268            ///
269            /// # Returns
270            ///
271            /// Returns `()` after the length prefix and string bytes are accepted.
272            ///
273            /// # Partial writes
274            ///
275            /// This operation is not transactional. An I/O error may leave the length
276            /// prefix and part of the payload retained by this writer or already
277            /// accepted by the wrapped output. Retrying
278            /// this whole method can write a second prefix; recover using the enclosing
279            /// protocol's framing or transaction boundary instead.
280            pub fn write_string_with_u32_len(&mut self, value: &str) -> Result<()> {
281                self.write_u32(checked_u32_len(value.len())?)?;
282                write_all(self, value.as_bytes())
283            }
284        }
285    };
286}
287
288impl_for_order!(BigEndian);
289impl_for_order!(LittleEndian);
290impl_for_order!(NativeEndian);
291
292impl<W, O> Output for BufferedBinaryWriter<W, O>
293where
294    W: ByteOutput,
295{
296    /// The smallest unit accepted by this byte-oriented output adapter.
297    type Item = u8;
298
299    /// Reports that this adapter buffers output.
300    ///
301    /// # Returns
302    ///
303    /// Always returns `true`.
304    #[inline(always)]
305    fn is_buffered(&self) -> bool {
306        true
307    }
308
309    /// Writes up to `count` bytes from an indexed input range.
310    ///
311    /// # Parameters
312    ///
313    /// - `input`: Source slice.
314    /// - `index`: First source index.
315    /// - `count`: Maximum number of bytes to write.
316    ///
317    /// # Returns
318    ///
319    /// Returns the number of bytes accepted.
320    ///
321    /// # Errors
322    ///
323    /// Returns an output error encountered while draining pending bytes.
324    ///
325    /// # Safety
326    ///
327    /// `index..index + count` must be a valid range within `input`.
328    #[inline(always)]
329    unsafe fn write_unchecked(&mut self, input: &[u8], index: usize, count: usize) -> Result<usize> {
330        // SAFETY: The caller upholds the indexed source range contract.
331        unsafe { self.output.write_unchecked(input, index, count) }
332    }
333
334    /// Flushes the internal buffer and then the wrapped writer.
335    ///
336    /// # Returns
337    ///
338    /// Returns after buffered and wrapped output have flushed.
339    ///
340    /// # Errors
341    ///
342    /// Returns an error encountered while draining or flushing.
343    #[inline(always)]
344    fn flush(&mut self) -> Result<()> {
345        self.output.flush()
346    }
347}
348
349impl<W, O> Seekable for BufferedBinaryWriter<W, O>
350where
351    W: SeekableByteOutput,
352{
353    /// The unit used for positions in this seekable byte stream.
354    type Unit = u8;
355
356    /// Seeks relative to this writer's logical position.
357    /// For `SeekFrom::Current(0)`, returns the logical position including
358    /// pending bytes without draining them. Other requests drain pending bytes
359    /// before repositioning the wrapped output, but do not flush that output.
360    /// Call [`Self::flush`] explicitly when buffered data and the wrapped
361    /// output must be flushed.
362    ///
363    /// # Parameters
364    ///
365    /// - `position`: Target seek position.
366    ///
367    /// # Returns
368    ///
369    /// Returns the new logical stream position in bytes.
370    ///
371    /// # Errors
372    ///
373    /// Returns an error encountered while draining pending bytes or seeking.
374    #[inline(always)]
375    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
376        self.output.seek(position)
377    }
378}