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.
137///
138/// # Examples
139///
140/// Define a generic async helper that writes a big-endian marker:
141///
142/// ```
143/// use qubit_io::AsyncOutput;
144/// use qubit_io_binary::AsyncBinaryWriteExt;
145///
146/// async fn write_marker<O>(output: &mut O) -> std::io::Result<()>
147/// where
148///     O: AsyncOutput<Item = u8> + Unpin,
149/// {
150///     output.write_u32_be_async(0x5142_4954).await
151/// }
152/// ```
153pub trait AsyncBinaryWriteExt: AsyncOutput<Item = u8> {
154    fixed_write_method!(
155        "Asynchronously writes an unsigned 8-bit integer.",
156        write_u8_async,
157        u8,
158        BigEndian
159    );
160    fixed_write_method!(
161        "Asynchronously writes a signed 8-bit integer.",
162        write_i8_async,
163        i8,
164        BigEndian
165    );
166
167    runtime_order_write_method!(
168        "Asynchronously writes a `u16` using a runtime byte order.",
169        write_u16_async,
170        u16,
171        write_u16_be_async,
172        write_u16_le_async
173    );
174
175    fixed_write_method!(
176        "Asynchronously writes a big-endian `u16`.",
177        write_u16_be_async,
178        u16,
179        BigEndian
180    );
181    fixed_write_method!(
182        "Asynchronously writes a little-endian `u16`.",
183        write_u16_le_async,
184        u16,
185        LittleEndian
186    );
187
188    runtime_order_write_method!(
189        "Asynchronously writes a `u32` using a runtime byte order.",
190        write_u32_async,
191        u32,
192        write_u32_be_async,
193        write_u32_le_async
194    );
195
196    fixed_write_method!(
197        "Asynchronously writes a big-endian `u32`.",
198        write_u32_be_async,
199        u32,
200        BigEndian
201    );
202    fixed_write_method!(
203        "Asynchronously writes a little-endian `u32`.",
204        write_u32_le_async,
205        u32,
206        LittleEndian
207    );
208
209    runtime_order_write_method!(
210        "Asynchronously writes a `u64` using a runtime byte order.",
211        write_u64_async,
212        u64,
213        write_u64_be_async,
214        write_u64_le_async
215    );
216
217    fixed_write_method!(
218        "Asynchronously writes a big-endian `u64`.",
219        write_u64_be_async,
220        u64,
221        BigEndian
222    );
223    fixed_write_method!(
224        "Asynchronously writes a little-endian `u64`.",
225        write_u64_le_async,
226        u64,
227        LittleEndian
228    );
229
230    runtime_order_write_method!(
231        "Asynchronously writes a `u128` using a runtime byte order.",
232        write_u128_async,
233        u128,
234        write_u128_be_async,
235        write_u128_le_async
236    );
237
238    fixed_write_method!(
239        "Asynchronously writes a big-endian `u128`.",
240        write_u128_be_async,
241        u128,
242        BigEndian
243    );
244    fixed_write_method!(
245        "Asynchronously writes a little-endian `u128`.",
246        write_u128_le_async,
247        u128,
248        LittleEndian
249    );
250
251    runtime_order_write_method!(
252        "Asynchronously writes an `i16` using a runtime byte order.",
253        write_i16_async,
254        i16,
255        write_i16_be_async,
256        write_i16_le_async
257    );
258
259    fixed_write_method!(
260        "Asynchronously writes a big-endian `i16`.",
261        write_i16_be_async,
262        i16,
263        BigEndian
264    );
265    fixed_write_method!(
266        "Asynchronously writes a little-endian `i16`.",
267        write_i16_le_async,
268        i16,
269        LittleEndian
270    );
271
272    runtime_order_write_method!(
273        "Asynchronously writes an `i32` using a runtime byte order.",
274        write_i32_async,
275        i32,
276        write_i32_be_async,
277        write_i32_le_async
278    );
279
280    fixed_write_method!(
281        "Asynchronously writes a big-endian `i32`.",
282        write_i32_be_async,
283        i32,
284        BigEndian
285    );
286    fixed_write_method!(
287        "Asynchronously writes a little-endian `i32`.",
288        write_i32_le_async,
289        i32,
290        LittleEndian
291    );
292
293    runtime_order_write_method!(
294        "Asynchronously writes an `i64` using a runtime byte order.",
295        write_i64_async,
296        i64,
297        write_i64_be_async,
298        write_i64_le_async
299    );
300
301    fixed_write_method!(
302        "Asynchronously writes a big-endian `i64`.",
303        write_i64_be_async,
304        i64,
305        BigEndian
306    );
307    fixed_write_method!(
308        "Asynchronously writes a little-endian `i64`.",
309        write_i64_le_async,
310        i64,
311        LittleEndian
312    );
313
314    runtime_order_write_method!(
315        "Asynchronously writes an `i128` using a runtime byte order.",
316        write_i128_async,
317        i128,
318        write_i128_be_async,
319        write_i128_le_async
320    );
321
322    fixed_write_method!(
323        "Asynchronously writes a big-endian `i128`.",
324        write_i128_be_async,
325        i128,
326        BigEndian
327    );
328    fixed_write_method!(
329        "Asynchronously writes a little-endian `i128`.",
330        write_i128_le_async,
331        i128,
332        LittleEndian
333    );
334
335    runtime_order_write_method!(
336        "Asynchronously writes an `f32` using a runtime byte order.",
337        write_f32_async,
338        f32,
339        write_f32_be_async,
340        write_f32_le_async
341    );
342
343    fixed_write_method!(
344        "Asynchronously writes a big-endian `f32`.",
345        write_f32_be_async,
346        f32,
347        BigEndian
348    );
349    fixed_write_method!(
350        "Asynchronously writes a little-endian `f32`.",
351        write_f32_le_async,
352        f32,
353        LittleEndian
354    );
355
356    runtime_order_write_method!(
357        "Asynchronously writes an `f64` using a runtime byte order.",
358        write_f64_async,
359        f64,
360        write_f64_be_async,
361        write_f64_le_async
362    );
363
364    fixed_write_method!(
365        "Asynchronously writes a big-endian `f64`.",
366        write_f64_be_async,
367        f64,
368        BigEndian
369    );
370    fixed_write_method!(
371        "Asynchronously writes a little-endian `f64`.",
372        write_f64_le_async,
373        f64,
374        LittleEndian
375    );
376}
377
378impl<W> AsyncBinaryWriteExt for W where W: AsyncOutput<Item = u8> + ?Sized {}
379
380/// Encodes and writes one fixed-width value asynchronously.
381///
382/// # Type Parameters
383///
384/// - `N`: Encoded scalar width in bytes.
385/// - `T`: Value type accepted by the encoder.
386/// - `W`: Destination asynchronous byte output.
387/// - `F`: Infallible encoding callback.
388///
389/// # Parameters
390///
391/// - `writer`: Destination for the fixed-width payload.
392/// - `value`: Value passed to `encode`.
393/// - `encode`: Callback that fills the local payload buffer.
394///
395/// # Returns
396///
397/// Returns after the complete payload has been written.
398///
399/// # Errors
400///
401/// Returns an output error, including a write-zero error when the output stops
402/// making progress.
403///
404/// # Cancellation safety
405///
406/// This operation is not cancellation safe. Dropping it leaves an
407/// already-written prefix in `writer`.
408async fn write_binary_async<const N: usize, T, W, F>(writer: &mut W, value: T, encode: F) -> Result<()>
409where
410    W: AsyncOutput<Item = u8> + Unpin + ?Sized,
411    F: FnOnce(&mut [u8], T),
412{
413    let mut bytes = [0_u8; N];
414    encode(&mut bytes, value);
415    write_all_async(writer, &bytes).await
416}