1use ferravex_play::persistence::{MAX_SAVE_BYTES, SaveData, SaveError};
3#[cfg(target_arch = "wasm32")]
4mod browser;
5#[cfg(not(target_arch = "wasm32"))]
6pub(crate) mod native;
7#[cfg(not(target_arch = "wasm32"))]
8pub use native::FileStore;
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum StorageError {
11 Unavailable,
12 TooLarge,
13 InvalidKey,
14 Protected,
15 GenerationExhausted,
16 Invalid(SaveError),
17 DurabilityUncertain,
18}
19impl From<SaveError> for StorageError {
20 fn from(v: SaveError) -> Self {
21 Self::Invalid(v)
22 }
23}
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum LoadStatus {
26 Missing,
27 Loaded,
28 Transient,
29 Rejected(StorageError),
30}
31pub trait Backend {
32 fn is_transient(&self) -> bool {
33 false
34 }
35 fn load(&self, owner: &str, slot: &str, limit: usize) -> Result<Option<Vec<u8>>, StorageError>;
36 fn store(&self, owner: &str, slot: &str, bytes: &[u8]) -> Result<(), StorageError>;
39}
40pub(crate) fn valid_name(value: &str) -> bool {
41 !value.is_empty()
42 && value.len() <= 64
43 && value
44 .bytes()
45 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"-_".contains(&b))
46 && !matches!(value, "con" | "prn" | "aux" | "nul")
47 && !(value.len() == 4
48 && (value.starts_with("com") || value.starts_with("lpt"))
49 && matches!(value.as_bytes()[3], b'1'..=b'9'))
50}
51fn validate(owner: &str, slot: &str, limit: usize) -> Result<(), StorageError> {
52 if !valid_name(owner) || !valid_name(slot) {
53 return Err(StorageError::InvalidKey);
54 }
55 if limit > MAX_SAVE_BYTES {
56 return Err(StorageError::TooLarge);
57 }
58 Ok(())
59}
60pub struct PlatformStore {
63 transient: bool,
64 #[cfg(not(target_arch = "wasm32"))]
65 files: Option<FileStore>,
66}
67impl Default for PlatformStore {
68 fn default() -> Self {
69 Self::new()
70 }
71}
72impl PlatformStore {
73 pub fn new() -> Self {
74 #[cfg(not(target_arch = "wasm32"))]
75 let transient = std::env::args()
76 .any(|a| matches!(a.as_str(), "--autoplay" | "--smoke-frames" | "--frames"));
77 #[cfg(target_arch = "wasm32")]
78 let transient = crate::autoplay_enabled();
79 Self {
80 transient,
81 #[cfg(not(target_arch = "wasm32"))]
82 files: FileStore::platform().ok(),
83 }
84 }
85 pub fn transient() -> Self {
86 Self {
87 transient: true,
88 #[cfg(not(target_arch = "wasm32"))]
89 files: None,
90 }
91 }
92 pub fn is_transient(&self) -> bool {
93 self.transient
94 }
95}
96impl Backend for PlatformStore {
97 fn is_transient(&self) -> bool {
98 self.transient
99 }
100 fn load(&self, owner: &str, slot: &str, limit: usize) -> Result<Option<Vec<u8>>, StorageError> {
101 validate(owner, slot, limit)?;
102 if self.transient {
103 return Ok(None);
104 }
105 #[cfg(not(target_arch = "wasm32"))]
106 {
107 self.files
108 .as_ref()
109 .ok_or(StorageError::Unavailable)?
110 .load(owner, slot, limit)
111 }
112 #[cfg(target_arch = "wasm32")]
113 {
114 browser::load(owner, slot, limit)
115 }
116 }
117 fn store(&self, owner: &str, slot: &str, bytes: &[u8]) -> Result<(), StorageError> {
118 validate(owner, slot, bytes.len())?;
119 if self.transient {
120 return Ok(());
121 }
122 #[cfg(not(target_arch = "wasm32"))]
123 {
124 self.files
125 .as_ref()
126 .ok_or(StorageError::Unavailable)?
127 .store(owner, slot, bytes)
128 }
129 #[cfg(target_arch = "wasm32")]
130 {
131 browser::store(owner, slot, bytes)
132 }
133 }
134}
135pub struct Slot<T: SaveData, B: Backend = PlatformStore> {
138 owner: String,
139 name: String,
140 value: T,
141 generation: u64,
142 status: LoadStatus,
143 protected: bool,
144 backend: B,
145}
146impl<T: SaveData> Slot<T> {
147 pub fn open(owner: &str, name: &str, default: T) -> Result<Self, StorageError> {
148 Self::with_backend(owner, name, default, PlatformStore::new())
149 }
150}
151impl<T: SaveData, B: Backend> Slot<T, B> {
152 pub fn with_backend(
153 owner: &str,
154 name: &str,
155 default: T,
156 backend: B,
157 ) -> Result<Self, StorageError> {
158 validate(owner, name, T::MAX_BYTES)?;
159 default.encode(0)?;
160 let mut value = default;
161 let mut generation = 0;
162 let mut protected = false;
163 let status = match backend.load(owner, name, T::MAX_BYTES) {
164 Ok(None) => {
165 if backend.is_transient() {
166 LoadStatus::Transient
167 } else {
168 LoadStatus::Missing
169 }
170 }
171 Ok(Some(bytes)) => match T::decode(&bytes) {
172 Ok((loaded, stamp)) => {
173 value = loaded;
174 generation = stamp;
175 LoadStatus::Loaded
176 }
177 Err(e) => {
178 protected = true;
179 LoadStatus::Rejected(e.into())
180 }
181 },
182 Err(e) => {
183 protected = true;
184 LoadStatus::Rejected(e)
185 }
186 };
187 Ok(Self {
188 owner: owner.into(),
189 name: name.into(),
190 value,
191 generation,
192 status,
193 protected,
194 backend,
195 })
196 }
197 pub fn value(&self) -> &T {
198 &self.value
199 }
200 pub fn generation(&self) -> u64 {
201 self.generation
202 }
203 pub fn status(&self) -> LoadStatus {
204 self.status
205 }
206 pub fn validate_loaded<R>(
209 &mut self,
210 validate: impl FnOnce(&T) -> Result<R, SaveError>,
211 ) -> Result<R, StorageError> {
212 match validate(&self.value) {
213 Ok(result) => Ok(result),
214 Err(e) => {
215 self.protected = true;
216 self.status = LoadStatus::Rejected(e.into());
217 Err(e.into())
218 }
219 }
220 }
221 pub fn commit(&mut self, next: T) -> Result<(), StorageError> {
224 if self.protected {
225 return Err(StorageError::Protected);
226 }
227 self.write(next, false)
228 }
229 pub fn reset(&mut self, next: T) -> Result<(), StorageError> {
231 self.write(next, true)
232 }
233 fn write(&mut self, next: T, reset: bool) -> Result<(), StorageError> {
234 let generation = if reset {
235 1
236 } else {
237 self.generation
238 .checked_add(1)
239 .ok_or(StorageError::GenerationExhausted)?
240 };
241 let bytes = next.encode(generation)?;
242 let result = self.backend.store(&self.owner, &self.name, &bytes);
243 if result.is_ok() || result == Err(StorageError::DurabilityUncertain) {
244 self.value = next;
245 self.generation = generation;
246 self.protected = false;
247 self.status = if self.backend.is_transient() {
248 LoadStatus::Transient
249 } else {
250 LoadStatus::Loaded
251 };
252 }
253 result
254 }
255}
256mod records;
257pub use records::{Record, RecordBook, Records, run_micros};
258#[cfg(test)]
259mod tests;
260#[cfg(not(target_arch = "wasm32"))]
263pub fn read_file(path: &std::path::Path, limit: usize) -> Result<Option<Vec<u8>>, StorageError> {
264 if limit > MAX_SAVE_BYTES {
265 return Err(StorageError::TooLarge);
266 }
267 native::read(path, limit)
268}
269#[cfg(not(target_arch = "wasm32"))]
270pub fn write_file(path: &std::path::Path, bytes: &[u8]) -> Result<(), StorageError> {
271 native::atomic_write(path, bytes, MAX_SAVE_BYTES)
272}