feat(write): initial hack for write

This commit is contained in:
Kat Marchán 2019-05-22 19:42:17 -07:00
parent e98bfb17da
commit e452fdcd16
No known key found for this signature in database
GPG Key ID: AEB529C08A3C7E9E
4 changed files with 40 additions and 0 deletions

View File

@ -7,3 +7,5 @@ edition = "2018"
[dependencies]
ssri = "0.2.0"
hex = "0.3.2"
atomicwrites = "0.2.2"
tempfile = "3.0.8"

View File

@ -1,2 +1,3 @@
pub mod path;
pub mod read;
pub mod write;

36
src/content/write.rs Normal file
View File

@ -0,0 +1,36 @@
use atomicwrites::{AtomicFile, AllowOverwrite};
use crate::content::path;
use ssri::{Algorithm, Integrity};
use std::fs::DirBuilder;
use std::io::{self, prelude::*};
use std::path::Path;
pub fn write(cache: &Path, data: &[u8]) -> io::Result<Integrity> {
let sri = Integrity::from(&data, Algorithm::Sha256);
let cpath = path::content_path(&cache, &sri);
DirBuilder::new().recursive(true).create(cpath.parent().unwrap())?;
let file = AtomicFile::new(&cpath, AllowOverwrite);
file.write(|f| f.write_all(&data))?;
Ok(sri)
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile;
#[test]
fn basic_write() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().to_owned();
println!("dir: {}", dir.to_str().unwrap());
let sri = write(&dir, b"hello world").unwrap();
assert_eq!(
sri.to_string(),
Integrity::from(b"hello world", Algorithm::Sha256).to_string()
);
assert_eq!(
std::fs::read(path::content_path(&dir, &sri)).unwrap(),
b"hello world"
);
}
}

View File

@ -1,3 +1,4 @@
mod content;
pub use crate::content::path;
pub use crate::content::read;
pub use crate::content::write;