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