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