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