use std::hash::Hasher;
use std::io;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
use crate::AsyncClose;
use crate::AsyncOutput;
use crate::traits::normalize_async_error;
#[must_use]
#[derive(Debug)]
pub struct AsyncChecksumOutput<O, H> {
inner: O,
hasher: H,
}
impl<O, H> AsyncClose for AsyncChecksumOutput<O, H>
where
O: AsyncClose<Item = u8>,
H: Hasher,
{
#[inline(always)]
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let this = unsafe { self.get_unchecked_mut() };
unsafe { Pin::new_unchecked(&mut this.inner) }
.poll_close(cx)
.map(|result| result.map_err(normalize_async_error))
}
}
impl<O, H> AsyncChecksumOutput<O, H>
where
H: Hasher,
{
#[inline(always)]
pub const fn new(inner: O, 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) -> &O {
&self.inner
}
#[inline(always)]
#[must_use]
pub fn inner_mut(&mut self) -> &mut O {
&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) -> (O, H) {
(self.inner, self.hasher)
}
}
impl<O, H> AsyncOutput for AsyncChecksumOutput<O, H>
where
O: AsyncOutput<Item = u8>,
H: Hasher,
{
type Item = u8;
#[inline(always)]
fn is_buffered(&self) -> bool {
self.inner.is_buffered()
}
unsafe fn poll_write_unchecked(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
input: &[u8],
index: usize,
count: usize,
) -> Poll<io::Result<usize>> {
let this = unsafe { self.as_mut().get_unchecked_mut() };
let source = &input[index..index + count];
let inner = unsafe { Pin::new_unchecked(&mut this.inner) };
match inner.poll_write(cx, source) {
Poll::Ready(Ok(written)) => {
this.hasher.write(&input[index..index + written]);
Poll::Ready(Ok(written))
}
Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
Poll::Pending => Poll::Pending,
}
}
#[inline(always)]
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let this = unsafe { self.get_unchecked_mut() };
unsafe { Pin::new_unchecked(&mut this.inner) }
.poll_flush(cx)
.map(|result| result.map_err(normalize_async_error))
}
}