| 1 | // Copyright (c) 2022 Harry [Majored] [[email protected]] |
| 2 | // MIT License (https://github.com/Majored/rs-async-zip/blob/main/LICENSE) |
| 3 | |
| 4 | use crate::base::read::io::poll_result_ok; |
| 5 | |
| 6 | use std::pin::Pin; |
| 7 | use std::task::{ready, Context, Poll}; |
| 8 | |
| 9 | use crc32fast::Hasher; |
| 10 | use futures_lite::io::AsyncRead; |
| 11 | use pin_project::pin_project; |
| 12 | |
| 13 | /// A wrapping reader which computes the CRC32 hash of data read via [`AsyncRead`]. |
| 14 | #[pin_project] |
| 15 | pub(crate) struct HashedReader<R> { |
| 16 | #[pin] |
| 17 | pub(crate) reader: R, |
| 18 | pub(crate) hasher: Hasher, |
| 19 | } |
| 20 | |
| 21 | impl<R> HashedReader<R> |
| 22 | where |
| 23 | R: AsyncRead + Unpin, |
| 24 | { |
| 25 | /// Constructs a new wrapping reader from a generic [`AsyncRead`] implementer. |
| 26 | pub(crate) fn new(reader: R) -> Self { |
| 27 | Self { reader, hasher: Hasher::default() } |
| 28 | } |
| 29 | |
| 30 | /// Swaps the internal hasher and returns the computed CRC32 hash. |
| 31 | /// |
| 32 | /// The internal hasher is taken and replaced with a newly-constructed one. As a result, this method should only be |
| 33 | /// called once EOF has been reached and it's known that no more data will be read, else the computed hash(s) won't |
| 34 | /// accurately represent the data read in. |
| 35 | pub(crate) fn swap_and_compute_hash(&mut self) -> u32 { |
| 36 | std::mem::take(&mut self.hasher).finalize() |
| 37 | } |
| 38 | |
| 39 | /// Consumes this reader and returns the inner value. |
| 40 | pub(crate) fn into_inner(self) -> R { |
| 41 | self.reader |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | impl<R> AsyncRead for HashedReader<R> |
| 46 | where |
| 47 | R: AsyncRead + Unpin, |
| 48 | { |
| 49 | fn poll_read(self: Pin<&mut Self>, c: &mut Context<'_>, b: &mut [u8]) -> Poll<std::io::Result<usize>> { |
| 50 | let project = self.project(); |
| 51 | let written = poll_result_ok!(ready!(project.reader.poll_read(c, b))); |
| 52 | project.hasher.update(&b[..written]); |
| 53 | |
| 54 | Poll::Ready(Ok(written)) |
| 55 | } |
| 56 | } |