diff --git a/Cargo.toml b/Cargo.toml index d039647..32b5d53 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,3 +7,5 @@ edition = "2018" [dependencies] ssri = "0.2.0" hex = "0.3.2" +atomicwrites = "0.2.2" +tempfile = "3.0.8" diff --git a/src/content/mod.rs b/src/content/mod.rs index f47ce16..cea38ba 100644 --- a/src/content/mod.rs +++ b/src/content/mod.rs @@ -1,2 +1,3 @@ pub mod path; pub mod read; +pub mod write; diff --git a/src/content/write.rs b/src/content/write.rs new file mode 100644 index 0000000..c10df93 --- /dev/null +++ b/src/content/write.rs @@ -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 { + 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" + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index 91ed62f..286585c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ mod content; pub use crate::content::path; pub use crate::content::read; +pub use crate::content::write;