use super::Read;
use core::{
pin::Pin,
task::{Context, Poll},
};
use void::Void;
pub trait AsyncRead {
type Error;
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context,
buf: &mut [u8],
) -> Poll<Result<usize, Self::Error>>;
fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Read<'a, Self>
where
Self: Unpin,
{
Read::new(self, buf)
}
}
macro_rules! deref_async_read {
() => {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context,
buf: &mut [u8],
) -> Poll<Result<usize, Self::Error>> {
Pin::new(&mut **self).poll_read(cx, buf)
}
};
}
#[cfg(feature = "alloc")]
impl<T: ?Sized + AsyncRead + Unpin> AsyncRead for Box<T> {
deref_async_read!();
}
impl<T: ?Sized + AsyncRead + Unpin> AsyncRead for &mut T {
type Error = T::Error;
deref_async_read!();
}
impl AsyncRead for &[u8] {
type Error = Void;
fn poll_read(
mut self: Pin<&mut Self>,
_cx: &mut Context,
buf: &mut [u8],
) -> Poll<Result<usize, Void>> {
let amt = core::cmp::min(self.len(), buf.len());
let (a, b) = self.split_at(amt);
buf[..amt].copy_from_slice(a);
*self = b;
Poll::Ready(Ok(amt))
}
}