Skip to main content

qubit_io_binary/ext/
async_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//! Asynchronous fixed-width binary reads.
9
10use core::future::Future;
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::AsyncInput;
18
19use crate::util::decode_infallible_unchecked;
20use crate::util::read_exactly_async;
21
22macro_rules! read_binary_value_async {
23    ($reader:expr, $ty:ty, $order:ty) => {
24        read_binary_async::<{ BinaryCodec::<$ty, $order>::MIN_UNITS_PER_VALUE }, _, _, _>($reader, |bytes| {
25            type Codec = BinaryCodec<$ty, $order>;
26            // SAFETY: The local buffer has exactly the codec's fixed width.
27            unsafe { decode_infallible_unchecked::<Codec>(bytes, 0) }
28        })
29        .await
30    };
31}
32
33macro_rules! fixed_read_method {
34    ($doc:literal, $name:ident, $ty:ty, $order:ty) => {
35        #[doc = $doc]
36        #[doc = ""]
37        #[doc = "# Returns"]
38        #[doc = ""]
39        #[doc = concat!("Returns the decoded `", stringify!($ty), "`.")]
40        #[doc = ""]
41        #[doc = "# Errors"]
42        #[doc = ""]
43        #[doc = "Returns an input error, including an unexpected-end-of-input \
44                 error when a complete value is unavailable."]
45        #[doc = ""]
46        #[doc = "# Cancellation safety"]
47        #[doc = ""]
48        #[doc = "This operation is not cancellation safe. Dropping the future \
49                 retains any bytes already consumed from the input."]
50        #[inline(always)]
51        fn $name(&mut self) -> impl Future<Output = Result<$ty>> + '_
52        where
53            Self: Unpin,
54        {
55            async move { read_binary_value_async!(self, $ty, $order) }
56        }
57    };
58}
59
60macro_rules! runtime_order_read_method {
61    ($doc:literal, $name:ident, $ty:ty, $big:ident, $little:ident) => {
62        #[doc = $doc]
63        #[doc = ""]
64        #[doc = "# Parameters"]
65        #[doc = ""]
66        #[doc = "- `byte_order`: Byte order used to decode the value."]
67        #[doc = ""]
68        #[doc = "# Returns"]
69        #[doc = ""]
70        #[doc = concat!("Returns the decoded `", stringify!($ty), "`.")]
71        #[doc = ""]
72        #[doc = "# Errors"]
73        #[doc = ""]
74        #[doc = "Returns an input error, including an unexpected-end-of-input \
75                 error when a complete value is unavailable."]
76        #[doc = ""]
77        #[doc = "# Cancellation safety"]
78        #[doc = ""]
79        #[doc = "This operation is not cancellation safe. Dropping the future \
80                 retains any bytes already consumed from the input."]
81        #[inline]
82        fn $name(&mut self, byte_order: ByteOrder) -> impl Future<Output = Result<$ty>> + '_
83        where
84            Self: Unpin,
85        {
86            async move {
87                if use_big_endian(byte_order) {
88                    self.$big().await
89                } else {
90                    self.$little().await
91                }
92            }
93        }
94    };
95}
96
97/// Resolves a runtime byte-order choice to a big-endian branch.
98///
99/// # Parameters
100///
101/// - `byte_order`: Runtime byte-order selection.
102///
103/// # Returns
104///
105/// Returns `true` for big endian, `false` for little endian, and the target's
106/// native ordering for [`ByteOrder::NativeEndian`].
107#[must_use]
108#[inline]
109const fn use_big_endian(byte_order: ByteOrder) -> bool {
110    match byte_order {
111        ByteOrder::BigEndian => true,
112        ByteOrder::LittleEndian => false,
113        ByteOrder::NativeEndian => cfg!(target_endian = "big"),
114    }
115}
116
117/// Future-based fixed-width binary reads from runtime-neutral async inputs.
118///
119/// # Cancellation safety
120///
121/// These reads are not cancellation safe. Dropping a pending future leaves
122/// bytes already consumed from the input consumed; retrying starts at the
123/// input's new position.
124pub trait AsyncBinaryReadExt: AsyncInput<Item = u8> {
125    fixed_read_method!(
126        "Asynchronously reads an unsigned 8-bit integer.",
127        read_u8_async,
128        u8,
129        BigEndian
130    );
131    fixed_read_method!(
132        "Asynchronously reads a signed 8-bit integer.",
133        read_i8_async,
134        i8,
135        BigEndian
136    );
137
138    runtime_order_read_method!(
139        "Asynchronously reads a `u16` using a runtime byte order.",
140        read_u16_async,
141        u16,
142        read_u16_be_async,
143        read_u16_le_async
144    );
145
146    fixed_read_method!(
147        "Asynchronously reads a big-endian `u16`.",
148        read_u16_be_async,
149        u16,
150        BigEndian
151    );
152    fixed_read_method!(
153        "Asynchronously reads a little-endian `u16`.",
154        read_u16_le_async,
155        u16,
156        LittleEndian
157    );
158
159    runtime_order_read_method!(
160        "Asynchronously reads a `u32` using a runtime byte order.",
161        read_u32_async,
162        u32,
163        read_u32_be_async,
164        read_u32_le_async
165    );
166
167    fixed_read_method!(
168        "Asynchronously reads a big-endian `u32`.",
169        read_u32_be_async,
170        u32,
171        BigEndian
172    );
173    fixed_read_method!(
174        "Asynchronously reads a little-endian `u32`.",
175        read_u32_le_async,
176        u32,
177        LittleEndian
178    );
179
180    runtime_order_read_method!(
181        "Asynchronously reads a `u64` using a runtime byte order.",
182        read_u64_async,
183        u64,
184        read_u64_be_async,
185        read_u64_le_async
186    );
187
188    fixed_read_method!(
189        "Asynchronously reads a big-endian `u64`.",
190        read_u64_be_async,
191        u64,
192        BigEndian
193    );
194    fixed_read_method!(
195        "Asynchronously reads a little-endian `u64`.",
196        read_u64_le_async,
197        u64,
198        LittleEndian
199    );
200
201    runtime_order_read_method!(
202        "Asynchronously reads a `u128` using a runtime byte order.",
203        read_u128_async,
204        u128,
205        read_u128_be_async,
206        read_u128_le_async
207    );
208
209    fixed_read_method!(
210        "Asynchronously reads a big-endian `u128`.",
211        read_u128_be_async,
212        u128,
213        BigEndian
214    );
215    fixed_read_method!(
216        "Asynchronously reads a little-endian `u128`.",
217        read_u128_le_async,
218        u128,
219        LittleEndian
220    );
221
222    runtime_order_read_method!(
223        "Asynchronously reads an `i16` using a runtime byte order.",
224        read_i16_async,
225        i16,
226        read_i16_be_async,
227        read_i16_le_async
228    );
229
230    fixed_read_method!(
231        "Asynchronously reads a big-endian `i16`.",
232        read_i16_be_async,
233        i16,
234        BigEndian
235    );
236    fixed_read_method!(
237        "Asynchronously reads a little-endian `i16`.",
238        read_i16_le_async,
239        i16,
240        LittleEndian
241    );
242
243    runtime_order_read_method!(
244        "Asynchronously reads an `i32` using a runtime byte order.",
245        read_i32_async,
246        i32,
247        read_i32_be_async,
248        read_i32_le_async
249    );
250
251    fixed_read_method!(
252        "Asynchronously reads a big-endian `i32`.",
253        read_i32_be_async,
254        i32,
255        BigEndian
256    );
257    fixed_read_method!(
258        "Asynchronously reads a little-endian `i32`.",
259        read_i32_le_async,
260        i32,
261        LittleEndian
262    );
263
264    runtime_order_read_method!(
265        "Asynchronously reads an `i64` using a runtime byte order.",
266        read_i64_async,
267        i64,
268        read_i64_be_async,
269        read_i64_le_async
270    );
271
272    fixed_read_method!(
273        "Asynchronously reads a big-endian `i64`.",
274        read_i64_be_async,
275        i64,
276        BigEndian
277    );
278    fixed_read_method!(
279        "Asynchronously reads a little-endian `i64`.",
280        read_i64_le_async,
281        i64,
282        LittleEndian
283    );
284
285    runtime_order_read_method!(
286        "Asynchronously reads an `i128` using a runtime byte order.",
287        read_i128_async,
288        i128,
289        read_i128_be_async,
290        read_i128_le_async
291    );
292
293    fixed_read_method!(
294        "Asynchronously reads a big-endian `i128`.",
295        read_i128_be_async,
296        i128,
297        BigEndian
298    );
299    fixed_read_method!(
300        "Asynchronously reads a little-endian `i128`.",
301        read_i128_le_async,
302        i128,
303        LittleEndian
304    );
305
306    runtime_order_read_method!(
307        "Asynchronously reads an `f32` using a runtime byte order.",
308        read_f32_async,
309        f32,
310        read_f32_be_async,
311        read_f32_le_async
312    );
313
314    fixed_read_method!(
315        "Asynchronously reads a big-endian `f32`.",
316        read_f32_be_async,
317        f32,
318        BigEndian
319    );
320    fixed_read_method!(
321        "Asynchronously reads a little-endian `f32`.",
322        read_f32_le_async,
323        f32,
324        LittleEndian
325    );
326
327    runtime_order_read_method!(
328        "Asynchronously reads an `f64` using a runtime byte order.",
329        read_f64_async,
330        f64,
331        read_f64_be_async,
332        read_f64_le_async
333    );
334
335    fixed_read_method!(
336        "Asynchronously reads a big-endian `f64`.",
337        read_f64_be_async,
338        f64,
339        BigEndian
340    );
341    fixed_read_method!(
342        "Asynchronously reads a little-endian `f64`.",
343        read_f64_le_async,
344        f64,
345        LittleEndian
346    );
347}
348
349impl<R> AsyncBinaryReadExt for R where R: AsyncInput<Item = u8> + ?Sized {}
350
351/// Reads and decodes one fixed-width value asynchronously.
352///
353/// # Type Parameters
354///
355/// - `N`: Encoded scalar width in bytes.
356/// - `T`: Decoded value type.
357/// - `R`: Source asynchronous byte input.
358/// - `F`: Infallible decoding callback.
359///
360/// # Parameters
361///
362/// - `reader`: Source from which the fixed-width payload is read.
363/// - `decode`: Callback that decodes the initialized local buffer.
364///
365/// # Returns
366///
367/// Returns the decoded value.
368///
369/// # Errors
370///
371/// Returns an input error, including an unexpected-end-of-input error when the
372/// payload is truncated.
373///
374/// # Cancellation safety
375///
376/// This operation is not cancellation safe. Dropping it retains bytes already
377/// consumed from `reader`.
378async fn read_binary_async<const N: usize, T, R, F>(reader: &mut R, decode: F) -> Result<T>
379where
380    R: AsyncInput<Item = u8> + Unpin + ?Sized,
381    F: FnOnce(&[u8]) -> T,
382{
383    let mut bytes = [0_u8; N];
384    read_exactly_async(reader, &mut bytes).await?;
385    Ok(decode(&bytes))
386}