use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
use tokio::io::AsyncRead;
use tokio::io::ReadBuf;
use crate::AsyncByteInput;
use crate::traits::normalize_async_error;
use crate::traits::validate_read_count;
#[must_use]
#[repr(transparent)]
pub struct TokioAsyncRead<I> {
inner: I,
}
impl<I> TokioAsyncRead<I> {
#[inline(always)]
pub const fn new(inner: I) -> Self {
Self { inner }
}
#[inline(always)]
#[must_use = "the wrapped input reference must be used"]
pub const fn get_ref(&self) -> &I {
&self.inner
}
#[inline(always)]
#[must_use = "the mutable wrapped input reference must be used"]
pub const fn get_mut(&mut self) -> &mut I {
&mut self.inner
}
#[inline(always)]
#[must_use = "the pinned wrapped input reference must be used"]
pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut I> {
unsafe { self.map_unchecked_mut(|this| &mut this.inner) }
}
#[inline(always)]
#[must_use = "the wrapped input must be used"]
pub fn into_inner(self) -> I {
self.inner
}
}
impl<I> AsyncRead for TokioAsyncRead<I>
where
I: AsyncByteInput,
{
#[inline]
fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, output: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
let requested = output.remaining();
if requested == 0 {
return Poll::Ready(Ok(()));
}
self.get_pin_mut()
.poll_read(cx, output.initialize_unfilled())
.map(|result| {
let read = result.map_err(normalize_async_error)?;
validate_read_count(read, requested)?;
output.advance(read);
Ok(())
})
}
}