use std::fs::File;
use std::io::prelude::*;
use crate::crypto;
use crate::error::{Error, Result};
use crate::etree::ParseOps;
pub fn load(hexhash: &str, paops: &mut ParseOps) -> Result<Vec<u8>> {
hex::decode(hexhash).map_err(|_| Error::Cas(format!("Not a valid hex token: {}", hexhash)))?;
let mut path = paops.io.casdir.clone();
path.push(hexhash);
let mut file_in = File::open(&path)
.map_err(|e| Error::Cas(format!("Failed to open {}: {}", path.display(), e)))?;
let mut blob = Vec::new();
let bytes = file_in
.read_to_end(&mut blob)
.map_err(|e| Error::Cas(format!("Error reading {}: {}", path.display(), e)))?;
if paops.io.verbose {
eprintln!("cas::load(): {} bytes from {}", bytes, path.display());
}
let verify = crypto::hexdigest("sha3-256", &blob, &*paops.crypto.policy)?;
if hexhash != verify {
return Err(Error::Cas(format!(
"CONTENT HASH MISMATCH!\ninput = {}\ncheck = {}",
hexhash, verify
)));
}
Ok(blob)
}
pub fn save(blob: Vec<u8>, paops: &mut ParseOps) -> Result<String> {
let hexhash = crypto::hexdigest("sha3-256", &blob, &*paops.crypto.policy)?;
let mut path = paops.io.casdir.clone();
path.push(&hexhash);
if path.is_file() {
if paops.io.verbose {
eprintln!("cas::save(): {} already exists. Exiting.", path.display());
}
return Ok(hexhash);
}
let mut file_out = File::create(&path)
.map_err(|e| Error::Cas(format!("Failed to open {}: {}", path.display(), e)))?;
let bytes = file_out.write(&blob).map_err(|e| {
Error::Cas(format!(
"Error writing {} bytes to {}: {}",
blob.len(),
path.display(),
e
))
})?;
if paops.io.verbose {
eprintln!("cas::save(): {} bytes to {}", bytes, path.display());
}
Ok(hexhash)
}