chug_cli/
validate.rs

1use std::io;
2
3use ring::digest::{self, SHA256};
4
5pub struct Validate<R> {
6    inner: R,
7    digest_context: digest::Context,
8    sha256: Vec<u8>,
9}
10
11impl<R: io::Read> Validate<R> {
12    pub(crate) fn new(inner: R, sha256: Vec<u8>) -> Self {
13        Validate {
14            inner,
15            digest_context: digest::Context::new(&SHA256),
16            sha256,
17        }
18    }
19
20    pub fn validate(self) -> anyhow::Result<()> {
21        let checksum = self.digest_context.finish();
22        anyhow::ensure!(
23            checksum.as_ref() == self.sha256.as_slice(),
24            "Checksum mismatch",
25        );
26        Ok(())
27    }
28}
29
30impl<R: io::Read> io::Read for Validate<R> {
31    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
32        let len = self.inner.read(buf)?;
33        self.digest_context.update(&buf[..len]);
34        Ok(len)
35    }
36}