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