qubit_io_binary/ext/binary_write_ext.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//! Extension methods for encoding fixed-width binary values into byte streams.
10
11use std::io::Result;
12
13use qubit_codec::BigEndian;
14use qubit_codec::ByteOrder;
15use qubit_codec::LittleEndian;
16use qubit_codec_binary::BinaryCodec;
17use qubit_io::Output;
18
19use crate::util::encode_infallible_unchecked;
20use crate::util::write_all;
21
22/// Encodes a scalar into a fixed-width buffer and writes the bytes.
23macro_rules! write_binary_value {
24 ($writer:expr, $value:expr, $ty:ty, $order:ty) => {
25 write_binary::<{ BinaryCodec::<$ty, $order>::MAX_ENCODE_UNITS_PER_VALUE }, _, _, _>(
26 $writer,
27 $value,
28 |bytes, value| {
29 type Codec = BinaryCodec<$ty, $order>;
30 // SAFETY: The local buffer is exactly the codec's maximum buffer
31 // length.
32 unsafe {
33 let _ = encode_infallible_unchecked::<Codec>(value, bytes, 0);
34 }
35 },
36 )
37 };
38}
39
40/// Resolves a runtime byte-order choice to a big-endian branch.
41///
42/// # Parameters
43///
44/// - `byte_order`: Runtime byte-order selection.
45///
46/// # Returns
47///
48/// Returns `true` for big endian, `false` for little endian, and the target's
49/// native ordering for [`ByteOrder::NativeEndian`].
50#[must_use]
51#[inline]
52const fn use_big_endian(byte_order: ByteOrder) -> bool {
53 match byte_order {
54 ByteOrder::BigEndian => true,
55 ByteOrder::LittleEndian => false,
56 ByteOrder::NativeEndian => cfg!(target_endian = "big"),
57 }
58}
59
60/// Extension methods for writing fixed-width binary values to byte streams.
61///
62/// # Examples
63///
64/// ```
65/// use qubit_io_binary::BinaryWriteExt;
66///
67/// let mut output = Vec::new();
68/// output.write_u16_be(0x1234)?;
69/// assert_eq!(output, [0x12, 0x34]);
70/// # Ok::<(), std::io::Error>(())
71/// ```
72pub trait BinaryWriteExt: Output<Item = u8> {
73 /// Writes an unsigned 8-bit integer.
74 ///
75 /// # Parameters
76 ///
77 /// - `value`: Scalar to encode and write.
78 ///
79 /// # Returns
80 ///
81 /// Returns after the encoded scalar has been written.
82 ///
83 /// # Errors
84 ///
85 /// Returns an output error, including a write-zero error when the output
86 /// stops making progress.
87 #[inline(always)]
88 fn write_u8(&mut self, value: u8) -> Result<()> {
89 write_binary_value!(self, value, u8, BigEndian)
90 }
91
92 /// Writes a signed 8-bit integer.
93 ///
94 /// # Parameters
95 ///
96 /// - `value`: Scalar to encode and write.
97 ///
98 /// # Returns
99 ///
100 /// Returns after the encoded scalar has been written.
101 ///
102 /// # Errors
103 ///
104 /// Returns an output error, including a write-zero error when the output
105 /// stops making progress.
106 #[inline(always)]
107 fn write_i8(&mut self, value: i8) -> Result<()> {
108 write_binary_value!(self, value, i8, BigEndian)
109 }
110
111 /// Writes an unsigned 16-bit integer using a runtime byte order.
112 ///
113 /// # Parameters
114 ///
115 /// - `value`: Scalar to encode and write.
116 /// - `byte_order`: Byte order used to encode the value.
117 ///
118 /// # Returns
119 ///
120 /// Returns after the encoded scalar has been written.
121 ///
122 /// # Errors
123 ///
124 /// Returns an output error, including a write-zero error when the output
125 /// stops making progress.
126 #[inline]
127 fn write_u16(&mut self, value: u16, byte_order: ByteOrder) -> Result<()> {
128 if use_big_endian(byte_order) {
129 self.write_u16_be(value)
130 } else {
131 self.write_u16_le(value)
132 }
133 }
134
135 /// Writes a big-endian unsigned 16-bit integer.
136 ///
137 /// # Parameters
138 ///
139 /// - `value`: Scalar to encode and write.
140 ///
141 /// # Returns
142 ///
143 /// Returns after the encoded scalar has been written.
144 ///
145 /// # Errors
146 ///
147 /// Returns an output error, including a write-zero error when the output
148 /// stops making progress.
149 #[inline(always)]
150 fn write_u16_be(&mut self, value: u16) -> Result<()> {
151 write_binary_value!(self, value, u16, BigEndian)
152 }
153
154 /// Writes a little-endian unsigned 16-bit integer.
155 ///
156 /// # Parameters
157 ///
158 /// - `value`: Scalar to encode and write.
159 ///
160 /// # Returns
161 ///
162 /// Returns after the encoded scalar has been written.
163 ///
164 /// # Errors
165 ///
166 /// Returns an output error, including a write-zero error when the output
167 /// stops making progress.
168 #[inline(always)]
169 fn write_u16_le(&mut self, value: u16) -> Result<()> {
170 write_binary_value!(self, value, u16, LittleEndian)
171 }
172
173 /// Writes an unsigned 32-bit integer using a runtime byte order.
174 ///
175 /// # Parameters
176 ///
177 /// - `value`: Scalar to encode and write.
178 /// - `byte_order`: Byte order used to encode the value.
179 ///
180 /// # Returns
181 ///
182 /// Returns after the encoded scalar has been written.
183 ///
184 /// # Errors
185 ///
186 /// Returns an output error, including a write-zero error when the output
187 /// stops making progress.
188 #[inline]
189 fn write_u32(&mut self, value: u32, byte_order: ByteOrder) -> Result<()> {
190 if use_big_endian(byte_order) {
191 self.write_u32_be(value)
192 } else {
193 self.write_u32_le(value)
194 }
195 }
196
197 /// Writes a big-endian unsigned 32-bit integer.
198 ///
199 /// # Parameters
200 ///
201 /// - `value`: Scalar to encode and write.
202 ///
203 /// # Returns
204 ///
205 /// Returns after the encoded scalar has been written.
206 ///
207 /// # Errors
208 ///
209 /// Returns an output error, including a write-zero error when the output
210 /// stops making progress.
211 #[inline(always)]
212 fn write_u32_be(&mut self, value: u32) -> Result<()> {
213 write_binary_value!(self, value, u32, BigEndian)
214 }
215
216 /// Writes a little-endian unsigned 32-bit integer.
217 ///
218 /// # Parameters
219 ///
220 /// - `value`: Scalar to encode and write.
221 ///
222 /// # Returns
223 ///
224 /// Returns after the encoded scalar has been written.
225 ///
226 /// # Errors
227 ///
228 /// Returns an output error, including a write-zero error when the output
229 /// stops making progress.
230 #[inline(always)]
231 fn write_u32_le(&mut self, value: u32) -> Result<()> {
232 write_binary_value!(self, value, u32, LittleEndian)
233 }
234
235 /// Writes an unsigned 64-bit integer using a runtime byte order.
236 ///
237 /// # Parameters
238 ///
239 /// - `value`: Scalar to encode and write.
240 /// - `byte_order`: Byte order used to encode the value.
241 ///
242 /// # Returns
243 ///
244 /// Returns after the encoded scalar has been written.
245 ///
246 /// # Errors
247 ///
248 /// Returns an output error, including a write-zero error when the output
249 /// stops making progress.
250 #[inline]
251 fn write_u64(&mut self, value: u64, byte_order: ByteOrder) -> Result<()> {
252 if use_big_endian(byte_order) {
253 self.write_u64_be(value)
254 } else {
255 self.write_u64_le(value)
256 }
257 }
258
259 /// Writes a big-endian unsigned 64-bit integer.
260 ///
261 /// # Parameters
262 ///
263 /// - `value`: Scalar to encode and write.
264 ///
265 /// # Returns
266 ///
267 /// Returns after the encoded scalar has been written.
268 ///
269 /// # Errors
270 ///
271 /// Returns an output error, including a write-zero error when the output
272 /// stops making progress.
273 #[inline(always)]
274 fn write_u64_be(&mut self, value: u64) -> Result<()> {
275 write_binary_value!(self, value, u64, BigEndian)
276 }
277
278 /// Writes a little-endian unsigned 64-bit integer.
279 ///
280 /// # Parameters
281 ///
282 /// - `value`: Scalar to encode and write.
283 ///
284 /// # Returns
285 ///
286 /// Returns after the encoded scalar has been written.
287 ///
288 /// # Errors
289 ///
290 /// Returns an output error, including a write-zero error when the output
291 /// stops making progress.
292 #[inline(always)]
293 fn write_u64_le(&mut self, value: u64) -> Result<()> {
294 write_binary_value!(self, value, u64, LittleEndian)
295 }
296
297 /// Writes an unsigned 128-bit integer using a runtime byte order.
298 ///
299 /// # Parameters
300 ///
301 /// - `value`: Scalar to encode and write.
302 /// - `byte_order`: Byte order used to encode the value.
303 ///
304 /// # Returns
305 ///
306 /// Returns after the encoded scalar has been written.
307 ///
308 /// # Errors
309 ///
310 /// Returns an output error, including a write-zero error when the output
311 /// stops making progress.
312 #[inline]
313 fn write_u128(&mut self, value: u128, byte_order: ByteOrder) -> Result<()> {
314 if use_big_endian(byte_order) {
315 self.write_u128_be(value)
316 } else {
317 self.write_u128_le(value)
318 }
319 }
320
321 /// Writes a big-endian unsigned 128-bit integer.
322 ///
323 /// # Parameters
324 ///
325 /// - `value`: Scalar to encode and write.
326 ///
327 /// # Returns
328 ///
329 /// Returns after the encoded scalar has been written.
330 ///
331 /// # Errors
332 ///
333 /// Returns an output error, including a write-zero error when the output
334 /// stops making progress.
335 #[inline(always)]
336 fn write_u128_be(&mut self, value: u128) -> Result<()> {
337 write_binary_value!(self, value, u128, BigEndian)
338 }
339
340 /// Writes a little-endian unsigned 128-bit integer.
341 ///
342 /// # Parameters
343 ///
344 /// - `value`: Scalar to encode and write.
345 ///
346 /// # Returns
347 ///
348 /// Returns after the encoded scalar has been written.
349 ///
350 /// # Errors
351 ///
352 /// Returns an output error, including a write-zero error when the output
353 /// stops making progress.
354 #[inline(always)]
355 fn write_u128_le(&mut self, value: u128) -> Result<()> {
356 write_binary_value!(self, value, u128, LittleEndian)
357 }
358
359 /// Writes a signed 16-bit integer using a runtime byte order.
360 ///
361 /// # Parameters
362 ///
363 /// - `value`: Scalar to encode and write.
364 /// - `byte_order`: Byte order used to encode the value.
365 ///
366 /// # Returns
367 ///
368 /// Returns after the encoded scalar has been written.
369 ///
370 /// # Errors
371 ///
372 /// Returns an output error, including a write-zero error when the output
373 /// stops making progress.
374 #[inline]
375 fn write_i16(&mut self, value: i16, byte_order: ByteOrder) -> Result<()> {
376 if use_big_endian(byte_order) {
377 self.write_i16_be(value)
378 } else {
379 self.write_i16_le(value)
380 }
381 }
382
383 /// Writes a big-endian signed 16-bit integer.
384 ///
385 /// # Parameters
386 ///
387 /// - `value`: Scalar to encode and write.
388 ///
389 /// # Returns
390 ///
391 /// Returns after the encoded scalar has been written.
392 ///
393 /// # Errors
394 ///
395 /// Returns an output error, including a write-zero error when the output
396 /// stops making progress.
397 #[inline(always)]
398 fn write_i16_be(&mut self, value: i16) -> Result<()> {
399 write_binary_value!(self, value, i16, BigEndian)
400 }
401
402 /// Writes a little-endian signed 16-bit integer.
403 ///
404 /// # Parameters
405 ///
406 /// - `value`: Scalar to encode and write.
407 ///
408 /// # Returns
409 ///
410 /// Returns after the encoded scalar has been written.
411 ///
412 /// # Errors
413 ///
414 /// Returns an output error, including a write-zero error when the output
415 /// stops making progress.
416 #[inline(always)]
417 fn write_i16_le(&mut self, value: i16) -> Result<()> {
418 write_binary_value!(self, value, i16, LittleEndian)
419 }
420
421 /// Writes a signed 32-bit integer using a runtime byte order.
422 ///
423 /// # Parameters
424 ///
425 /// - `value`: Scalar to encode and write.
426 /// - `byte_order`: Byte order used to encode the value.
427 ///
428 /// # Returns
429 ///
430 /// Returns after the encoded scalar has been written.
431 ///
432 /// # Errors
433 ///
434 /// Returns an output error, including a write-zero error when the output
435 /// stops making progress.
436 #[inline]
437 fn write_i32(&mut self, value: i32, byte_order: ByteOrder) -> Result<()> {
438 if use_big_endian(byte_order) {
439 self.write_i32_be(value)
440 } else {
441 self.write_i32_le(value)
442 }
443 }
444
445 /// Writes a big-endian signed 32-bit integer.
446 ///
447 /// # Parameters
448 ///
449 /// - `value`: Scalar to encode and write.
450 ///
451 /// # Returns
452 ///
453 /// Returns after the encoded scalar has been written.
454 ///
455 /// # Errors
456 ///
457 /// Returns an output error, including a write-zero error when the output
458 /// stops making progress.
459 #[inline(always)]
460 fn write_i32_be(&mut self, value: i32) -> Result<()> {
461 write_binary_value!(self, value, i32, BigEndian)
462 }
463
464 /// Writes a little-endian signed 32-bit integer.
465 ///
466 /// # Parameters
467 ///
468 /// - `value`: Scalar to encode and write.
469 ///
470 /// # Returns
471 ///
472 /// Returns after the encoded scalar has been written.
473 ///
474 /// # Errors
475 ///
476 /// Returns an output error, including a write-zero error when the output
477 /// stops making progress.
478 #[inline(always)]
479 fn write_i32_le(&mut self, value: i32) -> Result<()> {
480 write_binary_value!(self, value, i32, LittleEndian)
481 }
482
483 /// Writes a signed 64-bit integer using a runtime byte order.
484 ///
485 /// # Parameters
486 ///
487 /// - `value`: Scalar to encode and write.
488 /// - `byte_order`: Byte order used to encode the value.
489 ///
490 /// # Returns
491 ///
492 /// Returns after the encoded scalar has been written.
493 ///
494 /// # Errors
495 ///
496 /// Returns an output error, including a write-zero error when the output
497 /// stops making progress.
498 #[inline]
499 fn write_i64(&mut self, value: i64, byte_order: ByteOrder) -> Result<()> {
500 if use_big_endian(byte_order) {
501 self.write_i64_be(value)
502 } else {
503 self.write_i64_le(value)
504 }
505 }
506
507 /// Writes a big-endian signed 64-bit integer.
508 ///
509 /// # Parameters
510 ///
511 /// - `value`: Scalar to encode and write.
512 ///
513 /// # Returns
514 ///
515 /// Returns after the encoded scalar has been written.
516 ///
517 /// # Errors
518 ///
519 /// Returns an output error, including a write-zero error when the output
520 /// stops making progress.
521 #[inline(always)]
522 fn write_i64_be(&mut self, value: i64) -> Result<()> {
523 write_binary_value!(self, value, i64, BigEndian)
524 }
525
526 /// Writes a little-endian signed 64-bit integer.
527 ///
528 /// # Parameters
529 ///
530 /// - `value`: Scalar to encode and write.
531 ///
532 /// # Returns
533 ///
534 /// Returns after the encoded scalar has been written.
535 ///
536 /// # Errors
537 ///
538 /// Returns an output error, including a write-zero error when the output
539 /// stops making progress.
540 #[inline(always)]
541 fn write_i64_le(&mut self, value: i64) -> Result<()> {
542 write_binary_value!(self, value, i64, LittleEndian)
543 }
544
545 /// Writes a signed 128-bit integer using a runtime byte order.
546 ///
547 /// # Parameters
548 ///
549 /// - `value`: Scalar to encode and write.
550 /// - `byte_order`: Byte order used to encode the value.
551 ///
552 /// # Returns
553 ///
554 /// Returns after the encoded scalar has been written.
555 ///
556 /// # Errors
557 ///
558 /// Returns an output error, including a write-zero error when the output
559 /// stops making progress.
560 #[inline]
561 fn write_i128(&mut self, value: i128, byte_order: ByteOrder) -> Result<()> {
562 if use_big_endian(byte_order) {
563 self.write_i128_be(value)
564 } else {
565 self.write_i128_le(value)
566 }
567 }
568
569 /// Writes a big-endian signed 128-bit integer.
570 ///
571 /// # Parameters
572 ///
573 /// - `value`: Scalar to encode and write.
574 ///
575 /// # Returns
576 ///
577 /// Returns after the encoded scalar has been written.
578 ///
579 /// # Errors
580 ///
581 /// Returns an output error, including a write-zero error when the output
582 /// stops making progress.
583 #[inline(always)]
584 fn write_i128_be(&mut self, value: i128) -> Result<()> {
585 write_binary_value!(self, value, i128, BigEndian)
586 }
587
588 /// Writes a little-endian signed 128-bit integer.
589 ///
590 /// # Parameters
591 ///
592 /// - `value`: Scalar to encode and write.
593 ///
594 /// # Returns
595 ///
596 /// Returns after the encoded scalar has been written.
597 ///
598 /// # Errors
599 ///
600 /// Returns an output error, including a write-zero error when the output
601 /// stops making progress.
602 #[inline(always)]
603 fn write_i128_le(&mut self, value: i128) -> Result<()> {
604 write_binary_value!(self, value, i128, LittleEndian)
605 }
606
607 /// Writes a 32-bit float using a runtime byte order.
608 ///
609 /// # Parameters
610 ///
611 /// - `value`: Scalar to encode and write.
612 /// - `byte_order`: Byte order used to encode the value.
613 ///
614 /// # Returns
615 ///
616 /// Returns after the encoded scalar has been written.
617 ///
618 /// # Errors
619 ///
620 /// Returns an output error, including a write-zero error when the output
621 /// stops making progress.
622 #[inline]
623 fn write_f32(&mut self, value: f32, byte_order: ByteOrder) -> Result<()> {
624 if use_big_endian(byte_order) {
625 self.write_f32_be(value)
626 } else {
627 self.write_f32_le(value)
628 }
629 }
630
631 /// Writes a big-endian 32-bit float.
632 ///
633 /// # Parameters
634 ///
635 /// - `value`: Scalar to encode and write.
636 ///
637 /// # Returns
638 ///
639 /// Returns after the encoded scalar has been written.
640 ///
641 /// # Errors
642 ///
643 /// Returns an output error, including a write-zero error when the output
644 /// stops making progress.
645 #[inline(always)]
646 fn write_f32_be(&mut self, value: f32) -> Result<()> {
647 write_binary_value!(self, value, f32, BigEndian)
648 }
649
650 /// Writes a little-endian 32-bit float.
651 ///
652 /// # Parameters
653 ///
654 /// - `value`: Scalar to encode and write.
655 ///
656 /// # Returns
657 ///
658 /// Returns after the encoded scalar has been written.
659 ///
660 /// # Errors
661 ///
662 /// Returns an output error, including a write-zero error when the output
663 /// stops making progress.
664 #[inline(always)]
665 fn write_f32_le(&mut self, value: f32) -> Result<()> {
666 write_binary_value!(self, value, f32, LittleEndian)
667 }
668
669 /// Writes a 64-bit float using a runtime byte order.
670 ///
671 /// # Parameters
672 ///
673 /// - `value`: Scalar to encode and write.
674 /// - `byte_order`: Byte order used to encode the value.
675 ///
676 /// # Returns
677 ///
678 /// Returns after the encoded scalar has been written.
679 ///
680 /// # Errors
681 ///
682 /// Returns an output error, including a write-zero error when the output
683 /// stops making progress.
684 #[inline]
685 fn write_f64(&mut self, value: f64, byte_order: ByteOrder) -> Result<()> {
686 if use_big_endian(byte_order) {
687 self.write_f64_be(value)
688 } else {
689 self.write_f64_le(value)
690 }
691 }
692
693 /// Writes a big-endian 64-bit float.
694 ///
695 /// # Parameters
696 ///
697 /// - `value`: Scalar to encode and write.
698 ///
699 /// # Returns
700 ///
701 /// Returns after the encoded scalar has been written.
702 ///
703 /// # Errors
704 ///
705 /// Returns an output error, including a write-zero error when the output
706 /// stops making progress.
707 #[inline(always)]
708 fn write_f64_be(&mut self, value: f64) -> Result<()> {
709 write_binary_value!(self, value, f64, BigEndian)
710 }
711
712 /// Writes a little-endian 64-bit float.
713 ///
714 /// # Parameters
715 ///
716 /// - `value`: Scalar to encode and write.
717 ///
718 /// # Returns
719 ///
720 /// Returns after the encoded scalar has been written.
721 ///
722 /// # Errors
723 ///
724 /// Returns an output error, including a write-zero error when the output
725 /// stops making progress.
726 #[inline(always)]
727 fn write_f64_le(&mut self, value: f64) -> Result<()> {
728 write_binary_value!(self, value, f64, LittleEndian)
729 }
730}
731
732impl<W> BinaryWriteExt for W where W: Output<Item = u8> + ?Sized {}
733
734/// Encodes and writes one fixed-width value.
735///
736/// # Type Parameters
737///
738/// - `N`: Encoded scalar width in bytes.
739/// - `T`: Value type accepted by the encoder.
740/// - `W`: Destination byte output.
741/// - `F`: Infallible encoding callback.
742///
743/// # Parameters
744///
745/// - `writer`: Destination for the fixed-width payload.
746/// - `value`: Value passed to `encode`.
747/// - `encode`: Callback that fills the local payload buffer.
748///
749/// # Returns
750///
751/// Returns after the complete payload has been written.
752///
753/// # Errors
754///
755/// Returns an output error, including a write-zero error when the output stops
756/// making progress.
757#[inline]
758fn write_binary<const N: usize, T, W, F>(writer: &mut W, value: T, encode: F) -> Result<()>
759where
760 W: Output<Item = u8> + ?Sized,
761 F: FnOnce(&mut [u8], T),
762{
763 let mut bytes = [0u8; N];
764 encode(&mut bytes, value);
765 write_all(writer, &bytes)
766}