1use std::{collections::TryReserveError, fmt, io};
8
9mod file;
10pub use file::{load, load_with, save, save_with};
11
12pub const FORMAT_VERSION: u32 = 1;
14pub const HEADER_LEN: usize = 28;
16const MAGIC: &[u8; 8] = b"RAYSAVE\0";
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub struct SaveLimits {
22 pub max_payload_bytes: usize,
24}
25impl Default for SaveLimits {
26 fn default() -> Self {
27 Self {
28 max_payload_bytes: 64 * 1024 * 1024,
29 }
30 }
31}
32
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub enum Durability {
36 Atomic,
38 #[default]
41 Durable,
42}
43
44#[derive(Clone, Copy, Debug, Default)]
46pub struct SaveOptions {
47 pub limits: SaveLimits,
49 pub durability: Durability,
51}
52
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub enum SaveStage {
56 Read,
58 OpenDirectory,
60 CreateTemporary,
62 WriteTemporary,
64 SyncTemporary,
66 Rename,
68 SyncDirectory,
70}
71
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub enum CommitState {
75 NotCommitted,
77 Unknown,
79 Committed,
81}
82
83#[derive(Debug)]
85pub enum SaveError {
86 TruncatedHeader {
88 bytes: usize,
90 },
91 BadMagic,
93 UnsupportedFormat {
95 found: u32,
97 },
98 UnsupportedSchema {
100 expected: u32,
102 found: u32,
104 },
105 TooLarge {
107 bytes: u64,
109 limit: usize,
111 },
112 SizeOverflow,
114 LengthMismatch {
116 declared: u64,
118 actual: u64,
120 },
121 ChecksumMismatch {
123 expected: u32,
125 actual: u32,
127 },
128 InvalidPath,
130 NotRegularFile,
132 UnsupportedDurability,
134 Allocation(TryReserveError),
136 Io {
138 stage: SaveStage,
140 source: io::Error,
142 },
143}
144
145impl SaveError {
146 pub fn commit_state(&self) -> CommitState {
151 match self {
152 Self::Io {
153 stage: SaveStage::Rename,
154 ..
155 } => CommitState::Unknown,
156 Self::Io {
157 stage: SaveStage::SyncDirectory,
158 ..
159 } => CommitState::Committed,
160 _ => CommitState::NotCommitted,
161 }
162 }
163}
164
165impl fmt::Display for SaveError {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 match self {
168 Self::TruncatedHeader { bytes } => {
169 write!(f, "save header has {bytes} bytes; needs {HEADER_LEN}")
170 }
171 Self::BadMagic => f.write_str("invalid save magic"),
172 Self::UnsupportedFormat { found } => write!(f, "unsupported save format {found}"),
173 Self::UnsupportedSchema { expected, found } => {
174 write!(f, "expected game schema {expected}, found {found}")
175 }
176 Self::TooLarge { bytes, limit } => {
177 write!(f, "save payload {bytes} exceeds limit {limit}")
178 }
179 Self::SizeOverflow => f.write_str("save size exceeds platform limits"),
180 Self::LengthMismatch { declared, actual } => {
181 write!(f, "save declares {declared} payload bytes, found {actual}")
182 }
183 Self::ChecksumMismatch { expected, actual } => write!(
184 f,
185 "save checksum mismatch: expected {expected:08x}, found {actual:08x}"
186 ),
187 Self::InvalidPath => f.write_str("save path must name a file"),
188 Self::NotRegularFile => f.write_str("save source must be a regular file"),
189 Self::UnsupportedDurability => f.write_str(
190 "durable saves require Linux; choose Atomic explicitly on other targets",
191 ),
192 Self::Allocation(source) => write!(f, "save allocation: {source}"),
193 Self::Io { stage, source } => write!(f, "save {stage:?}: {source}"),
194 }
195 }
196}
197impl std::error::Error for SaveError {
198 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
199 match self {
200 Self::Allocation(source) => Some(source),
201 Self::Io { source, .. } => Some(source),
202 _ => None,
203 }
204 }
205}
206
207#[derive(Debug)]
209pub enum CodecError<E> {
210 Container(SaveError),
212 Payload(E),
214}
215impl<E: fmt::Display> fmt::Display for CodecError<E> {
216 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217 match self {
218 Self::Container(e) => e.fmt(f),
219 Self::Payload(e) => write!(f, "save payload codec: {e}"),
220 }
221 }
222}
223impl<E: std::error::Error + 'static> std::error::Error for CodecError<E> {
224 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
225 match self {
226 Self::Container(e) => Some(e),
227 Self::Payload(e) => Some(e),
228 }
229 }
230}
231
232#[derive(Clone, Copy, Debug, PartialEq, Eq)]
234pub struct SaveRef<'a> {
235 pub schema_version: u32,
237 pub payload: &'a [u8],
239}
240impl SaveRef<'_> {
241 pub fn require_schema(&self, expected: u32) -> Result<(), SaveError> {
244 if self.schema_version == expected {
245 Ok(())
246 } else {
247 Err(SaveError::UnsupportedSchema {
248 expected,
249 found: self.schema_version,
250 })
251 }
252 }
253}
254
255#[derive(Clone, Debug, PartialEq, Eq)]
257pub struct SaveData {
258 pub schema_version: u32,
260 pub payload: Vec<u8>,
262}
263impl SaveData {
264 pub fn as_ref(&self) -> SaveRef<'_> {
266 SaveRef {
267 schema_version: self.schema_version,
268 payload: &self.payload,
269 }
270 }
271 pub fn require_schema(&self, expected: u32) -> Result<(), SaveError> {
273 self.as_ref().require_schema(expected)
274 }
275}
276
277pub fn encode(
279 schema_version: u32,
280 payload: &[u8],
281 limits: SaveLimits,
282) -> Result<Vec<u8>, SaveError> {
283 let mut output = Vec::new();
284 encode_into(&mut output, schema_version, payload, limits)?;
285 Ok(output)
286}
287
288pub fn encode_into(
292 output: &mut Vec<u8>,
293 schema_version: u32,
294 payload: &[u8],
295 limits: SaveLimits,
296) -> Result<(), SaveError> {
297 let header = make_header(schema_version, payload, limits)?;
298 let total = HEADER_LEN
299 .checked_add(payload.len())
300 .ok_or(SaveError::SizeOverflow)?;
301 output
302 .try_reserve(total.saturating_sub(output.len()))
303 .map_err(SaveError::Allocation)?;
304 output.clear();
305 output.extend_from_slice(&header);
306 output.extend_from_slice(payload);
307 Ok(())
308}
309
310pub fn decode(bytes: &[u8], limits: SaveLimits) -> Result<SaveRef<'_>, SaveError> {
314 let header = bytes
315 .get(..HEADER_LEN)
316 .ok_or(SaveError::TruncatedHeader { bytes: bytes.len() })?;
317 let (schema_version, size) = parse_header(header, limits)?;
318 let payload = &bytes[HEADER_LEN..];
319 if payload.len() != size {
320 return Err(SaveError::LengthMismatch {
321 declared: size as u64,
322 actual: payload.len() as u64,
323 });
324 }
325 verify_checksum(header, payload)?;
326 Ok(SaveRef {
327 schema_version,
328 payload,
329 })
330}
331
332fn make_header(
333 schema: u32,
334 payload: &[u8],
335 limits: SaveLimits,
336) -> Result<[u8; HEADER_LEN], SaveError> {
337 let size = u64::try_from(payload.len()).map_err(|_| SaveError::SizeOverflow)?;
338 if payload.len() > limits.max_payload_bytes {
339 return Err(SaveError::TooLarge {
340 bytes: size,
341 limit: limits.max_payload_bytes,
342 });
343 }
344 HEADER_LEN
345 .checked_add(payload.len())
346 .ok_or(SaveError::SizeOverflow)?;
347 let mut header = [0; HEADER_LEN];
348 header[..8].copy_from_slice(MAGIC);
349 header[8..12].copy_from_slice(&FORMAT_VERSION.to_le_bytes());
350 header[12..16].copy_from_slice(&schema.to_le_bytes());
351 header[16..24].copy_from_slice(&size.to_le_bytes());
352 let crc = checksum(&header[..24], payload);
353 header[24..].copy_from_slice(&crc.to_le_bytes());
354 Ok(header)
355}
356
357fn parse_header(header: &[u8], limits: SaveLimits) -> Result<(u32, usize), SaveError> {
358 if &header[..8] != MAGIC {
359 return Err(SaveError::BadMagic);
360 }
361 let format = u32::from_le_bytes(header[8..12].try_into().expect("fixed header"));
362 if format != FORMAT_VERSION {
363 return Err(SaveError::UnsupportedFormat { found: format });
364 }
365 let schema = u32::from_le_bytes(header[12..16].try_into().expect("fixed header"));
366 let length = u64::from_le_bytes(header[16..24].try_into().expect("fixed header"));
367 let size = usize::try_from(length).map_err(|_| SaveError::TooLarge {
368 bytes: length,
369 limit: limits.max_payload_bytes,
370 })?;
371 if size > limits.max_payload_bytes {
372 return Err(SaveError::TooLarge {
373 bytes: length,
374 limit: limits.max_payload_bytes,
375 });
376 }
377 HEADER_LEN
378 .checked_add(size)
379 .ok_or(SaveError::SizeOverflow)?;
380 Ok((schema, size))
381}
382
383fn checksum(prefix: &[u8], payload: &[u8]) -> u32 {
384 let mut hasher = crc32fast::Hasher::new();
385 hasher.update(prefix);
386 hasher.update(payload);
387 hasher.finalize()
388}
389fn verify_checksum(header: &[u8], payload: &[u8]) -> Result<(), SaveError> {
390 let expected = u32::from_le_bytes(header[24..28].try_into().expect("fixed header"));
391 let actual = checksum(&header[..24], payload);
392 if actual == expected {
393 Ok(())
394 } else {
395 Err(SaveError::ChecksumMismatch { expected, actual })
396 }
397}
398
399#[cfg(test)]
400mod tests;