taos_query/util/
inline_write.rs

1use tokio::io::{AsyncWrite, AsyncWriteExt};
2
3use super::AsyncInlinable;
4
5#[async_trait::async_trait]
6pub trait AsyncInlinableWrite: AsyncWrite + Send + Unpin {
7    #[inline]
8    /// Write `usize` length as little endian `N` bytes.
9    async fn write_len_with_width<const N: usize>(&mut self, len: usize) -> std::io::Result<usize> {
10        self.write_all(&len.to_le_bytes()[0..N]).await?;
11        Ok(N)
12    }
13
14    #[inline]
15    /// Write inlined bytes to writer with specific length width `N`.
16    ///
17    /// The inlined bytes are constructed as:
18    ///
19    /// ```text
20    /// +--------------+-----------------+
21    /// | len: N bytes | data: len bytes |
22    /// +--------------+-----------------+
23    /// ```
24    ///
25    ///  ## Safety
26    ///
27    ///  Write inlined bytes may not be safe if the input bytes length overflows to the width.
28    ///  For example, write `256` bytes with length width `1` is not safe.
29    async fn write_inlined_bytes<const N: usize>(
30        &mut self,
31        bytes: &[u8],
32    ) -> std::io::Result<usize> {
33        debug_assert_eq!(bytes.len() >> (N * 8), 0); // bytes.len() < (2 ^ (8 * N))
34        let len = &bytes.len().to_le_bytes()[0..N];
35        self.write_all(len).await?;
36        self.write_all(bytes).await?;
37        Ok(N + bytes.len())
38    }
39
40    #[inline]
41    /// Write inlined string with specific length width `N`.
42    async fn write_inlined_str<const N: usize>(&mut self, s: &str) -> std::io::Result<usize> {
43        self.write_inlined_bytes::<N>(s.as_bytes()).await
44    }
45
46    #[inline]
47    /// Write an inlinable object.
48    async fn write_inlinable<T: AsyncInlinable + Sync>(
49        &mut self,
50        value: &T,
51    ) -> std::io::Result<usize>
52    where
53        Self: Sized,
54    {
55        // self.write_inlinable(value).await
56        T::write_inlined(value, self).await
57    }
58}
59
60impl<T> AsyncInlinableWrite for T where T: AsyncWrite + Send + Unpin {}