Skip to main content

qubit_io_binary/stream/
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//! Writer for fixed-width binary values.
10
11use core::marker::PhantomData;
12use std::io::Result;
13use std::io::SeekFrom;
14
15use qubit_codec::BigEndian;
16use qubit_codec::ByteOrder;
17use qubit_codec::ByteOrderSpec;
18use qubit_codec::LittleEndian;
19use qubit_codec::NativeEndian;
20use qubit_codec_binary::BinaryCodec;
21use qubit_io::ByteOutput;
22use qubit_io::Output;
23use qubit_io::Seekable;
24use qubit_io::SeekableByteOutput;
25
26use crate::util::checked_u16_len;
27use crate::util::checked_u32_len;
28use crate::util::encode_infallible_unchecked;
29use crate::util::write_all;
30
31/// Writer wrapper for fixed-width binary values.
32///
33/// The byte order is selected by the `O` type parameter. Use
34/// `BinaryWriter<W, BigEndian>` for big-endian data and
35/// `BinaryWriter<W, LittleEndian>` for little-endian data.
36///
37/// # Type Parameters
38///
39/// - `W`: Underlying byte output.
40/// - `O`: Compile-time byte-order specification.
41///
42/// # Partial writes
43///
44/// These methods are not transactional. An output error may occur after the
45/// output has accepted a byte prefix of the encoded value, and those bytes are
46/// not rolled back. Calling a method again encodes the entire value from the
47/// output's current position and may duplicate that prefix. Recovery requires
48/// outer framing, a trusted seek or rollback strategy, or a transactional
49/// transport. Output acceptance does not imply durable persistence.
50///
51/// # Examples
52///
53/// ```
54/// use qubit_codec::LittleEndian;
55/// use qubit_io_binary::BinaryWriter;
56///
57/// let mut writer = BinaryWriter::<_, LittleEndian>::new(Vec::new());
58/// writer.write_u16(0x1234).expect("value should encode");
59/// assert_eq!(vec![0x34, 0x12], writer.into_inner());
60/// ```
61pub struct BinaryWriter<W, O = BigEndian> {
62    /// Wrapped byte output.
63    inner: W,
64    /// Scratch storage for the largest fixed-width scalar.
65    buffer: [u8; 16],
66    /// Associates the selected byte order without storing a value.
67    marker: PhantomData<fn() -> O>,
68}
69
70impl<W, O> BinaryWriter<W, O>
71where
72    O: ByteOrderSpec,
73{
74    /// Creates a binary writer.
75    ///
76    /// # Parameters
77    ///
78    /// - `inner`: Underlying byte writer.
79    ///
80    /// # Returns
81    ///
82    /// Returns a writer using the byte order selected by `O`.
83    #[must_use]
84    #[inline]
85    pub const fn new(inner: W) -> Self {
86        Self {
87            inner,
88            buffer: [0; 16],
89            marker: PhantomData,
90        }
91    }
92
93    /// Returns the byte order selected by this writer.
94    ///
95    /// # Returns
96    ///
97    /// Returns the compile-time byte order as a runtime value.
98    #[must_use]
99    #[inline(always)]
100    pub const fn byte_order(&self) -> ByteOrder {
101        O::ORDER
102    }
103
104    /// Returns a shared reference to the underlying writer.
105    ///
106    /// # Returns
107    ///
108    /// Returns the wrapped writer.
109    #[must_use]
110    #[inline(always)]
111    pub const fn inner(&self) -> &W {
112        &self.inner
113    }
114
115    /// Returns an exclusive reference to the underlying writer.
116    ///
117    /// # Returns
118    ///
119    /// Returns mutable access to the wrapped writer.
120    #[must_use]
121    #[inline(always)]
122    pub fn inner_mut(&mut self) -> &mut W {
123        &mut self.inner
124    }
125
126    /// Consumes this wrapper and returns the underlying writer.
127    ///
128    /// # Returns
129    ///
130    /// Returns the wrapped writer.
131    #[must_use]
132    #[inline(always)]
133    pub fn into_inner(self) -> W {
134        self.inner
135    }
136}
137
138macro_rules! impl_value_write {
139    ($order:ty, $method:ident, $ty:ty, $doc:literal) => {
140        #[doc = $doc]
141        #[doc = ""]
142        #[doc = "# Parameters"]
143        #[doc = ""]
144        #[doc = "- `value`: Scalar to encode and write."]
145        #[doc = ""]
146        #[doc = "# Returns"]
147        #[doc = ""]
148        #[doc = "Returns after all encoded bytes have been written."]
149        #[doc = ""]
150        #[doc = "# Errors"]
151        #[doc = ""]
152        #[doc = "Returns an output error, including a write-zero error when \
153                 the output stops making progress."]
154        #[inline]
155        pub fn $method(&mut self, value: $ty) -> Result<()> {
156            type Codec = BinaryCodec<$ty, $order>;
157
158            const LEN: usize = Codec::MAX_ENCODE_UNITS_PER_VALUE;
159            // SAFETY: `LEN` is declared by the codec and fits the fixed
160            // internal buffer.
161            unsafe {
162                let _ = encode_infallible_unchecked::<Codec>(value, &mut self.buffer, 0);
163            }
164            write_all(&mut self.inner, &self.buffer[..LEN])
165        }
166    };
167}
168
169macro_rules! impl_for_order {
170    ($order:ty) => {
171        impl<W> BinaryWriter<W, $order>
172        where
173            W: ByteOutput,
174        {
175            impl_value_write!($order, write_u8, u8, "Writes an unsigned 8-bit integer.");
176            impl_value_write!($order, write_i8, i8, "Writes a signed 8-bit integer.");
177            impl_value_write!($order, write_u16, u16, "Writes an unsigned 16-bit integer.");
178            impl_value_write!($order, write_u32, u32, "Writes an unsigned 32-bit integer.");
179            impl_value_write!($order, write_u64, u64, "Writes an unsigned 64-bit integer.");
180            impl_value_write!($order, write_u128, u128, "Writes an unsigned 128-bit integer.");
181            impl_value_write!($order, write_i16, i16, "Writes a signed 16-bit integer.");
182            impl_value_write!($order, write_i32, i32, "Writes a signed 32-bit integer.");
183            impl_value_write!($order, write_i64, i64, "Writes a signed 64-bit integer.");
184            impl_value_write!($order, write_i128, i128, "Writes a signed 128-bit integer.");
185            impl_value_write!($order, write_f32, f32, "Writes a 32-bit float.");
186            impl_value_write!($order, write_f64, f64, "Writes a 64-bit float.");
187
188            /// Writes a UTF-8 string prefixed by a 16-bit byte length.
189            ///
190            /// # Parameters
191            ///
192            /// - `value`: String to length-prefix and write.
193            ///
194            /// # Returns
195            ///
196            /// Returns after the length and payload have been written.
197            ///
198            /// # Errors
199            ///
200            /// Returns an invalid-input error when the length exceeds
201            /// `u16::MAX`, or an output error while writing.
202            ///
203            /// # Partial writes
204            ///
205            /// This operation is not transactional. An I/O error may leave the length
206            /// prefix and part of the payload already accepted by the output. Retrying
207            /// this whole method can write a second prefix; recover using the enclosing
208            /// protocol's framing or transaction boundary instead.
209            #[inline]
210            pub fn write_string_with_u16_len(&mut self, value: &str) -> Result<()> {
211                self.write_u16(checked_u16_len(value.len())?)?;
212                let bytes = value.as_bytes();
213                write_all(&mut self.inner, bytes)
214            }
215
216            /// Writes a UTF-8 string prefixed by a 32-bit byte length.
217            ///
218            /// # Parameters
219            ///
220            /// - `value`: String to length-prefix and write.
221            ///
222            /// # Returns
223            ///
224            /// Returns after the length and payload have been written.
225            ///
226            /// # Errors
227            ///
228            /// Returns an invalid-input error when the length exceeds
229            /// `u32::MAX`, or an output error while writing.
230            ///
231            /// # Partial writes
232            ///
233            /// This operation is not transactional. An I/O error may leave the length
234            /// prefix and part of the payload already accepted by the output. Retrying
235            /// this whole method can write a second prefix; recover using the enclosing
236            /// protocol's framing or transaction boundary instead.
237            #[inline]
238            pub fn write_string_with_u32_len(&mut self, value: &str) -> Result<()> {
239                self.write_u32(checked_u32_len(value.len())?)?;
240                let bytes = value.as_bytes();
241                write_all(&mut self.inner, bytes)
242            }
243        }
244    };
245}
246
247impl_for_order!(BigEndian);
248impl_for_order!(LittleEndian);
249impl_for_order!(NativeEndian);
250
251impl<W, O> Output for BinaryWriter<W, O>
252where
253    W: ByteOutput,
254{
255    /// Byte units accepted and emitted by this writer.
256    type Item = u8;
257
258    /// Reports whether the wrapped output is buffered.
259    ///
260    /// # Returns
261    ///
262    /// Returns the wrapped output's buffering state.
263    #[inline(always)]
264    fn is_buffered(&self) -> bool {
265        self.inner.is_buffered()
266    }
267
268    /// Writes up to `count` bytes from an indexed input range.
269    ///
270    /// # Parameters
271    ///
272    /// - `input`: Source slice.
273    /// - `index`: First source index.
274    /// - `count`: Maximum number of bytes to write.
275    ///
276    /// # Returns
277    ///
278    /// Returns the number of bytes written.
279    ///
280    /// # Errors
281    ///
282    /// Returns an error reported by the wrapped output.
283    ///
284    /// # Safety
285    ///
286    /// `index..index + count` must be a valid range within `input`.
287    #[inline(always)]
288    unsafe fn write_unchecked(&mut self, input: &[u8], index: usize, count: usize) -> Result<usize> {
289        // SAFETY: The caller upholds the same indexed range contract required
290        // by the wrapped output.
291        unsafe { self.inner.write_unchecked(input, index, count) }
292    }
293
294    /// Flushes the wrapped writer.
295    ///
296    /// # Returns
297    ///
298    /// Returns after the wrapped output has flushed.
299    ///
300    /// # Errors
301    ///
302    /// Returns the I/O error reported by the wrapped writer.
303    #[inline(always)]
304    fn flush(&mut self) -> Result<()> {
305        Output::flush(&mut self.inner)
306    }
307}
308
309impl<W, O> Seekable for BinaryWriter<W, O>
310where
311    W: SeekableByteOutput,
312{
313    /// Byte units used to measure seek positions in the wrapped output.
314    type Unit = u8;
315
316    /// Seeks the wrapped writer.
317    ///
318    /// # Parameters
319    ///
320    /// - `position`: Target seek position.
321    ///
322    /// # Returns
323    ///
324    /// Returns the new stream position.
325    ///
326    /// # Errors
327    ///
328    /// Returns the seek error reported by the wrapped writer.
329    #[inline(always)]
330    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
331        self.inner.seek_to(position)
332    }
333}
334
335impl_output_methods!(BinaryWriter<W, O> where W: ByteOutput);
336impl_seekable_methods!(BinaryWriter<W, O> where W: SeekableByteOutput);