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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
//! A storage.

use crate::prelude::*;

/// A storage.
#[derive(Clone, Debug, Eq, PartialEq, Reflect)]
pub enum Storage {
    #[cfg(not(target_family = "wasm"))]
    Filesystem { path: PathBuf },
    #[cfg(target_family = "wasm")]
    LocalStorage { key: String },
    #[cfg(target_family = "wasm")]
    SessionStorage { key: String },
}

impl Storage {
    /// Initializes the storage.
    pub fn initialize(&self) -> Result<(), PersistenceError> {
        match self {
            #[cfg(not(target_family = "wasm"))]
            Storage::Filesystem { path } => {
                if let Some(parent) = path.parent() {
                    std::fs::create_dir_all(parent)?;
                }
            },
            #[cfg(target_family = "wasm")]
            Storage::LocalStorage { .. } => {},
            #[cfg(target_family = "wasm")]
            Storage::SessionStorage { .. } => {},
        }
        Ok(())
    }

    /// Gets if the storage is occupied.
    pub fn occupied(&self) -> bool {
        match self {
            #[cfg(not(target_family = "wasm"))]
            Storage::Filesystem { path } => path.exists(),
            #[cfg(target_family = "wasm")]
            Storage::LocalStorage { key } => {
                use gloo_storage::{
                    LocalStorage,
                    Storage,
                };
                matches!(LocalStorage::raw().get_item(key), Ok(Some(_)))
            },
            #[cfg(target_family = "wasm")]
            Storage::SessionStorage { key } => {
                use gloo_storage::{
                    SessionStorage,
                    Storage,
                };
                matches!(SessionStorage::raw().get_item(key), Ok(Some(_)))
            },
        }
    }

    /// Reads a resource from the storage.
    pub fn read<R: Serialize + DeserializeOwned>(
        &self,
        name: &str,
        format: StorageFormat,
    ) -> Result<R, PersistenceError> {
        match self {
            #[cfg(not(target_family = "wasm"))]
            Storage::Filesystem { path } => {
                let bytes = std::fs::read(path)?;
                format.deserialize::<R>(name, &bytes)
            },
            #[cfg(target_family = "wasm")]
            Storage::LocalStorage { key } => {
                use gloo_storage::{
                    LocalStorage,
                    Storage,
                };

                #[cfg(feature = "json")]
                if format == StorageFormat::Json {
                    return Ok(LocalStorage::get::<R>(key)?);
                }
                #[cfg(all(feature = "json", feature = "pretty"))]
                if format == StorageFormat::JsonPretty {
                    return Ok(LocalStorage::get::<R>(key)?);
                }

                #[cfg(feature = "bincode")]
                if format == StorageFormat::Bincode {
                    let bytes = LocalStorage::get::<Vec<u8>>(key)?;
                    return format.deserialize::<R>(name, &bytes);
                }

                let content = LocalStorage::get::<String>(key)?;
                format.deserialize::<R>(name, content.as_bytes())
            },
            #[cfg(target_family = "wasm")]
            Storage::SessionStorage { key } => {
                use gloo_storage::{
                    SessionStorage,
                    Storage,
                };

                #[cfg(feature = "json")]
                if format == StorageFormat::Json {
                    return Ok(SessionStorage::get::<R>(key)?);
                }
                #[cfg(all(feature = "json", feature = "pretty"))]
                if format == StorageFormat::JsonPretty {
                    return Ok(SessionStorage::get::<R>(key)?);
                }

                #[cfg(feature = "bincode")]
                if format == StorageFormat::Bincode {
                    let bytes = SessionStorage::get::<Vec<u8>>(key)?;
                    return format.deserialize::<R>(name, &bytes);
                }

                let content = SessionStorage::get::<String>(key)?;
                format.deserialize::<R>(name, content.as_bytes())
            },
        }
    }

    /// Writes a resource to the storage.
    pub fn write<R: Serialize + DeserializeOwned>(
        &self,
        name: &str,
        format: StorageFormat,
        resource: &R,
    ) -> Result<(), PersistenceError> {
        match self {
            #[cfg(not(target_family = "wasm"))]
            Storage::Filesystem { path } => {
                let bytes = format.serialize(name, resource)?;

                use std::io::Write;
                std::fs::OpenOptions::new()
                    .create(true)
                    .truncate(true)
                    .write(true)
                    .open(path)
                    .and_then(|mut file| file.write_all(&bytes))?;
            },
            #[cfg(target_family = "wasm")]
            Storage::LocalStorage { key } => {
                use gloo_storage::{
                    LocalStorage,
                    Storage,
                };

                #[cfg(feature = "json")]
                if format == StorageFormat::Json {
                    LocalStorage::set::<&R>(key, resource)?;
                    return Ok(());
                }
                #[cfg(all(feature = "json", feature = "pretty"))]
                if format == StorageFormat::JsonPretty {
                    LocalStorage::set::<&R>(key, resource)?;
                    return Ok(());
                }

                #[cfg(feature = "bincode")]
                if format == StorageFormat::Bincode {
                    let bytes = format.serialize(name, resource)?;
                    LocalStorage::set::<&[u8]>(key, &bytes)?;
                    return Ok(());
                }

                let bytes = format.serialize(name, resource)?;

                // unwrapping is okay in this case because
                // remaining storage formats all return a string
                // and that string is converted to bytes
                let string = std::str::from_utf8(&bytes).unwrap();
                LocalStorage::set::<&str>(key, string)?;
            },
            #[cfg(target_family = "wasm")]
            Storage::SessionStorage { key } => {
                use gloo_storage::{
                    SessionStorage,
                    Storage,
                };

                #[cfg(feature = "json")]
                if format == StorageFormat::Json {
                    SessionStorage::set::<&R>(key, resource)?;
                    return Ok(());
                }
                #[cfg(all(feature = "json", feature = "pretty"))]
                if format == StorageFormat::JsonPretty {
                    SessionStorage::set::<&R>(key, resource)?;
                    return Ok(());
                }

                #[cfg(feature = "bincode")]
                if format == StorageFormat::Bincode {
                    let bytes = format.serialize(name, resource)?;
                    SessionStorage::set::<&[u8]>(key, &bytes)?;
                    return Ok(());
                }

                let bytes = format.serialize(name, resource)?;

                // unwrapping is okay in this case because
                // remaining storage formats all return a string
                // and that string is converted to bytes
                let string = std::str::from_utf8(&bytes).unwrap();
                SessionStorage::set::<&str>(key, string)?;
            },
        }
        Ok(())
    }
}

impl Display for Storage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            #[cfg(not(target_family = "wasm"))]
            Storage::Filesystem { path } => {
                if let Some(path) = path.to_str() {
                    write!(f, "{}", path)
                } else {
                    write!(f, "{:?}", path)
                }
            },
            #[cfg(target_family = "wasm")]
            Storage::LocalStorage { key } => {
                let separator = std::path::MAIN_SEPARATOR;
                write!(f, "{}local{}{}", separator, separator, key)
            },
            #[cfg(target_family = "wasm")]
            Storage::SessionStorage { key } => {
                let separator = std::path::MAIN_SEPARATOR;
                write!(f, "{}session{}{}", separator, separator, key)
            },
        }
    }
}