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.
124///
125/// # Examples
126///
127/// ```
128/// use qubit_io_binary::AsyncBinaryReadExt;
129///
130/// async fn read_u16<R>(input: &mut R) -> std::io::Result<u16>
131/// where
132///     R: AsyncBinaryReadExt + Unpin,
133/// {
134///     input.read_u16_be_async().await
135/// }
136/// ```
137pub trait AsyncBinaryReadExt: AsyncInput<Item = u8> {
138    fixed_read_method!(
139        "Asynchronously reads an unsigned 8-bit integer.",
140        read_u8_async,
141        u8,
142        BigEndian
143    );
144    fixed_read_method!(
145        "Asynchronously reads a signed 8-bit integer.",
146        read_i8_async,
147        i8,
148        BigEndian
149    );
150
151    runtime_order_read_method!(
152        "Asynchronously reads a `u16` using a runtime byte order.",
153        read_u16_async,
154        u16,
155        read_u16_be_async,
156        read_u16_le_async
157    );
158
159    fixed_read_method!(
160        "Asynchronously reads a big-endian `u16`.",
161        read_u16_be_async,
162        u16,
163        BigEndian
164    );
165    fixed_read_method!(
166        "Asynchronously reads a little-endian `u16`.",
167        read_u16_le_async,
168        u16,
169        LittleEndian
170    );
171
172    runtime_order_read_method!(
173        "Asynchronously reads a `u32` using a runtime byte order.",
174        read_u32_async,
175        u32,
176        read_u32_be_async,
177        read_u32_le_async
178    );
179
180    fixed_read_method!(
181        "Asynchronously reads a big-endian `u32`.",
182        read_u32_be_async,
183        u32,
184        BigEndian
185    );
186    fixed_read_method!(
187        "Asynchronously reads a little-endian `u32`.",
188        read_u32_le_async,
189        u32,
190        LittleEndian
191    );
192
193    runtime_order_read_method!(
194        "Asynchronously reads a `u64` using a runtime byte order.",
195        read_u64_async,
196        u64,
197        read_u64_be_async,
198        read_u64_le_async
199    );
200
201    fixed_read_method!(
202        "Asynchronously reads a big-endian `u64`.",
203        read_u64_be_async,
204        u64,
205        BigEndian
206    );
207    fixed_read_method!(
208        "Asynchronously reads a little-endian `u64`.",
209        read_u64_le_async,
210        u64,
211        LittleEndian
212    );
213
214    runtime_order_read_method!(
215        "Asynchronously reads a `u128` using a runtime byte order.",
216        read_u128_async,
217        u128,
218        read_u128_be_async,
219        read_u128_le_async
220    );
221
222    fixed_read_method!(
223        "Asynchronously reads a big-endian `u128`.",
224        read_u128_be_async,
225        u128,
226        BigEndian
227    );
228    fixed_read_method!(
229        "Asynchronously reads a little-endian `u128`.",
230        read_u128_le_async,
231        u128,
232        LittleEndian
233    );
234
235    runtime_order_read_method!(
236        "Asynchronously reads an `i16` using a runtime byte order.",
237        read_i16_async,
238        i16,
239        read_i16_be_async,
240        read_i16_le_async
241    );
242
243    fixed_read_method!(
244        "Asynchronously reads a big-endian `i16`.",
245        read_i16_be_async,
246        i16,
247        BigEndian
248    );
249    fixed_read_method!(
250        "Asynchronously reads a little-endian `i16`.",
251        read_i16_le_async,
252        i16,
253        LittleEndian
254    );
255
256    runtime_order_read_method!(
257        "Asynchronously reads an `i32` using a runtime byte order.",
258        read_i32_async,
259        i32,
260        read_i32_be_async,
261        read_i32_le_async
262    );
263
264    fixed_read_method!(
265        "Asynchronously reads a big-endian `i32`.",
266        read_i32_be_async,
267        i32,
268        BigEndian
269    );
270    fixed_read_method!(
271        "Asynchronously reads a little-endian `i32`.",
272        read_i32_le_async,
273        i32,
274        LittleEndian
275    );
276
277    runtime_order_read_method!(
278        "Asynchronously reads an `i64` using a runtime byte order.",
279        read_i64_async,
280        i64,
281        read_i64_be_async,
282        read_i64_le_async
283    );
284
285    fixed_read_method!(
286        "Asynchronously reads a big-endian `i64`.",
287        read_i64_be_async,
288        i64,
289        BigEndian
290    );
291    fixed_read_method!(
292        "Asynchronously reads a little-endian `i64`.",
293        read_i64_le_async,
294        i64,
295        LittleEndian
296    );
297
298    runtime_order_read_method!(
299        "Asynchronously reads an `i128` using a runtime byte order.",
300        read_i128_async,
301        i128,
302        read_i128_be_async,
303        read_i128_le_async
304    );
305
306    fixed_read_method!(
307        "Asynchronously reads a big-endian `i128`.",
308        read_i128_be_async,
309        i128,
310        BigEndian
311    );
312    fixed_read_method!(
313        "Asynchronously reads a little-endian `i128`.",
314        read_i128_le_async,
315        i128,
316        LittleEndian
317    );
318
319    runtime_order_read_method!(
320        "Asynchronously reads an `f32` using a runtime byte order.",
321        read_f32_async,
322        f32,
323        read_f32_be_async,
324        read_f32_le_async
325    );
326
327    fixed_read_method!(
328        "Asynchronously reads a big-endian `f32`.",
329        read_f32_be_async,
330        f32,
331        BigEndian
332    );
333    fixed_read_method!(
334        "Asynchronously reads a little-endian `f32`.",
335        read_f32_le_async,
336        f32,
337        LittleEndian
338    );
339
340    runtime_order_read_method!(
341        "Asynchronously reads an `f64` using a runtime byte order.",
342        read_f64_async,
343        f64,
344        read_f64_be_async,
345        read_f64_le_async
346    );
347
348    fixed_read_method!(
349        "Asynchronously reads a big-endian `f64`.",
350        read_f64_be_async,
351        f64,
352        BigEndian
353    );
354    fixed_read_method!(
355        "Asynchronously reads a little-endian `f64`.",
356        read_f64_le_async,
357        f64,
358        LittleEndian
359    );
360}
361
362impl<R> AsyncBinaryReadExt for R where R: AsyncInput<Item = u8> + ?Sized {}
363
364/// Reads and decodes one fixed-width value asynchronously.
365///
366/// # Type Parameters
367///
368/// - `N`: Encoded scalar width in bytes.
369/// - `T`: Decoded value type.
370/// - `R`: Source asynchronous byte input.
371/// - `F`: Infallible decoding callback.
372///
373/// # Parameters
374///
375/// - `reader`: Source from which the fixed-width payload is read.
376/// - `decode`: Callback that decodes the initialized local buffer.
377///
378/// # Returns
379///
380/// Returns the decoded value.
381///
382/// # Errors
383///
384/// Returns an input error, including an unexpected-end-of-input error when the
385/// payload is truncated.
386///
387/// # Cancellation safety
388///
389/// This operation is not cancellation safe. Dropping it retains bytes already
390/// consumed from `reader`.
391async fn read_binary_async<const N: usize, T, R, F>(reader: &mut R, decode: F) -> Result<T>
392where
393    R: AsyncInput<Item = u8> + Unpin + ?Sized,
394    F: FnOnce(&[u8]) -> T,
395{
396    let mut bytes = [0_u8; N];
397    read_exactly_async(reader, &mut bytes).await?;
398    Ok(decode(&bytes))
399}