Skip to main content

qubit_io_binary/ext/
async_zig_zag_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 ZigZag writes.
9
10use core::future::Future;
11use std::io::Result;
12
13use qubit_codec_binary::NonStrict;
14use qubit_codec_binary::ZigZagCodec;
15use qubit_io::AsyncOutput;
16
17use crate::util::encode_infallible_unchecked;
18use crate::util::write_all_async;
19
20macro_rules! zig_zag_write_method {
21    ($doc:literal, $name:ident, $ty:ty) => {
22        #[doc = $doc]
23        #[doc = ""]
24        #[doc = "# Parameters"]
25        #[doc = ""]
26        #[doc = "- `value`: Signed integer to encode and write."]
27        #[doc = ""]
28        #[doc = "# Returns"]
29        #[doc = ""]
30        #[doc = "Returns a future that completes after the encoded payload \
31                 has been written."]
32        #[doc = ""]
33        #[doc = "# Errors"]
34        #[doc = ""]
35        #[doc = "Returns an output error, including a write-zero error when \
36                 the output stops making progress."]
37        #[doc = ""]
38        #[doc = "# Cancellation safety"]
39        #[doc = ""]
40        #[doc = "This operation is not cancellation safe. Dropping the future \
41                 retains any bytes already written to the output."]
42        #[inline(always)]
43        fn $name(&mut self, value: $ty) -> impl Future<Output = Result<()>> + '_
44        where
45            Self: Unpin,
46        {
47            async move {
48                let mut bytes = [0_u8; ZigZagCodec::<$ty, NonStrict>::MAX_ENCODE_UNITS_PER_VALUE];
49                type Codec = ZigZagCodec<$ty, NonStrict>;
50                // SAFETY: The local buffer has the codec's maximum payload
51                // size.
52                let len = unsafe { encode_infallible_unchecked::<Codec>(value, &mut bytes, 0) };
53                write_all_async(self, &bytes[..len]).await
54            }
55        }
56    };
57}
58
59/// Future-based ZigZag plus unsigned-LEB128 writes.
60///
61/// # Cancellation safety
62///
63/// These writes are not cancellation safe. Dropping a pending future leaves
64/// an already-written prefix in the output.
65///
66/// # Examples
67///
68/// ```
69/// use qubit_io::AsyncOutput;
70/// use qubit_io_binary::AsyncZigZagWriteExt;
71///
72/// async fn write_value<O>(output: &mut O) -> std::io::Result<()>
73/// where
74///     O: AsyncOutput<Item = u8> + Unpin,
75/// {
76///     output.write_zig_zag_i32_async(-150).await
77/// }
78/// ```
79pub trait AsyncZigZagWriteExt: AsyncOutput<Item = u8> {
80    zig_zag_write_method!("Asynchronously writes ZigZag `i8`.", write_zig_zag_i8_async, i8);
81    zig_zag_write_method!("Asynchronously writes ZigZag `i16`.", write_zig_zag_i16_async, i16);
82    zig_zag_write_method!("Asynchronously writes ZigZag `i32`.", write_zig_zag_i32_async, i32);
83    zig_zag_write_method!("Asynchronously writes ZigZag `i64`.", write_zig_zag_i64_async, i64);
84    zig_zag_write_method!("Asynchronously writes ZigZag `i128`.", write_zig_zag_i128_async, i128);
85    zig_zag_write_method!(
86        "Asynchronously writes ZigZag `isize`.",
87        write_zig_zag_isize_async,
88        isize
89    );
90}
91
92impl<W> AsyncZigZagWriteExt for W where W: AsyncOutput<Item = u8> + ?Sized {}