variable_len_reader/asynchronous/
helper.rs

1use core::ops::{Deref, DerefMut};
2use crate::{AsyncVariableReader, AsyncVariableWriter};
3
4#[derive(Debug)]
5#[repr(transparent)]
6pub struct AsyncReaderHelper<'a, R: AsyncVariableReader + Unpin>(pub &'a mut R);
7
8impl<'a, R: AsyncVariableReader + Unpin> Deref for AsyncReaderHelper<'a, R> {
9    type Target = R;
10
11    fn deref(&self) -> &Self::Target {
12        &self.0
13    }
14}
15
16impl<'a, R: AsyncVariableReader + Unpin> DerefMut for AsyncReaderHelper<'a, R> {
17    fn deref_mut(&mut self) -> &mut Self::Target {
18        &mut self.0
19    }
20}
21
22impl<'a, R: AsyncVariableReader + Unpin> AsyncReaderHelper<'a, R> {
23    pub async fn help_read_u8_vec(&'a mut self) -> Result<alloc::vec::Vec<u8>, R::Error> {
24        let length = self.read_usize_varint_ap().await?;
25        let mut bytes = alloc::vec![0; length];
26        self.read_more(&mut bytes).await?;
27        Ok(bytes)
28    }
29
30    #[cfg(feature = "async_string")]
31    #[cfg_attr(docsrs, doc(cfg(feature = "async_string")))]
32    pub async fn help_read_string(&'a mut self) -> Result<alloc::string::String, R::Error> {
33        match alloc::string::String::from_utf8(self.help_read_u8_vec().await?) {
34            Ok(s) => Ok(s),
35            Err(e) => Err(R::read_string_error("ReadString", e)),
36        }
37    }
38}
39
40
41#[derive(Debug)]
42#[repr(transparent)]
43pub struct AsyncWriterHelper<'a, W: AsyncVariableWriter + Unpin>(pub &'a mut W);
44
45impl<'a, W: AsyncVariableWriter + Unpin> Deref for AsyncWriterHelper<'a, W> {
46    type Target = W;
47
48    fn deref(&self) -> &Self::Target {
49        &self.0
50    }
51}
52
53impl<'a, W: AsyncVariableWriter + Unpin> DerefMut for AsyncWriterHelper<'a, W> {
54    fn deref_mut(&mut self) -> &mut Self::Target {
55        &mut self.0
56    }
57}
58
59impl<'a, W: AsyncVariableWriter + Unpin> AsyncWriterHelper<'a, W> {
60    pub async fn help_write_u8_vec(&'a mut self, bytes: &[u8]) -> Result<(), W::Error> {
61        self.write_usize_varint_ap(bytes.len()).await?;
62        self.write_more(bytes).await?;
63        Ok(())
64    }
65
66    #[cfg(feature = "async_string")]
67    #[cfg_attr(docsrs, doc(cfg(feature = "async_string")))]
68    pub async fn help_write_string(&'a mut self, string: &str) -> Result<(), W::Error> {
69        self.help_write_u8_vec(string.as_bytes()).await?;
70        Ok(())
71    }
72}