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