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