1use std::path::PathBuf;
5
6pub trait LedgerStorage: Send + Sync {
7 fn load(&self) -> Result<Option<Vec<u8>>, String>;
8 fn save(&self, bytes: &[u8]) -> Result<(), String>;
9}
10
11pub struct FileStorage {
14 path: PathBuf,
15}
16
17impl FileStorage {
18 pub fn new(path: impl Into<PathBuf>) -> Self {
19 Self { path: path.into() }
20 }
21}
22
23impl LedgerStorage for FileStorage {
24 fn load(&self) -> Result<Option<Vec<u8>>, String> {
25 match std::fs::read(&self.path) {
26 Ok(b) => Ok(Some(b)),
27 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
28 Err(e) => Err(e.to_string()),
29 }
30 }
31 fn save(&self, bytes: &[u8]) -> Result<(), String> {
32 if let Some(dir) = self.path.parent() {
33 std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
34 }
35 rightkit_fs::atomic_write_private(&self.path, bytes).map_err(|e| e.to_string())
36 }
37}