Skip to main content

qubit_io_binary/ext/
async_binary_write_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 writes.
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::AsyncOutput;
18
19use crate::util::encode_infallible_unchecked;
20use crate::util::write_all_async;
21
22macro_rules! write_binary_value_async {
23    ($writer:expr, $value:expr, $ty:ty, $order:ty) => {
24        write_binary_async::<{ BinaryCodec::<$ty, $order>::MAX_ENCODE_UNITS_PER_VALUE }, _, _, _>(
25            $writer,
26            $value,
27            |bytes, value| {
28                type Codec = BinaryCodec<$ty, $order>;
29                // SAFETY: The local buffer has exactly the codec's fixed width.
30                unsafe {
31                    let _ = encode_infallible_unchecked::<Codec>(value, bytes, 0);
32                }
33            },
34        )
35        .await
36    };
37}
38
39macro_rules! fixed_write_method {
40    ($doc:literal, $name:ident, $ty:ty, $order:ty) => {
41        #[doc = $doc]
42        #[doc = ""]
43        #[doc = "# Parameters"]
44        #[doc = ""]
45        #[doc = "- `value`: Value to encode and write."]
46        #[doc = ""]
47        #[doc = "# Returns"]
48        #[doc = ""]
49        #[doc = "Returns a future that completes after all encoded bytes have \
50                 been written."]
51        #[doc = ""]
52        #[doc = "# Errors"]
53        #[doc = ""]
54        #[doc = "Returns an output error, including a write-zero error when \
55                 the output stops making progress."]
56        #[doc = ""]
57        #[doc = "# Cancellation safety"]
58        #[doc = ""]
59        #[doc = "This operation is not cancellation safe. Dropping the future \
60                 retains any bytes already written to the output."]
61        #[inline(always)]
62        fn $name(&mut self, value: $ty) -> impl Future<Output = Result<()>> + '_
63        where
64            Self: Unpin,
65        {
66            async move { write_binary_value_async!(self, value, $ty, $order) }
67        }
68    };
69}
70
71macro_rules! runtime_order_write_method {
72    ($doc:literal, $name:ident, $ty:ty, $big:ident, $little:ident) => {
73        #[doc = $doc]
74        #[doc = ""]
75        #[doc = "# Parameters"]
76        #[doc = ""]
77        #[doc = "- `value`: Value to encode and write."]
78        #[doc = "- `byte_order`: Byte order used to encode the value."]
79        #[doc = ""]
80        #[doc = "# Returns"]
81        #[doc = ""]
82        #[doc = "Returns a future that completes after all encoded bytes have \
83                 been written."]
84        #[doc = ""]
85        #[doc = "# Errors"]
86        #[doc = ""]
87        #[doc = "Returns an output error, including a write-zero error when \
88                 the output stops making progress."]
89        #[doc = ""]
90        #[doc = "# Cancellation safety"]
91        #[doc = ""]
92        #[doc = "This operation is not cancellation safe. Dropping the future \
93                 retains any bytes already written to the output."]
94        #[inline]
95        fn $name(&mut self, value: $ty, byte_order: ByteOrder) -> impl Future<Output = Result<()>> + '_
96        where
97            Self: Unpin,
98        {
99            async move {
100                if use_big_endian(byte_order) {
101                    self.$big(value).await
102                } else {
103                    self.$little(value).await
104                }
105            }
106        }
107    };
108}
109
110/// Resolves a runtime byte-order choice to a big-endian branch.
111///
112/// # Parameters
113///
114/// - `byte_order`: Runtime byte-order selection.
115///
116/// # Returns
117///
118/// Returns `true` for big endian, `false` for little endian, and the target's
119/// native ordering for [`ByteOrder::NativeEndian`].
120#[must_use]
121#[inline]
122const fn use_big_endian(byte_order: ByteOrder) -> bool {
123    match byte_order {
124        ByteOrder::BigEndian => true,
125        ByteOrder::LittleEndian => false,
126        ByteOrder::NativeEndian => cfg!(target_endian = "big"),
127    }
128}
129
130/// Future-based fixed-width binary writes to runtime-neutral async outputs.
131///
132/// # Cancellation safety
133///
134/// These writes are not cancellation safe. Dropping a pending future leaves
135/// any already-written prefix in the output; retrying can duplicate that
136/// prefix.
137pub trait AsyncBinaryWriteExt: AsyncOutput<Item = u8> {
138    fixed_write_method!(
139        "Asynchronously writes an unsigned 8-bit integer.",
140        write_u8_async,
141        u8,
142        BigEndian
143    );
144    fixed_write_method!(
145        "Asynchronously writes a signed 8-bit integer.",
146        write_i8_async,
147        i8,
148        BigEndian
149    );
150
151    runtime_order_write_method!(
152        "Asynchronously writes a `u16` using a runtime byte order.",
153        write_u16_async,
154        u16,
155        write_u16_be_async,
156        write_u16_le_async
157    );
158
159    fixed_write_method!(
160        "Asynchronously writes a big-endian `u16`.",
161        write_u16_be_async,
162        u16,
163        BigEndian
164    );
165    fixed_write_method!(
166        "Asynchronously writes a little-endian `u16`.",
167        write_u16_le_async,
168        u16,
169        LittleEndian
170    );
171
172    runtime_order_write_method!(
173        "Asynchronously writes a `u32` using a runtime byte order.",
174        write_u32_async,
175        u32,
176        write_u32_be_async,
177        write_u32_le_async
178    );
179
180    fixed_write_method!(
181        "Asynchronously writes a big-endian `u32`.",
182        write_u32_be_async,
183        u32,
184        BigEndian
185    );
186    fixed_write_method!(
187        "Asynchronously writes a little-endian `u32`.",
188        write_u32_le_async,
189        u32,
190        LittleEndian
191    );
192
193    runtime_order_write_method!(
194        "Asynchronously writes a `u64` using a runtime byte order.",
195        write_u64_async,
196        u64,
197        write_u64_be_async,
198        write_u64_le_async
199    );
200
201    fixed_write_method!(
202        "Asynchronously writes a big-endian `u64`.",
203        write_u64_be_async,
204        u64,
205        BigEndian
206    );
207    fixed_write_method!(
208        "Asynchronously writes a little-endian `u64`.",
209        write_u64_le_async,
210        u64,
211        LittleEndian
212    );
213
214    runtime_order_write_method!(
215        "Asynchronously writes a `u128` using a runtime byte order.",
216        write_u128_async,
217        u128,
218        write_u128_be_async,
219        write_u128_le_async
220    );
221
222    fixed_write_method!(
223        "Asynchronously writes a big-endian `u128`.",
224        write_u128_be_async,
225        u128,
226        BigEndian
227    );
228    fixed_write_method!(
229        "Asynchronously writes a little-endian `u128`.",
230        write_u128_le_async,
231        u128,
232        LittleEndian
233    );
234
235    runtime_order_write_method!(
236        "Asynchronously writes an `i16` using a runtime byte order.",
237        write_i16_async,
238        i16,
239        write_i16_be_async,
240        write_i16_le_async
241    );
242
243    fixed_write_method!(
244        "Asynchronously writes a big-endian `i16`.",
245        write_i16_be_async,
246        i16,
247        BigEndian
248    );
249    fixed_write_method!(
250        "Asynchronously writes a little-endian `i16`.",
251        write_i16_le_async,
252        i16,
253        LittleEndian
254    );
255
256    runtime_order_write_method!(
257        "Asynchronously writes an `i32` using a runtime byte order.",
258        write_i32_async,
259        i32,
260        write_i32_be_async,
261        write_i32_le_async
262    );
263
264    fixed_write_method!(
265        "Asynchronously writes a big-endian `i32`.",
266        write_i32_be_async,
267        i32,
268        BigEndian
269    );
270    fixed_write_method!(
271        "Asynchronously writes a little-endian `i32`.",
272        write_i32_le_async,
273        i32,
274        LittleEndian
275    );
276
277    runtime_order_write_method!(
278        "Asynchronously writes an `i64` using a runtime byte order.",
279        write_i64_async,
280        i64,
281        write_i64_be_async,
282        write_i64_le_async
283    );
284
285    fixed_write_method!(
286        "Asynchronously writes a big-endian `i64`.",
287        write_i64_be_async,
288        i64,
289        BigEndian
290    );
291    fixed_write_method!(
292        "Asynchronously writes a little-endian `i64`.",
293        write_i64_le_async,
294        i64,
295        LittleEndian
296    );
297
298    runtime_order_write_method!(
299        "Asynchronously writes an `i128` using a runtime byte order.",
300        write_i128_async,
301        i128,
302        write_i128_be_async,
303        write_i128_le_async
304    );
305
306    fixed_write_method!(
307        "Asynchronously writes a big-endian `i128`.",
308        write_i128_be_async,
309        i128,
310        BigEndian
311    );
312    fixed_write_method!(
313        "Asynchronously writes a little-endian `i128`.",
314        write_i128_le_async,
315        i128,
316        LittleEndian
317    );
318
319    runtime_order_write_method!(
320        "Asynchronously writes an `f32` using a runtime byte order.",
321        write_f32_async,
322        f32,
323        write_f32_be_async,
324        write_f32_le_async
325    );
326
327    fixed_write_method!(
328        "Asynchronously writes a big-endian `f32`.",
329        write_f32_be_async,
330        f32,
331        BigEndian
332    );
333    fixed_write_method!(
334        "Asynchronously writes a little-endian `f32`.",
335        write_f32_le_async,
336        f32,
337        LittleEndian
338    );
339
340    runtime_order_write_method!(
341        "Asynchronously writes an `f64` using a runtime byte order.",
342        write_f64_async,
343        f64,
344        write_f64_be_async,
345        write_f64_le_async
346    );
347
348    fixed_write_method!(
349        "Asynchronously writes a big-endian `f64`.",
350        write_f64_be_async,
351        f64,
352        BigEndian
353    );
354    fixed_write_method!(
355        "Asynchronously writes a little-endian `f64`.",
356        write_f64_le_async,
357        f64,
358        LittleEndian
359    );
360}
361
362impl<W> AsyncBinaryWriteExt for W where W: AsyncOutput<Item = u8> + ?Sized {}
363
364/// Encodes and writes one fixed-width value asynchronously.
365///
366/// # Type Parameters
367///
368/// - `N`: Encoded scalar width in bytes.
369/// - `T`: Value type accepted by the encoder.
370/// - `W`: Destination asynchronous byte output.
371/// - `F`: Infallible encoding callback.
372///
373/// # Parameters
374///
375/// - `writer`: Destination for the fixed-width payload.
376/// - `value`: Value passed to `encode`.
377/// - `encode`: Callback that fills the local payload buffer.
378///
379/// # Returns
380///
381/// Returns after the complete payload has been written.
382///
383/// # Errors
384///
385/// Returns an output error, including a write-zero error when the output stops
386/// making progress.
387///
388/// # Cancellation safety
389///
390/// This operation is not cancellation safe. Dropping it leaves an
391/// already-written prefix in `writer`.
392async fn write_binary_async<const N: usize, T, W, F>(writer: &mut W, value: T, encode: F) -> Result<()>
393where
394    W: AsyncOutput<Item = u8> + Unpin + ?Sized,
395    F: FnOnce(&mut [u8], T),
396{
397    let mut bytes = [0_u8; N];
398    encode(&mut bytes, value);
399    write_all_async(writer, &bytes).await
400}