Skip to main content

qubit_io_binary/ext/
binary_read_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 decoding fixed-width binary values from 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::ByteInput;
18use qubit_io::Input;
19
20use crate::util::decode_infallible_unchecked;
21
22macro_rules! read_binary_value {
23    ($reader:expr, $ty:ty, $order:ty) => {
24        read_binary::<{ BinaryCodec::<$ty, $order>::MIN_UNITS_PER_VALUE }, _, _, _>($reader, |bytes| {
25            type Codec = BinaryCodec<$ty, $order>;
26            // SAFETY: The local buffer is exactly the codec's minimum buffer
27            // length.
28            unsafe { decode_infallible_unchecked::<Codec>(bytes, 0) }
29        })
30    };
31}
32
33/// Resolves a runtime byte-order choice to a big-endian branch.
34///
35/// # Parameters
36///
37/// - `byte_order`: Runtime byte-order selection.
38///
39/// # Returns
40///
41/// Returns `true` for big endian, `false` for little endian, and the target's
42/// native ordering for [`ByteOrder::NativeEndian`].
43#[must_use]
44#[inline]
45const fn use_big_endian(byte_order: ByteOrder) -> bool {
46    match byte_order {
47        ByteOrder::BigEndian => true,
48        ByteOrder::LittleEndian => false,
49        ByteOrder::NativeEndian => cfg!(target_endian = "big"),
50    }
51}
52
53/// Extension methods for reading fixed-width binary values from byte streams.
54///
55/// # Examples
56///
57/// ```
58/// use std::io::Cursor;
59///
60/// use qubit_io_binary::BinaryReadExt;
61///
62/// let mut input = Cursor::new([0x12, 0x34]);
63/// assert_eq!(input.read_u16_be().unwrap(), 0x1234);
64/// ```
65/// A failed synchronous read may have consumed part of the current value.
66/// Do not blindly retry the same operation; resume only from a framing
67/// boundary or a trusted seek checkpoint.
68pub trait BinaryReadExt: ByteInput {
69    /// Reads an unsigned 8-bit integer.
70    ///
71    /// # Returns
72    ///
73    /// Returns the decoded scalar.
74    ///
75    /// # Errors
76    ///
77    /// Returns an input error, including an unexpected-end-of-input error
78    /// when a complete scalar is unavailable.
79    #[inline(always)]
80    fn read_u8(&mut self) -> Result<u8> {
81        read_binary_value!(self, u8, BigEndian)
82    }
83
84    /// Reads a signed 8-bit integer.
85    ///
86    /// # Returns
87    ///
88    /// Returns the decoded scalar.
89    ///
90    /// # Errors
91    ///
92    /// Returns an input error, including an unexpected-end-of-input error
93    /// when a complete scalar is unavailable.
94    #[inline(always)]
95    fn read_i8(&mut self) -> Result<i8> {
96        read_binary_value!(self, i8, BigEndian)
97    }
98
99    /// Reads an unsigned 16-bit integer using a runtime byte order.
100    ///
101    /// # Parameters
102    ///
103    /// - `byte_order`: Byte order used to decode the value.
104    ///
105    /// # Returns
106    ///
107    /// Returns the decoded scalar.
108    ///
109    /// # Errors
110    ///
111    /// Returns an input error, including an unexpected-end-of-input error
112    /// when a complete scalar is unavailable.
113    #[inline]
114    fn read_u16(&mut self, byte_order: ByteOrder) -> Result<u16> {
115        if use_big_endian(byte_order) {
116            self.read_u16_be()
117        } else {
118            self.read_u16_le()
119        }
120    }
121
122    /// Reads a big-endian unsigned 16-bit integer.
123    ///
124    /// # Returns
125    ///
126    /// Returns the decoded scalar.
127    ///
128    /// # Errors
129    ///
130    /// Returns an input error, including an unexpected-end-of-input error
131    /// when a complete scalar is unavailable.
132    #[inline(always)]
133    fn read_u16_be(&mut self) -> Result<u16> {
134        read_binary_value!(self, u16, BigEndian)
135    }
136
137    /// Reads a little-endian unsigned 16-bit integer.
138    ///
139    /// # Returns
140    ///
141    /// Returns the decoded scalar.
142    ///
143    /// # Errors
144    ///
145    /// Returns an input error, including an unexpected-end-of-input error
146    /// when a complete scalar is unavailable.
147    #[inline(always)]
148    fn read_u16_le(&mut self) -> Result<u16> {
149        read_binary_value!(self, u16, LittleEndian)
150    }
151
152    /// Reads an unsigned 32-bit integer using a runtime byte order.
153    ///
154    /// # Parameters
155    ///
156    /// - `byte_order`: Byte order used to decode the value.
157    ///
158    /// # Returns
159    ///
160    /// Returns the decoded scalar.
161    ///
162    /// # Errors
163    ///
164    /// Returns an input error, including an unexpected-end-of-input error
165    /// when a complete scalar is unavailable.
166    #[inline]
167    fn read_u32(&mut self, byte_order: ByteOrder) -> Result<u32> {
168        if use_big_endian(byte_order) {
169            self.read_u32_be()
170        } else {
171            self.read_u32_le()
172        }
173    }
174
175    /// Reads a big-endian unsigned 32-bit integer.
176    ///
177    /// # Returns
178    ///
179    /// Returns the decoded scalar.
180    ///
181    /// # Errors
182    ///
183    /// Returns an input error, including an unexpected-end-of-input error
184    /// when a complete scalar is unavailable.
185    #[inline(always)]
186    fn read_u32_be(&mut self) -> Result<u32> {
187        read_binary_value!(self, u32, BigEndian)
188    }
189
190    /// Reads a little-endian unsigned 32-bit integer.
191    ///
192    /// # Returns
193    ///
194    /// Returns the decoded scalar.
195    ///
196    /// # Errors
197    ///
198    /// Returns an input error, including an unexpected-end-of-input error
199    /// when a complete scalar is unavailable.
200    #[inline(always)]
201    fn read_u32_le(&mut self) -> Result<u32> {
202        read_binary_value!(self, u32, LittleEndian)
203    }
204
205    /// Reads an unsigned 64-bit integer using a runtime byte order.
206    ///
207    /// # Parameters
208    ///
209    /// - `byte_order`: Byte order used to decode the value.
210    ///
211    /// # Returns
212    ///
213    /// Returns the decoded scalar.
214    ///
215    /// # Errors
216    ///
217    /// Returns an input error, including an unexpected-end-of-input error
218    /// when a complete scalar is unavailable.
219    #[inline]
220    fn read_u64(&mut self, byte_order: ByteOrder) -> Result<u64> {
221        if use_big_endian(byte_order) {
222            self.read_u64_be()
223        } else {
224            self.read_u64_le()
225        }
226    }
227
228    /// Reads a big-endian unsigned 64-bit integer.
229    ///
230    /// # Returns
231    ///
232    /// Returns the decoded scalar.
233    ///
234    /// # Errors
235    ///
236    /// Returns an input error, including an unexpected-end-of-input error
237    /// when a complete scalar is unavailable.
238    #[inline(always)]
239    fn read_u64_be(&mut self) -> Result<u64> {
240        read_binary_value!(self, u64, BigEndian)
241    }
242
243    /// Reads a little-endian unsigned 64-bit integer.
244    ///
245    /// # Returns
246    ///
247    /// Returns the decoded scalar.
248    ///
249    /// # Errors
250    ///
251    /// Returns an input error, including an unexpected-end-of-input error
252    /// when a complete scalar is unavailable.
253    #[inline(always)]
254    fn read_u64_le(&mut self) -> Result<u64> {
255        read_binary_value!(self, u64, LittleEndian)
256    }
257
258    /// Reads an unsigned 128-bit integer using a runtime byte order.
259    ///
260    /// # Parameters
261    ///
262    /// - `byte_order`: Byte order used to decode the value.
263    ///
264    /// # Returns
265    ///
266    /// Returns the decoded scalar.
267    ///
268    /// # Errors
269    ///
270    /// Returns an input error, including an unexpected-end-of-input error
271    /// when a complete scalar is unavailable.
272    #[inline]
273    fn read_u128(&mut self, byte_order: ByteOrder) -> Result<u128> {
274        if use_big_endian(byte_order) {
275            self.read_u128_be()
276        } else {
277            self.read_u128_le()
278        }
279    }
280
281    /// Reads a big-endian unsigned 128-bit integer.
282    ///
283    /// # Returns
284    ///
285    /// Returns the decoded scalar.
286    ///
287    /// # Errors
288    ///
289    /// Returns an input error, including an unexpected-end-of-input error
290    /// when a complete scalar is unavailable.
291    #[inline(always)]
292    fn read_u128_be(&mut self) -> Result<u128> {
293        read_binary_value!(self, u128, BigEndian)
294    }
295
296    /// Reads a little-endian unsigned 128-bit integer.
297    ///
298    /// # Returns
299    ///
300    /// Returns the decoded scalar.
301    ///
302    /// # Errors
303    ///
304    /// Returns an input error, including an unexpected-end-of-input error
305    /// when a complete scalar is unavailable.
306    #[inline(always)]
307    fn read_u128_le(&mut self) -> Result<u128> {
308        read_binary_value!(self, u128, LittleEndian)
309    }
310
311    /// Reads a signed 16-bit integer using a runtime byte order.
312    ///
313    /// # Parameters
314    ///
315    /// - `byte_order`: Byte order used to decode the value.
316    ///
317    /// # Returns
318    ///
319    /// Returns the decoded scalar.
320    ///
321    /// # Errors
322    ///
323    /// Returns an input error, including an unexpected-end-of-input error
324    /// when a complete scalar is unavailable.
325    #[inline]
326    fn read_i16(&mut self, byte_order: ByteOrder) -> Result<i16> {
327        if use_big_endian(byte_order) {
328            self.read_i16_be()
329        } else {
330            self.read_i16_le()
331        }
332    }
333
334    /// Reads a big-endian signed 16-bit integer.
335    ///
336    /// # Returns
337    ///
338    /// Returns the decoded scalar.
339    ///
340    /// # Errors
341    ///
342    /// Returns an input error, including an unexpected-end-of-input error
343    /// when a complete scalar is unavailable.
344    #[inline(always)]
345    fn read_i16_be(&mut self) -> Result<i16> {
346        read_binary_value!(self, i16, BigEndian)
347    }
348
349    /// Reads a little-endian signed 16-bit integer.
350    ///
351    /// # Returns
352    ///
353    /// Returns the decoded scalar.
354    ///
355    /// # Errors
356    ///
357    /// Returns an input error, including an unexpected-end-of-input error
358    /// when a complete scalar is unavailable.
359    #[inline(always)]
360    fn read_i16_le(&mut self) -> Result<i16> {
361        read_binary_value!(self, i16, LittleEndian)
362    }
363
364    /// Reads a signed 32-bit integer using a runtime byte order.
365    ///
366    /// # Parameters
367    ///
368    /// - `byte_order`: Byte order used to decode the value.
369    ///
370    /// # Returns
371    ///
372    /// Returns the decoded scalar.
373    ///
374    /// # Errors
375    ///
376    /// Returns an input error, including an unexpected-end-of-input error
377    /// when a complete scalar is unavailable.
378    #[inline]
379    fn read_i32(&mut self, byte_order: ByteOrder) -> Result<i32> {
380        if use_big_endian(byte_order) {
381            self.read_i32_be()
382        } else {
383            self.read_i32_le()
384        }
385    }
386
387    /// Reads a big-endian signed 32-bit integer.
388    ///
389    /// # Returns
390    ///
391    /// Returns the decoded scalar.
392    ///
393    /// # Errors
394    ///
395    /// Returns an input error, including an unexpected-end-of-input error
396    /// when a complete scalar is unavailable.
397    #[inline(always)]
398    fn read_i32_be(&mut self) -> Result<i32> {
399        read_binary_value!(self, i32, BigEndian)
400    }
401
402    /// Reads a little-endian signed 32-bit integer.
403    ///
404    /// # Returns
405    ///
406    /// Returns the decoded scalar.
407    ///
408    /// # Errors
409    ///
410    /// Returns an input error, including an unexpected-end-of-input error
411    /// when a complete scalar is unavailable.
412    #[inline(always)]
413    fn read_i32_le(&mut self) -> Result<i32> {
414        read_binary_value!(self, i32, LittleEndian)
415    }
416
417    /// Reads a signed 64-bit integer using a runtime byte order.
418    ///
419    /// # Parameters
420    ///
421    /// - `byte_order`: Byte order used to decode the value.
422    ///
423    /// # Returns
424    ///
425    /// Returns the decoded scalar.
426    ///
427    /// # Errors
428    ///
429    /// Returns an input error, including an unexpected-end-of-input error
430    /// when a complete scalar is unavailable.
431    #[inline]
432    fn read_i64(&mut self, byte_order: ByteOrder) -> Result<i64> {
433        if use_big_endian(byte_order) {
434            self.read_i64_be()
435        } else {
436            self.read_i64_le()
437        }
438    }
439
440    /// Reads a big-endian signed 64-bit integer.
441    ///
442    /// # Returns
443    ///
444    /// Returns the decoded scalar.
445    ///
446    /// # Errors
447    ///
448    /// Returns an input error, including an unexpected-end-of-input error
449    /// when a complete scalar is unavailable.
450    #[inline(always)]
451    fn read_i64_be(&mut self) -> Result<i64> {
452        read_binary_value!(self, i64, BigEndian)
453    }
454
455    /// Reads a little-endian signed 64-bit integer.
456    ///
457    /// # Returns
458    ///
459    /// Returns the decoded scalar.
460    ///
461    /// # Errors
462    ///
463    /// Returns an input error, including an unexpected-end-of-input error
464    /// when a complete scalar is unavailable.
465    #[inline(always)]
466    fn read_i64_le(&mut self) -> Result<i64> {
467        read_binary_value!(self, i64, LittleEndian)
468    }
469
470    /// Reads a signed 128-bit integer using a runtime byte order.
471    ///
472    /// # Parameters
473    ///
474    /// - `byte_order`: Byte order used to decode the value.
475    ///
476    /// # Returns
477    ///
478    /// Returns the decoded scalar.
479    ///
480    /// # Errors
481    ///
482    /// Returns an input error, including an unexpected-end-of-input error
483    /// when a complete scalar is unavailable.
484    #[inline]
485    fn read_i128(&mut self, byte_order: ByteOrder) -> Result<i128> {
486        if use_big_endian(byte_order) {
487            self.read_i128_be()
488        } else {
489            self.read_i128_le()
490        }
491    }
492
493    /// Reads a big-endian signed 128-bit integer.
494    ///
495    /// # Returns
496    ///
497    /// Returns the decoded scalar.
498    ///
499    /// # Errors
500    ///
501    /// Returns an input error, including an unexpected-end-of-input error
502    /// when a complete scalar is unavailable.
503    #[inline(always)]
504    fn read_i128_be(&mut self) -> Result<i128> {
505        read_binary_value!(self, i128, BigEndian)
506    }
507
508    /// Reads a little-endian signed 128-bit integer.
509    ///
510    /// # Returns
511    ///
512    /// Returns the decoded scalar.
513    ///
514    /// # Errors
515    ///
516    /// Returns an input error, including an unexpected-end-of-input error
517    /// when a complete scalar is unavailable.
518    #[inline(always)]
519    fn read_i128_le(&mut self) -> Result<i128> {
520        read_binary_value!(self, i128, LittleEndian)
521    }
522
523    /// Reads a 32-bit float using a runtime byte order.
524    ///
525    /// # Parameters
526    ///
527    /// - `byte_order`: Byte order used to decode the value.
528    ///
529    /// # Returns
530    ///
531    /// Returns the decoded scalar.
532    ///
533    /// # Errors
534    ///
535    /// Returns an input error, including an unexpected-end-of-input error
536    /// when a complete scalar is unavailable.
537    #[inline]
538    fn read_f32(&mut self, byte_order: ByteOrder) -> Result<f32> {
539        if use_big_endian(byte_order) {
540            self.read_f32_be()
541        } else {
542            self.read_f32_le()
543        }
544    }
545
546    /// Reads a big-endian 32-bit float.
547    ///
548    /// # Returns
549    ///
550    /// Returns the decoded scalar.
551    ///
552    /// # Errors
553    ///
554    /// Returns an input error, including an unexpected-end-of-input error
555    /// when a complete scalar is unavailable.
556    #[inline(always)]
557    fn read_f32_be(&mut self) -> Result<f32> {
558        read_binary_value!(self, f32, BigEndian)
559    }
560
561    /// Reads a little-endian 32-bit float.
562    ///
563    /// # Returns
564    ///
565    /// Returns the decoded scalar.
566    ///
567    /// # Errors
568    ///
569    /// Returns an input error, including an unexpected-end-of-input error
570    /// when a complete scalar is unavailable.
571    #[inline(always)]
572    fn read_f32_le(&mut self) -> Result<f32> {
573        read_binary_value!(self, f32, LittleEndian)
574    }
575
576    /// Reads a 64-bit float using a runtime byte order.
577    ///
578    /// # Parameters
579    ///
580    /// - `byte_order`: Byte order used to decode the value.
581    ///
582    /// # Returns
583    ///
584    /// Returns the decoded scalar.
585    ///
586    /// # Errors
587    ///
588    /// Returns an input error, including an unexpected-end-of-input error
589    /// when a complete scalar is unavailable.
590    #[inline]
591    fn read_f64(&mut self, byte_order: ByteOrder) -> Result<f64> {
592        if use_big_endian(byte_order) {
593            self.read_f64_be()
594        } else {
595            self.read_f64_le()
596        }
597    }
598
599    /// Reads a big-endian 64-bit float.
600    ///
601    /// # Returns
602    ///
603    /// Returns the decoded scalar.
604    ///
605    /// # Errors
606    ///
607    /// Returns an input error, including an unexpected-end-of-input error
608    /// when a complete scalar is unavailable.
609    #[inline(always)]
610    fn read_f64_be(&mut self) -> Result<f64> {
611        read_binary_value!(self, f64, BigEndian)
612    }
613
614    /// Reads a little-endian 64-bit float.
615    ///
616    /// # Returns
617    ///
618    /// Returns the decoded scalar.
619    ///
620    /// # Errors
621    ///
622    /// Returns an input error, including an unexpected-end-of-input error
623    /// when a complete scalar is unavailable.
624    #[inline(always)]
625    fn read_f64_le(&mut self) -> Result<f64> {
626        read_binary_value!(self, f64, LittleEndian)
627    }
628}
629
630impl<R> BinaryReadExt for R where R: ByteInput + ?Sized {}
631
632/// Reads and decodes one fixed-width value.
633///
634/// # Type Parameters
635///
636/// - `N`: Encoded scalar width in bytes.
637/// - `T`: Decoded value type.
638/// - `R`: Source byte input.
639/// - `F`: Infallible decoding callback.
640///
641/// # Parameters
642///
643/// - `reader`: Source from which the fixed-width payload is read.
644/// - `decode`: Callback that decodes the initialized local buffer.
645///
646/// # Returns
647///
648/// Returns the decoded value.
649///
650/// # Errors
651///
652/// Returns an input error, including an unexpected-end-of-input error when the
653/// payload is truncated.
654#[inline]
655fn read_binary<const N: usize, T, R, F>(reader: &mut R, decode: F) -> Result<T>
656where
657    R: ByteInput + ?Sized,
658    F: FnOnce(&[u8]) -> T,
659{
660    let mut bytes = [0u8; N];
661    Input::read_exactly(reader, &mut bytes)?;
662    Ok(decode(&bytes))
663}