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