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