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