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