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