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