variable_len_reader/asynchronous/
mod.rs

1use core::pin::Pin;
2use core::task::{Context, Poll, ready};
3use crate::util::read_buf::ReadBuf;
4use crate::util::write_buf::WriteBuf;
5
6pub mod reader;
7pub mod writer;
8#[cfg(feature = "async_string")]
9#[cfg_attr(docsrs, doc(cfg(feature = "async_string")))]
10pub mod helper;
11
12pub trait AsyncVariableReadable {
13    type Error;
14
15    fn poll_read_single(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut Option<u8>) -> Poll<Result<u8, Self::Error>>;
16
17    fn poll_read_more(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<Result<(), Self::Error>> {
18        while buf.left() > 0 {
19            buf.put(ready!(self.as_mut().poll_read_single(cx, &mut None))?);
20        }
21        Poll::Ready(Ok(()))
22    }
23
24    #[cfg(feature = "bytes")]
25    #[cfg_attr(docsrs, doc(cfg(feature = "bytes")))]
26    #[inline]
27    fn poll_read_more_buf<'a, B: bytes::BufMut>(mut self: Pin<&mut Self>, cx: &mut Context<'_>, bytes: &'a mut B) -> Poll<Result<(), Self::Error>> {
28        use bytes::BufMut;
29        while bytes.has_remaining_mut() {
30            let chunk = bytes.chunk_mut();
31            let chunk = unsafe {&mut *core::ptr::slice_from_raw_parts_mut(chunk.as_mut_ptr(), chunk.len()) };
32            let mut buf = ReadBuf::new(chunk);
33            let res = self.as_mut().poll_read_more(cx, &mut buf);
34            let position = buf.position();
35            unsafe { bytes.advance_mut(position); }
36            ready!(res)?;
37        }
38        Poll::Ready(Ok(()))
39    }
40}
41
42pub trait AsyncVariableWritable {
43    type Error;
44
45    fn poll_write_single(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut Option<u8>) -> Poll<Result<(), Self::Error>>;
46
47    fn poll_write_more(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut WriteBuf<'_>) -> Poll<Result<(), Self::Error>> {
48        while buf.left() > 0 {
49            ready!(self.as_mut().poll_write_single(cx, &mut Some(buf.get())))?;
50            buf.skip(1);
51        }
52        Poll::Ready(Ok(()))
53    }
54
55    #[cfg(feature = "bytes")]
56    #[cfg_attr(docsrs, doc(cfg(feature = "bytes")))]
57    #[inline]
58    fn poll_write_more_buf<'a, B: bytes::Buf>(mut self: Pin<&mut Self>, cx: &mut Context<'_>, bytes: &'a mut B) -> Poll<Result<(), Self::Error>> {
59        use bytes::Buf;
60        while bytes.has_remaining() {
61            let chunk = bytes.chunk();
62            let mut buf = WriteBuf::new(chunk);
63            let res = self.as_mut().poll_write_more(cx, &mut buf);
64            let position = buf.position();
65            bytes.advance(position);
66            ready!(res)?;
67        }
68        Poll::Ready(Ok(()))
69    }
70}