arcis_interface/
path_with_hash.rs1use sha2::{Digest, Sha256};
2use std::io::Write;
3
4fn compute_hash(src: &[u8]) -> [u8; 32] {
5 Sha256::digest(src).into()
6}
7
8#[derive(Debug, Clone)]
9pub struct PathWithHash {
10 pub path: String,
11 pub hash: [u8; 32],
12}
13
14impl PathWithHash {
15 pub fn new(contents: &[u8], path: String) -> Result<Self, std::io::Error> {
16 let mut file = std::fs::File::create(&path)?;
17 file.write_all(contents)?;
18 let hash = compute_hash(contents);
19 Ok(PathWithHash { path, hash })
20 }
21 pub fn check(&self) -> bool {
22 let Ok(file) = std::fs::read(&self.path) else {
23 return false;
24 };
25 let hash = compute_hash(&file);
26 self.hash == hash
27 }
28 pub fn checked_read(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
29 let file = std::fs::read(&self.path)?;
30 let hash = compute_hash(&file);
31 if self.hash == hash {
32 Ok(file)
33 } else {
34 Err("Hash mismatch".into())
35 }
36 }
37}