use std::io;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
use crate::AsyncInput;
#[must_use]
#[derive(Debug)]
pub struct AsyncCountingInput<I> {
inner: I,
items_read: u64,
}
impl<I> AsyncCountingInput<I> {
#[inline(always)]
pub const fn new(inner: I) -> Self {
Self { inner, items_read: 0 }
}
#[inline(always)]
#[must_use]
pub const fn items_read(&self) -> u64 {
self.items_read
}
#[inline(always)]
#[must_use]
pub const fn inner(&self) -> &I {
&self.inner
}
#[inline(always)]
#[must_use]
pub fn inner_mut(&mut self) -> &mut I {
&mut self.inner
}
#[inline(always)]
#[must_use]
pub fn into_inner(self) -> I {
self.inner
}
}
impl<I> AsyncCountingInput<I>
where
I: AsyncInput<Item = u8>,
{
#[inline(always)]
#[must_use]
pub const fn bytes_read(&self) -> u64 {
self.items_read
}
}
impl<I> AsyncInput for AsyncCountingInput<I>
where
I: AsyncInput,
{
type Item = I::Item;
#[inline(always)]
fn is_buffered(&self) -> bool {
self.inner.is_buffered()
}
unsafe fn poll_read_unchecked(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
output: &mut [Self::Item],
index: usize,
count: usize,
) -> Poll<io::Result<usize>> {
let this = unsafe { self.as_mut().get_unchecked_mut() };
let destination = &mut output[index..index + count];
let inner = unsafe { Pin::new_unchecked(&mut this.inner) };
match inner.poll_read(cx, destination) {
Poll::Ready(Ok(read)) => {
let read_u64 = u64::try_from(read).unwrap_or(u64::MAX);
this.items_read = this.items_read.saturating_add(read_u64);
Poll::Ready(Ok(read))
}
Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
Poll::Pending => Poll::Pending,
}
}
}