qubit_io_binary/ext/
async_zig_zag_write_ext.rs1use 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 let len = unsafe { encode_infallible_unchecked::<Codec>(value, &mut bytes, 0) };
53 write_all_async(self, &bytes[..len]).await
54 }
55 }
56 };
57}
58
59pub 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 {}