use std::io;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
use digest::Digest;
use crate::AsyncByteInput;
use crate::AsyncInput;
use crate::DigestAllFuture;
use crate::traits::validate_read_count;
#[must_use]
#[derive(Debug)]
pub struct AsyncDigestInput<I, D> {
inner: I,
hasher: D,
}
impl<I, D> AsyncDigestInput<I, D>
where
D: Digest,
{
#[inline(always)]
pub const fn new(inner: I, hasher: D) -> Self {
Self { inner, hasher }
}
#[inline]
pub fn digest_all(input: Pin<&mut I>) -> DigestAllFuture<'_, I, D>
where
I: AsyncByteInput,
{
DigestAllFuture::new(input)
}
#[inline]
#[must_use]
pub fn digest(&self) -> digest::Output<D>
where
D: Clone,
{
self.hasher.clone().finalize()
}
#[inline]
#[must_use]
pub fn finalize(self) -> (I, digest::Output<D>) {
(self.inner, self.hasher.finalize())
}
#[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) -> &D {
&self.hasher
}
#[inline(always)]
#[must_use]
pub fn hasher_mut(&mut self) -> &mut D {
&mut self.hasher
}
#[inline(always)]
#[must_use]
pub fn into_parts(self) -> (I, D) {
(self.inner, self.hasher)
}
}
impl<I, D> AsyncInput for AsyncDigestInput<I, D>
where
I: AsyncByteInput,
D: Digest,
{
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.update(&output[index..index + read]);
}
Poll::Ready(Ok(read))
}
Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
Poll::Pending => Poll::Pending,
}
}
}