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