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>(
141 value,
142 &mut self.buffer,
143 0,
144 );
145 }
146 write_all(&mut self.inner, &self.buffer[..LEN])
147 }
148 };
149}
150
151macro_rules! impl_for_order {
152 ($order:ty) => {
153 impl<W> BinaryWriter<W, $order>
154 where
155 W: Output<Item = u8>,
156 {
157 impl_value_write!(
158 $order,
159 write_u8,
160 u8,
161 "Writes an unsigned 8-bit integer."
162 );
163 impl_value_write!(
164 $order,
165 write_i8,
166 i8,
167 "Writes a signed 8-bit integer."
168 );
169 impl_value_write!(
170 $order,
171 write_u16,
172 u16,
173 "Writes an unsigned 16-bit integer."
174 );
175 impl_value_write!(
176 $order,
177 write_u32,
178 u32,
179 "Writes an unsigned 32-bit integer."
180 );
181 impl_value_write!(
182 $order,
183 write_u64,
184 u64,
185 "Writes an unsigned 64-bit integer."
186 );
187 impl_value_write!(
188 $order,
189 write_u128,
190 u128,
191 "Writes an unsigned 128-bit integer."
192 );
193 impl_value_write!(
194 $order,
195 write_i16,
196 i16,
197 "Writes a signed 16-bit integer."
198 );
199 impl_value_write!(
200 $order,
201 write_i32,
202 i32,
203 "Writes a signed 32-bit integer."
204 );
205 impl_value_write!(
206 $order,
207 write_i64,
208 i64,
209 "Writes a signed 64-bit integer."
210 );
211 impl_value_write!(
212 $order,
213 write_i128,
214 i128,
215 "Writes a signed 128-bit integer."
216 );
217 impl_value_write!($order, write_f32, f32, "Writes a 32-bit float.");
218 impl_value_write!($order, write_f64, f64, "Writes a 64-bit float.");
219
220 /// Writes a UTF-8 string prefixed by a 16-bit byte length.
221 ///
222 /// # Parameters
223 ///
224 /// - `value`: String to length-prefix and write.
225 ///
226 /// # Returns
227 ///
228 /// Returns after the length and payload have been written.
229 ///
230 /// # Errors
231 ///
232 /// Returns an invalid-input error when the length exceeds
233 /// `u16::MAX`, or an output error while writing.
234 #[inline]
235 pub fn write_string_with_u16_len(
236 &mut self,
237 value: &str,
238 ) -> Result<()> {
239 self.write_u16(checked_u16_len(value.len())?)?;
240 let bytes = value.as_bytes();
241 write_all(&mut self.inner, bytes)
242 }
243
244 /// Writes a UTF-8 string prefixed by a 32-bit byte length.
245 ///
246 /// # Parameters
247 ///
248 /// - `value`: String to length-prefix and write.
249 ///
250 /// # Returns
251 ///
252 /// Returns after the length and payload have been written.
253 ///
254 /// # Errors
255 ///
256 /// Returns an invalid-input error when the length exceeds
257 /// `u32::MAX`, or an output error while writing.
258 #[inline]
259 pub fn write_string_with_u32_len(
260 &mut self,
261 value: &str,
262 ) -> Result<()> {
263 self.write_u32(checked_u32_len(value.len())?)?;
264 let bytes = value.as_bytes();
265 write_all(&mut self.inner, bytes)
266 }
267 }
268 };
269}
270
271impl_for_order!(BigEndian);
272impl_for_order!(LittleEndian);
273impl_for_order!(NativeEndian);
274
275impl<W, O> Output for BinaryWriter<W, O>
276where
277 W: Output<Item = u8>,
278{
279 type Item = u8;
280
281 /// Reports whether the wrapped output is buffered.
282 ///
283 /// # Returns
284 ///
285 /// Returns the wrapped output's buffering state.
286 #[inline(always)]
287 fn is_buffered(&self) -> bool {
288 self.inner.is_buffered()
289 }
290
291 /// Writes up to `count` bytes from an indexed input range.
292 ///
293 /// # Parameters
294 ///
295 /// - `input`: Source slice.
296 /// - `index`: First source index.
297 /// - `count`: Maximum number of bytes to write.
298 ///
299 /// # Returns
300 ///
301 /// Returns the number of bytes written.
302 ///
303 /// # Errors
304 ///
305 /// Returns an error reported by the wrapped output.
306 ///
307 /// # Safety
308 ///
309 /// `index..index + count` must be a valid range within `input`.
310 #[inline(always)]
311 unsafe fn write_unchecked(
312 &mut self,
313 input: &[u8],
314 index: usize,
315 count: usize,
316 ) -> Result<usize> {
317 // SAFETY: The caller upholds the same indexed range contract required
318 // by the wrapped output.
319 unsafe { self.inner.write_unchecked(input, index, count) }
320 }
321
322 /// Flushes the wrapped writer.
323 ///
324 /// # Returns
325 ///
326 /// Returns after the wrapped output has flushed.
327 ///
328 /// # Errors
329 ///
330 /// Returns the I/O error reported by the wrapped writer.
331 #[inline(always)]
332 fn flush(&mut self) -> Result<()> {
333 Output::flush(&mut self.inner)
334 }
335}
336
337impl<W, O> Seekable for BinaryWriter<W, O>
338where
339 W: Seekable<Unit = u8>,
340{
341 type Unit = u8;
342
343 /// Seeks the wrapped writer.
344 ///
345 /// # Parameters
346 ///
347 /// - `position`: Target seek position.
348 ///
349 /// # Returns
350 ///
351 /// Returns the new stream position.
352 ///
353 /// # Errors
354 ///
355 /// Returns the seek error reported by the wrapped writer.
356 #[inline(always)]
357 fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
358 self.inner.seek_to(position)
359 }
360}