use std::hash::Hasher;
use std::io;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
use crate::AsyncByteInput;
use crate::AsyncInput;
use crate::traits::validate_read_count;
#[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 = "inspect the wrapped input"]
pub const fn inner(&self) -> &I {
&self.inner
}
#[inline(always)]
#[must_use = "inspect the current hasher state"]
pub const fn hasher(&self) -> &H {
&self.hasher
}
#[inline(always)]
#[must_use = "use the returned reference to access the wrapped input"]
pub fn inner_mut(&mut self) -> &mut I {
&mut self.inner
}
#[inline(always)]
#[must_use = "use the returned reference to access the hasher"]
pub fn hasher_mut(&mut self) -> &mut H {
&mut self.hasher
}
#[inline(always)]
#[must_use = "retain the wrapped input and final hasher state"]
pub fn into_parts(self) -> (I, H) {
(self.inner, self.hasher)
}
}
impl<I, H> AsyncInput for AsyncChecksumInput<I, H>
where
I: AsyncByteInput,
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 requested = destination.len();
let inner = unsafe { Pin::new_unchecked(&mut this.inner) };
match inner.poll_read(cx, destination) {
Poll::Ready(Ok(read)) => {
if let Err(error) = validate_read_count(read, requested) {
return Poll::Ready(Err(error));
}
if read != 0 {
this.hasher.write(&output[index..index + read]);
}
Poll::Ready(Ok(read))
}
Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
Poll::Pending => Poll::Pending,
}
}
}