use std::path::PathBuf;
use std::io::{Write, Read};
use std::fs::{File, create_dir, OpenOptions};
#[derive(Clone)]
pub struct IO {
pub path: PathBuf
}
impl IO {
pub fn locate(path: &'static str) -> Self {
let home_dir = dirs::home_dir().unwrap();
let luna = home_dir.join(".luna");
if luna.exists() == false {
create_dir(&luna).unwrap();
}
let target = luna.join(path);
File::create(&target).unwrap();
IO { path: target }
}
pub fn clean(&self) {
std::fs::remove_file(&self.path).unwrap()
}
pub fn push<B>(&self, data: B)
where B: std::convert::AsRef<[u8]> {
let mut file = OpenOptions::new()
.write(true).open(&self.path).unwrap();
file.write_all(data.as_ref()).unwrap();
file.flush().unwrap()
}
pub fn pull(&self) -> Vec<u8> {
let mut file = File::open(&self.path).unwrap();
let mut content = vec![];
file.read_to_end(&mut content).unwrap();
content
}
}
#[cfg(test)]
mod tests {
use super::IO;
#[test]
fn handler() {
let file = IO::locate("test_file");
assert_eq!(file.path.exists(), true);
file.push(b"halo, spaceboy");
assert_eq!(file.pull(), b"halo, spaceboy");
file.clean();
assert_eq!(file.path.exists(), false);
}
}