1use crate::error::SettingsError;
2use std::path::{Path, PathBuf};
3use std::sync::Mutex;
4
5pub trait SettingsBackend: Send + Sync {
7 fn load(&self) -> Result<Vec<u8>, SettingsError>;
8 fn save(&self, data: &[u8]) -> Result<(), SettingsError>;
9 fn exists(&self) -> bool;
10 fn delete(&self) -> Result<(), SettingsError>;
11}
12
13pub struct JsonFileBackend {
15 path: PathBuf,
16}
17
18impl JsonFileBackend {
19 pub fn new(path: impl Into<PathBuf>) -> Self {
20 Self { path: path.into() }
21 }
22
23 pub fn path(&self) -> &Path {
24 &self.path
25 }
26}
27
28impl SettingsBackend for JsonFileBackend {
29 fn load(&self) -> Result<Vec<u8>, SettingsError> {
30 if !self.path.exists() {
31 return Ok(Vec::new());
32 }
33
34 let temp_path = self.path.with_extension("tmp");
36 if temp_path.exists() {
37 let _ = std::fs::remove_file(&temp_path);
38 }
39
40 std::fs::read(&self.path).map_err(SettingsError::Io)
41 }
42
43 fn save(&self, data: &[u8]) -> Result<(), SettingsError> {
44 if let Some(parent) = self.path.parent() {
45 std::fs::create_dir_all(parent)?;
46 }
47
48 let temp_path = self
49 .path
50 .with_extension(format!("tmp.{}", std::process::id()));
51
52 std::fs::write(&temp_path, data)?;
53
54 #[cfg(target_os = "windows")]
55 let _ = std::fs::remove_file(&self.path);
56
57 std::fs::rename(&temp_path, &self.path)?;
58
59 Ok(())
60 }
61
62 fn exists(&self) -> bool {
63 self.path.exists()
64 }
65
66 fn delete(&self) -> Result<(), SettingsError> {
67 if self.path.exists() {
68 std::fs::remove_file(&self.path)?;
69 }
70 Ok(())
71 }
72}
73
74pub struct MemoryBackend {
76 data: Mutex<Vec<u8>>,
77}
78
79impl MemoryBackend {
80 pub fn new() -> Self {
81 Self {
82 data: Mutex::new(Vec::new()),
83 }
84 }
85
86 pub fn with_data(data: Vec<u8>) -> Self {
87 Self {
88 data: Mutex::new(data),
89 }
90 }
91}
92
93impl Default for MemoryBackend {
94 fn default() -> Self {
95 Self::new()
96 }
97}
98
99impl SettingsBackend for MemoryBackend {
100 fn load(&self) -> Result<Vec<u8>, SettingsError> {
101 let guard = self
102 .data
103 .lock()
104 .map_err(|e| SettingsError::LockPoisoned(e.to_string()))?;
105 Ok(guard.clone())
106 }
107
108 fn save(&self, data: &[u8]) -> Result<(), SettingsError> {
109 let mut guard = self
110 .data
111 .lock()
112 .map_err(|e| SettingsError::LockPoisoned(e.to_string()))?;
113 *guard = data.to_vec();
114 Ok(())
115 }
116
117 fn exists(&self) -> bool {
118 let guard = self.data.lock().unwrap_or_else(|e| e.into_inner());
119 !guard.is_empty()
120 }
121
122 fn delete(&self) -> Result<(), SettingsError> {
123 let mut guard = self
124 .data
125 .lock()
126 .map_err(|e| SettingsError::LockPoisoned(e.to_string()))?;
127 guard.clear();
128 Ok(())
129 }
130}