use std::{
hash::Hasher,
io::{
self,
SeekFrom,
},
};
use crate::{
Input,
Seekable,
};
#[must_use]
#[derive(Debug)]
pub struct ChecksumInput<I, H> {
inner: I,
hasher: H,
}
impl<I, H> ChecksumInput<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> Input for ChecksumInput<I, H>
where
I: Input<Item = u8>,
H: Hasher,
{
type Item = u8;
#[inline(always)]
fn is_buffered(&self) -> bool {
self.inner.is_buffered()
}
#[inline]
unsafe fn read_unchecked(
&mut self,
output: &mut [u8],
index: usize,
count: usize,
) -> io::Result<usize> {
let read = self.inner.read(&mut output[index..index + count])?;
self.hasher.write(&output[index..index + read]);
Ok(read)
}
}
impl<I, H> Seekable for ChecksumInput<I, H>
where
I: Seekable,
H: Hasher,
{
type Unit = I::Unit;
#[inline(always)]
fn seek_to(&mut self, position: SeekFrom) -> io::Result<u64> {
self.inner.seek_to(position)
}
}