use std::io::prelude::*;
use std::hash::{Hash, Hasher};
use std::fs::File;
use std::path::Path;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::collections::hash_map::DefaultHasher;
use serde_json;
use errors::*;
pub fn hash_by_serialize<T>(data: &T, pretty: bool) -> Result<(String, u64)>
where
T: Serialize,
{
let serializer = match pretty {
true => serde_json::to_string_pretty,
false => serde_json::to_string,
};
let mut hasher = DefaultHasher::new();
let serialized = serializer(data)
.chain_err(|| "Failed to serialize for hashing")?;
serialized.hash(&mut hasher);
Ok((serialized, hasher.finish()))
}
pub fn just_load<T>(path: &Path) -> Result<T>
where
T: DeserializeOwned,
{
let mut file = File::open(path)
.chain_err(|| format!("Failed to open file: {:?}", &path))?;
let mut contents = String::new();
let _ = file.read_to_string(&mut contents);
serde_json::from_str(&contents).chain_err(|| "Deserialize error")
}
pub fn just_write<T>(contents: &T, path: &Path, pretty: bool) -> Result<()>
where
T: Serialize,
{
let serializer = match pretty {
true => serde_json::to_string_pretty,
false => serde_json::to_string,
};
just_write_string(&serializer(contents)
.chain_err(|| "Failed to serialize")?, path)
}
pub fn just_write_string(contents: &str, path: &Path) -> Result<()>
{
let mut file = File::create(path)
.chain_err(|| format!("Failed to create file: {:?}", path))?;
let _ = file.write_all(contents.as_bytes())
.chain_err(|| "Failed to write to file")?;
Ok(())
}