Skip to main content

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