1use crate::{error::Result, scope::Scope, version::Persistor};
2use serde::Serialize;
3use serde::de::DeserializeOwned;
4use std::{io::ErrorKind, marker::PhantomData, path::PathBuf, sync::Arc};
5use tokio::fs::{read_to_string, write};
6use tokio::sync::Mutex;
7
8pub struct NoPersistor;
9
10impl<V> Persistor<V> for NoPersistor {
11 async fn load(&self) -> Result<Option<V>> {
12 Ok(None)
13 }
14
15 async fn save(&self, _value: &V) -> Result<()> {
16 Ok(())
17 }
18}
19
20#[derive(Clone, Default)]
21pub struct MemoryPersistor<V> {
22 value: Arc<Mutex<Option<V>>>,
23}
24
25impl<V> MemoryPersistor<V> {
26 pub fn new(value: Option<V>) -> Self {
27 Self {
28 value: Arc::new(Mutex::new(value)),
29 }
30 }
31}
32
33impl<V> Persistor<V> for MemoryPersistor<V>
34where
35 V: Clone,
36{
37 async fn load(&self) -> Result<Option<V>> {
38 Ok(self.value.lock().await.clone())
39 }
40
41 async fn save(&self, value: &V) -> Result<()> {
42 self.value.lock().await.replace(value.clone());
43 Ok(())
44 }
45}
46
47pub trait PersistorIO<S> {
48 fn read(path: PathBuf) -> impl Future<Output = Result<Option<S>>>;
49 fn write(path: PathBuf, data: S) -> impl Future<Output = Result<()>>;
50}
51
52pub struct AsyncFileStringIO;
53
54impl PersistorIO<String> for AsyncFileStringIO {
55 async fn read(path: PathBuf) -> Result<Option<String>> {
56 match read_to_string(&path).await {
57 Ok(d) => Ok(Some(d)),
58 Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
59 Err(e) => Err(e.into()),
60 }
61 }
62
63 async fn write(path: PathBuf, data: String) -> Result<()> {
64 write(&path, data).await?;
65 Ok(())
66 }
67}
68
69pub struct CustomPersistor<
70 V: Serialize + DeserializeOwned,
71 S,
72 D: ?Sized,
73 IO: PersistorIO<S>,
74 Ser: Fn(&V) -> Result<S>,
75 De: Fn(&D) -> Result<V>,
76> {
77 pub ser: Ser,
78 pub de: De,
79 pub id: String,
80 pub scope: Scope,
81 pub suffix: Option<String>,
82 _marker: PhantomData<(IO, V, S, *const D)>,
83}
84
85impl<V, S, D, IO, Ser, De> CustomPersistor<V, S, D, IO, Ser, De>
86where
87 V: Serialize + DeserializeOwned,
88 D: ?Sized,
89 IO: PersistorIO<S>,
90 Ser: Fn(&V) -> Result<S>,
91 De: Fn(&D) -> Result<V>,
92 S: AsRef<D>,
93{
94 pub fn new(ser: Ser, de: De, id: String, scope: Scope, suffix: Option<String>) -> Self {
95 Self {
96 ser,
97 de,
98 id,
99 scope,
100 suffix,
101 _marker: PhantomData,
102 }
103 }
104}
105
106#[cfg(feature = "json")]
107pub type JsonFilePersistor<V> = CustomPersistor<
108 V,
109 String,
110 str,
111 AsyncFileStringIO,
112 fn(&V) -> Result<String>,
113 fn(&str) -> Result<V>,
114>;
115
116#[cfg(feature = "json")]
117fn serialize_json<V: Serialize>(value: &V) -> Result<String> {
118 Ok(serde_json::to_string(value)?)
119}
120
121#[cfg(feature = "json")]
122fn deserialize_json<V: DeserializeOwned>(value: &str) -> Result<V> {
123 Ok(serde_json::from_str(value)?)
124}
125
126impl<V, S, D, IO, Ser, De> Persistor<V> for CustomPersistor<V, S, D, IO, Ser, De>
127where
128 V: Serialize + DeserializeOwned,
129 D: ?Sized,
130 IO: PersistorIO<S>,
131 Ser: Fn(&V) -> Result<S>,
132 De: Fn(&D) -> Result<V>,
133 S: AsRef<D>,
134{
135 async fn load(&self) -> Result<Option<V>> {
136 let path = self
137 .scope
138 .get_full_path(&self.id, self.suffix.clone())
139 .await?;
140 let data = IO::read(path).await?;
141 match data {
142 Some(d) => Ok(Some((self.de)(d.as_ref())?)),
143 None => Ok(None),
144 }
145 }
146
147 async fn save(&self, value: &V) -> Result<()> {
148 let data = (self.ser)(value)?;
149 let path = self
150 .scope
151 .get_full_path(&self.id, self.suffix.clone())
152 .await?;
153 IO::write(path, data).await?;
154 Ok(())
155 }
156}
157
158#[cfg(feature = "json")]
159pub fn json_persistor<V: Serialize + DeserializeOwned>(
160 id: String,
161 scope: Scope,
162) -> JsonFilePersistor<V> {
163 CustomPersistor::new(
164 serialize_json::<V>,
165 deserialize_json::<V>,
166 id,
167 scope,
168 Some("json".to_string()),
169 )
170}
171
172#[cfg(feature = "toml")]
173pub type TomlFilePersistor<V> = CustomPersistor<
174 V,
175 String,
176 str,
177 AsyncFileStringIO,
178 fn(&V) -> Result<String>,
179 fn(&str) -> Result<V>,
180>;
181
182#[cfg(feature = "toml")]
183fn serialize_toml<V: Serialize>(value: &V) -> Result<String> {
184 Ok(toml::to_string(value)?)
185}
186
187#[cfg(feature = "toml")]
188fn deserialize_toml<V: DeserializeOwned>(value: &str) -> Result<V> {
189 Ok(toml::from_str(value)?)
190}
191
192#[cfg(feature = "toml")]
193pub fn toml_persistor<V: Serialize + DeserializeOwned>(
194 id: String,
195 scope: Scope,
196) -> TomlFilePersistor<V> {
197 CustomPersistor::new(
198 serialize_toml::<V>,
199 deserialize_toml::<V>,
200 id,
201 scope,
202 Some("toml".to_string()),
203 )
204}