use std::{
hash::Hasher,
io,
pin::Pin,
task::{
Context,
Poll,
},
};
use crate::AsyncInput;
#[must_use]
#[derive(Debug)]
pub struct AsyncChecksumInput<I, H> {
inner: I,
hasher: H,
}
impl<I, H> AsyncChecksumInput<I, H>
where
H: Hasher,
{
#[inline(always)]
pub const fn new(inner: I, hasher: H) -> Self {
Self { inner, hasher }
}
#[inline(always)]
#[must_use]
pub fn checksum(&self) -> u64 {
self.hasher.finish()
}
#[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 const fn hasher(&self) -> &H {
&self.hasher
}
#[inline(always)]
#[must_use]
pub fn hasher_mut(&mut self) -> &mut H {
&mut self.hasher
}
#[inline(always)]
#[must_use]
pub fn into_parts(self) -> (I, H) {
(self.inner, self.hasher)
}
}
impl<I, H> AsyncInput for AsyncChecksumInput<I, H>
where
I: AsyncInput<Item = u8>,
H: Hasher,
{
type Item = u8;
#[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 [u8],
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)) => {
this.hasher.write(&output[index..index + read]);
Poll::Ready(Ok(read))
}
Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
Poll::Pending => Poll::Pending,
}
}
}