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;
49 ZigZagCodec::<$ty, NonStrict>::MAX_ENCODE_UNITS_PER_VALUE];
50 type Codec = ZigZagCodec<$ty, NonStrict>;
51 let len = unsafe {
54 encode_infallible_unchecked::<Codec>(value, &mut bytes, 0)
55 };
56 write_all_async(self, &bytes[..len]).await
57 }
58 }
59 };
60}
61
62pub trait AsyncZigZagWriteExt: AsyncOutput<Item = u8> {
69 zig_zag_write_method!(
70 "Asynchronously writes ZigZag `i8`.",
71 write_zig_zag_i8_async,
72 i8
73 );
74 zig_zag_write_method!(
75 "Asynchronously writes ZigZag `i16`.",
76 write_zig_zag_i16_async,
77 i16
78 );
79 zig_zag_write_method!(
80 "Asynchronously writes ZigZag `i32`.",
81 write_zig_zag_i32_async,
82 i32
83 );
84 zig_zag_write_method!(
85 "Asynchronously writes ZigZag `i64`.",
86 write_zig_zag_i64_async,
87 i64
88 );
89 zig_zag_write_method!(
90 "Asynchronously writes ZigZag `i128`.",
91 write_zig_zag_i128_async,
92 i128
93 );
94 zig_zag_write_method!(
95 "Asynchronously writes ZigZag `isize`.",
96 write_zig_zag_isize_async,
97 isize
98 );
99}
100
101impl<W> AsyncZigZagWriteExt for W where W: AsyncOutput<Item = u8> + ?Sized {}