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: CustomPersistorMarker<IO, V, S, D>,
83}
84
85#[allow(type_alias_bounds)]
86type CustomPersistorMarker<IO, V, S, D: ?Sized> = PhantomData<(IO, V, S, fn(&D))>;
87
88impl<V, S, D, IO, Ser, De> CustomPersistor<V, S, D, IO, Ser, De>
89where
90 V: Serialize + DeserializeOwned,
91 D: ?Sized,
92 IO: PersistorIO<S>,
93 Ser: Fn(&V) -> Result<S>,
94 De: Fn(&D) -> Result<V>,
95 S: AsRef<D>,
96{
97 pub fn new(ser: Ser, de: De, id: String, scope: Scope, suffix: Option<String>) -> Self {
98 Self {
99 ser,
100 de,
101 id,
102 scope,
103 suffix,
104 _marker: PhantomData,
105 }
106 }
107}
108
109#[cfg(feature = "json")]
110pub type JsonFilePersistor<V> = CustomPersistor<
111 V,
112 String,
113 str,
114 AsyncFileStringIO,
115 fn(&V) -> Result<String>,
116 fn(&str) -> Result<V>,
117>;
118
119#[cfg(feature = "json")]
120fn serialize_json<V: Serialize>(value: &V) -> Result<String> {
121 Ok(serde_json::to_string(value)?)
122}
123
124#[cfg(feature = "json")]
125fn deserialize_json<V: DeserializeOwned>(value: &str) -> Result<V> {
126 Ok(serde_json::from_str(value)?)
127}
128
129impl<V, S, D, IO, Ser, De> Persistor<V> for CustomPersistor<V, S, D, IO, Ser, De>
130where
131 V: Serialize + DeserializeOwned,
132 D: ?Sized,
133 IO: PersistorIO<S>,
134 Ser: Fn(&V) -> Result<S>,
135 De: Fn(&D) -> Result<V>,
136 S: AsRef<D>,
137{
138 async fn load(&self) -> Result<Option<V>> {
139 let path = self
140 .scope
141 .get_full_path(&self.id, self.suffix.clone())
142 .await?;
143 let data = IO::read(path).await?;
144 match data {
145 Some(d) => Ok(Some((self.de)(d.as_ref())?)),
146 None => Ok(None),
147 }
148 }
149
150 async fn save(&self, value: &V) -> Result<()> {
151 let data = (self.ser)(value)?;
152 let path = self
153 .scope
154 .get_full_path(&self.id, self.suffix.clone())
155 .await?;
156 IO::write(path, data).await?;
157 Ok(())
158 }
159}
160
161#[cfg(feature = "json")]
162pub fn json_persistor<V: Serialize + DeserializeOwned>(
163 id: String,
164 scope: Scope,
165) -> JsonFilePersistor<V> {
166 CustomPersistor::new(
167 serialize_json::<V>,
168 deserialize_json::<V>,
169 id,
170 scope,
171 Some("json".to_string()),
172 )
173}
174
175#[cfg(feature = "toml")]
176pub type TomlFilePersistor<V> = CustomPersistor<
177 V,
178 String,
179 str,
180 AsyncFileStringIO,
181 fn(&V) -> Result<String>,
182 fn(&str) -> Result<V>,
183>;
184
185#[cfg(feature = "toml")]
186fn serialize_toml<V: Serialize>(value: &V) -> Result<String> {
187 Ok(toml::to_string(value)?)
188}
189
190#[cfg(feature = "toml")]
191fn deserialize_toml<V: DeserializeOwned>(value: &str) -> Result<V> {
192 Ok(toml::from_str(value)?)
193}
194
195#[cfg(feature = "toml")]
196pub fn toml_persistor<V: Serialize + DeserializeOwned>(
197 id: String,
198 scope: Scope,
199) -> TomlFilePersistor<V> {
200 CustomPersistor::new(
201 serialize_toml::<V>,
202 deserialize_toml::<V>,
203 id,
204 scope,
205 Some("toml".to_string()),
206 )
207}