-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathstorage.rs
More file actions
43 lines (35 loc) · 926 Bytes
/
storage.rs
File metadata and controls
43 lines (35 loc) · 926 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
use std::fs;
// Abstract away storage to allow testing via dependency injection
pub trait Storage {
fn exists(&self) -> bool;
fn save(&self, state_toml: String);
fn read(&self) -> String;
}
// The struct used in production code
pub struct StorageImpl<'a> {
pub path: &'a str,
}
impl Storage for Box<dyn Storage + 'static> {
fn exists(&self) -> bool {
self.as_ref().exists()
}
fn save(&self, state_toml: String) {
self.as_ref().save(state_toml)
}
fn read(&self) -> String {
self.as_ref().read()
}
}
// The implementation used in production code
impl<'a> Storage for StorageImpl<'a> {
fn exists(&self) -> bool {
std::path::Path::new(self.path).exists()
}
fn save(&self, state_toml: String) {
fs::write(self.path, state_toml)
.unwrap_or_else(|_| panic!("Failed to write {}", self.path));
}
fn read(&self) -> String {
fs::read_to_string(self.path).expect("Failed to read state file {}")
}
}