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 crate::util::MIN_CODEC_BUFFER_CAPACITY;
28use crate::util::checked_u16_len;
29use crate::util::checked_u32_len;
30use crate::util::write_all;
31use super::internal::TranscodeEncodeOutputExt;
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(
101 inner,
102 capacity.max(MIN_CODEC_BUFFER_CAPACITY),
103 ),
104 marker: PhantomData,
105 }
106 }
107
108 /// Tries to create a buffered binary writer with at least `capacity` bytes.
109 ///
110 /// # Errors
111 ///
112 /// Returns an allocation error when the requested buffer cannot be
113 /// allocated.
114 #[inline]
115 pub fn try_with_capacity(
116 inner: W,
117 capacity: usize,
118 ) -> std::result::Result<Self, TryReserveError> {
119 Ok(Self {
120 output: TranscodeEncodeOutput::try_with_capacity(
121 inner,
122 capacity.max(MIN_CODEC_BUFFER_CAPACITY),
123 )?,
124 marker: PhantomData,
125 })
126 }
127
128 /// Returns the byte order selected by this writer.
129 ///
130 /// # Returns
131 ///
132 /// Returns the compile-time byte order as a runtime value.
133 #[must_use]
134 #[inline(always)]
135 pub const fn byte_order(&self) -> ByteOrder {
136 O::ORDER
137 }
138
139 /// Returns a shared reference to the underlying writer.
140 ///
141 /// Pending bytes may still be held in this wrapper's internal buffer.
142 ///
143 /// # Returns
144 ///
145 /// Returns the wrapped writer.
146 #[must_use]
147 #[inline(always)]
148 pub const fn inner(&self) -> &W {
149 self.output.inner()
150 }
151
152 /// This method does not call [`Self::flush`] and performs no I/O. Pending
153 /// bytes in the returned buffer have already been accepted by this writer
154 /// but have not reached the returned writer. To complete a stream normally,
155 /// call [`Self::flush`] first; a successful flush leaves the returned
156 /// buffer empty.
157 ///
158 /// # Returns
159 ///
160 /// Returns the wrapped writer and pending bytes in logical write order.
161 #[must_use = "the returned inner writer and pending buffer must be handled"]
162 #[inline(always)]
163 pub fn into_parts(self) -> (W, Buffer<u8>) {
164 self.output.into_parts()
165 }
166}
167
168macro_rules! impl_value_write {
169 ($order:ty, $method:ident, $ty:ty, $doc:literal) => {
170 #[doc = $doc]
171 #[doc = ""]
172 #[doc = "# Parameters"]
173 #[doc = ""]
174 #[doc = "- `value`: Scalar to encode and buffer."]
175 #[doc = ""]
176 #[doc = "# Returns"]
177 #[doc = ""]
178 #[doc = "Returns after the encoded bytes have been accepted."]
179 #[doc = ""]
180 #[doc = "# Errors"]
181 #[doc = ""]
182 #[doc = "Returns an output error encountered while making buffer \
183 space."]
184 #[inline(always)]
185 pub fn $method(&mut self, value: $ty) -> Result<()> {
186 type Codec = BinaryCodec<$ty, $order>;
187
188 self.output.write_encoded::<Codec>(value)
189 }
190 };
191}
192
193macro_rules! impl_for_order {
194 ($order:ty) => {
195 impl<W> BufferedBinaryWriter<W, $order>
196 where
197 W: Output<Item = u8>,
198 {
199 impl_value_write!(
200 $order,
201 write_u8,
202 u8,
203 "Writes an unsigned 8-bit integer."
204 );
205 impl_value_write!(
206 $order,
207 write_i8,
208 i8,
209 "Writes a signed 8-bit integer."
210 );
211 impl_value_write!(
212 $order,
213 write_u16,
214 u16,
215 "Writes an unsigned 16-bit integer."
216 );
217 impl_value_write!(
218 $order,
219 write_u32,
220 u32,
221 "Writes an unsigned 32-bit integer."
222 );
223 impl_value_write!(
224 $order,
225 write_u64,
226 u64,
227 "Writes an unsigned 64-bit integer."
228 );
229 impl_value_write!(
230 $order,
231 write_u128,
232 u128,
233 "Writes an unsigned 128-bit integer."
234 );
235 impl_value_write!(
236 $order,
237 write_i16,
238 i16,
239 "Writes a signed 16-bit integer."
240 );
241 impl_value_write!(
242 $order,
243 write_i32,
244 i32,
245 "Writes a signed 32-bit integer."
246 );
247 impl_value_write!(
248 $order,
249 write_i64,
250 i64,
251 "Writes a signed 64-bit integer."
252 );
253 impl_value_write!(
254 $order,
255 write_i128,
256 i128,
257 "Writes a signed 128-bit integer."
258 );
259 impl_value_write!($order, write_f32, f32, "Writes a 32-bit float.");
260 impl_value_write!($order, write_f64, f64, "Writes a 64-bit float.");
261
262 /// Writes a UTF-8 string prefixed by a `u16` byte length.
263 ///
264 /// # Errors
265 ///
266 /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8
267 /// byte length does not fit `u16`, or an output error.
268 pub fn write_string_with_u16_len(
269 &mut self,
270 value: &str,
271 ) -> Result<()> {
272 self.write_u16(checked_u16_len(value.len())?)?;
273 write_all(self, value.as_bytes())
274 }
275
276 /// Writes a UTF-8 string prefixed by a `u32` byte length.
277 ///
278 /// # Errors
279 ///
280 /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8
281 /// byte length does not fit `u32`, or an output error.
282 pub fn write_string_with_u32_len(
283 &mut self,
284 value: &str,
285 ) -> Result<()> {
286 self.write_u32(checked_u32_len(value.len())?)?;
287 write_all(self, value.as_bytes())
288 }
289 }
290 };
291}
292
293impl_for_order!(BigEndian);
294impl_for_order!(LittleEndian);
295impl_for_order!(NativeEndian);
296
297impl<W, O> Output for BufferedBinaryWriter<W, O>
298where
299 W: Output<Item = u8>,
300{
301 type Item = u8;
302
303 /// Reports that this adapter buffers output.
304 ///
305 /// # Returns
306 ///
307 /// Always returns `true`.
308 #[inline(always)]
309 fn is_buffered(&self) -> bool {
310 true
311 }
312
313 /// Writes up to `count` bytes from an indexed input range.
314 ///
315 /// # Parameters
316 ///
317 /// - `input`: Source slice.
318 /// - `index`: First source index.
319 /// - `count`: Maximum number of bytes to write.
320 ///
321 /// # Returns
322 ///
323 /// Returns the number of bytes accepted.
324 ///
325 /// # Errors
326 ///
327 /// Returns an output error encountered while draining pending bytes.
328 ///
329 /// # Safety
330 ///
331 /// `index..index + count` must be a valid range within `input`.
332 #[inline(always)]
333 unsafe fn write_unchecked(
334 &mut self,
335 input: &[u8],
336 index: usize,
337 count: usize,
338 ) -> Result<usize> {
339 // SAFETY: The caller upholds the indexed source range contract.
340 unsafe { self.output.write_unchecked(input, index, count) }
341 }
342
343 /// Flushes the internal buffer and then the wrapped writer.
344 ///
345 /// # Returns
346 ///
347 /// Returns after buffered and wrapped output have flushed.
348 ///
349 /// # Errors
350 ///
351 /// Returns an error encountered while draining or flushing.
352 #[inline(always)]
353 fn flush(&mut self) -> Result<()> {
354 self.output.flush()
355 }
356}
357
358impl<W, O> Seekable for BufferedBinaryWriter<W, O>
359where
360 W: Output<Item = u8> + Seekable<Unit = u8>,
361{
362 type Unit = u8;
363
364 /// Flushes pending bytes before seeking the wrapped writer.
365 ///
366 /// # Parameters
367 ///
368 /// - `position`: Target seek position.
369 ///
370 /// # Returns
371 ///
372 /// Returns the new physical stream position.
373 ///
374 /// # Errors
375 ///
376 /// Returns an error encountered while flushing or seeking.
377 #[inline(always)]
378 fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
379 self.output.seek(position)
380 }
381}