Last active
September 29, 2020 05:27
-
-
Save SharpCoder/0253587bc80785630fd07b1c3cf3c476 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::fs; | |
| use std::path::Path; | |
| pub trait Cache { | |
| fn write_file(&self, bucket: String, path: String, contents: String); | |
| fn write_json<Z : serde::ser::Serialize >(&self, bucket: String, path: String, model: Z); | |
| fn read_file(&self, bucket: String, path: String) -> Option<Vec<u8>>; | |
| fn read_json<Z : serde::de::DeserializeOwned>(&self, bucket: String, path: String) -> Option<Z>; | |
| } | |
| pub struct DataCache { | |
| base_path: String, | |
| } | |
| impl DataCache { | |
| pub fn new(base_path: String) -> DataCache { | |
| let base = Path::new(base_path.as_str()); | |
| assert!(base.exists(), "base data_cache path does not exist"); | |
| return DataCache { | |
| base_path: base_path, | |
| }; | |
| } | |
| pub fn from_default() -> DataCache { | |
| return DataCache::new("D:\\DATA_MIRROR\\".to_string()); | |
| } | |
| fn as_path(&self) -> &Path { | |
| return Path::new(self.base_path.as_str()); | |
| } | |
| } | |
| impl Cache for DataCache { | |
| fn write_file(&self, bucket: String, path: String, contents: String) { | |
| fs::write(self.as_path().join(bucket).join(path), contents).unwrap(); | |
| } | |
| fn write_json<Z : serde::ser::Serialize >(&self, bucket: String, path: String, model: Z) { | |
| self.write_file(bucket, path, serde_json::to_string(&model).unwrap()); | |
| } | |
| fn read_file(&self, bucket: String, path: String) -> Option<Vec<u8>> { | |
| return match fs::read(self.as_path().join(bucket).join(path)) { | |
| Err(err) => None, | |
| Ok(file) => Some(file), | |
| }; | |
| } | |
| fn read_json<Z : serde::de::DeserializeOwned>(&self, bucket: String, path: String) -> Option<Z> { | |
| return match self.read_file(bucket, path) { | |
| None => None, | |
| Some(file) => Some(serde_json::from_str(String::from_utf8_lossy(file.as_slice()).to_string().as_str()).unwrap()), | |
| }; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment