Skip to main content

rayengine_core/
save.rs

1//! Versioned, checksummed containers for game-defined payloads.
2//!
3//! The engine validates its container; the game owns serialization, schema
4//! versions, migration, and recovery policy. Filesystem writes are explicit and
5//! optional. See [`save`] for replacement and durability behavior.
6
7use std::{collections::TryReserveError, fmt, io};
8
9mod file;
10pub use file::{load, load_with, save, save_with};
11
12/// Current engine container format, independent of a game's schema version.
13pub const FORMAT_VERSION: u32 = 1;
14/// Fixed header size: magic (8), format/schema (4 each), length (8), CRC32 (4).
15pub const HEADER_LEN: usize = 28;
16const MAGIC: &[u8; 8] = b"RAYSAVE\0";
17
18/// Bounds container payload allocation and admission; game codecs can allocate
19/// additional memory. The default limit is 64 MiB.
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub struct SaveLimits {
22    /// Maximum admitted payload bytes, excluding the fixed header.
23    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/// Explicit storage policy. Neither mode creates parent directories.
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub enum Durability {
36    /// Same-directory replacement without fsync. No power-loss durability promise.
37    Atomic,
38    /// Sync the complete temporary file, replace, then sync its parent directory.
39    /// Supported on Linux; other targets return an error before creating a file.
40    #[default]
41    Durable,
42}
43
44/// File-write limits and persistence policy. Defaults to Linux durable writes.
45#[derive(Clone, Copy, Debug, Default)]
46pub struct SaveOptions {
47    /// Maximum serialized payload size.
48    pub limits: SaveLimits,
49    /// Whether to flush storage as part of replacement.
50    pub durability: Durability,
51}
52
53/// Filesystem operation that failed.
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub enum SaveStage {
56    /// Opening, inspecting, or reading a container.
57    Read,
58    /// Opening the existing parent directory before a durable write.
59    OpenDirectory,
60    /// Creating a unique sibling temporary file.
61    CreateTemporary,
62    /// Writing the header or payload to the temporary file.
63    WriteTemporary,
64    /// Flushing the temporary file before replacement.
65    SyncTemporary,
66    /// Replacing the destination name.
67    Rename,
68    /// Flushing the directory after successful replacement.
69    SyncDirectory,
70}
71
72/// File replacement disposition when handling a save error.
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub enum CommitState {
75    /// Replacement was not attempted; the destination was not changed.
76    NotCommitted,
77    /// Replacement returned an error. Reload to resolve ambiguous filesystem outcomes.
78    Unknown,
79    /// Replacement succeeded, but directory durability confirmation failed.
80    Committed,
81}
82
83/// Container validation or filesystem failure. No recovery is performed implicitly.
84#[derive(Debug)]
85pub enum SaveError {
86    /// A header ended before all fixed fields were available.
87    TruncatedHeader {
88        /// Available header bytes.
89        bytes: usize,
90    },
91    /// The file is not a rayengine save container.
92    BadMagic,
93    /// The engine cannot decode this container format.
94    UnsupportedFormat {
95        /// Recorded container version.
96        found: u32,
97    },
98    /// A strict game schema check failed; migration is game-owned.
99    UnsupportedSchema {
100        /// Required game schema.
101        expected: u32,
102        /// Recorded game schema.
103        found: u32,
104    },
105    /// Declared payload size exceeds the configured bound.
106    TooLarge {
107        /// Declared payload bytes.
108        bytes: u64,
109        /// Configured byte limit.
110        limit: usize,
111    },
112    /// Header/payload size cannot be represented on this platform.
113    SizeOverflow,
114    /// Truncation or trailing data disagrees with the declared payload size.
115    LengthMismatch {
116        /// Declared payload bytes.
117        declared: u64,
118        /// Available payload bytes.
119        actual: u64,
120    },
121    /// CRC32 of the header prefix and payload did not match.
122    ChecksumMismatch {
123        /// Stored checksum.
124        expected: u32,
125        /// Calculated checksum.
126        actual: u32,
127    },
128    /// Destination must name a file, with an existing stable parent directory.
129    InvalidPath,
130    /// Loading requires a regular file.
131    NotRegularFile,
132    /// Linux durable semantics are unavailable on this target.
133    UnsupportedDurability,
134    /// Bounded container allocation failed.
135    Allocation(TryReserveError),
136    /// An operating-system operation failed.
137    Io {
138        /// Operation that failed.
139        stage: SaveStage,
140        /// Original operating-system error.
141        source: io::Error,
142    },
143}
144
145impl SaveError {
146    /// Disposition for recovery after a save operation. Rename errors are
147    /// conservatively ambiguous (notably on network filesystems). A directory
148    /// sync error means the new container is already installed; never roll it
149    /// back implicitly. Load/validation errors do not modify files.
150    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/// Keeps game serialization/migration failures separate from engine failures.
208#[derive(Debug)]
209pub enum CodecError<E> {
210    /// Container or filesystem failure, including replacement disposition.
211    Container(SaveError),
212    /// Game-defined encoder, decoder, or migration failure.
213    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/// Validated borrowed payload. The engine does not interpret the game schema.
233#[derive(Clone, Copy, Debug, PartialEq, Eq)]
234pub struct SaveRef<'a> {
235    /// Game-owned payload schema version.
236    pub schema_version: u32,
237    /// Validated opaque bytes, borrowing the container.
238    pub payload: &'a [u8],
239}
240impl SaveRef<'_> {
241    /// Checks one supported schema. Games with migrations can dispatch on the
242    /// recorded version instead, after container validation.
243    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/// Owned disk payload, allocated once after header/length admission.
256#[derive(Clone, Debug, PartialEq, Eq)]
257pub struct SaveData {
258    /// Game-owned payload schema version.
259    pub schema_version: u32,
260    /// Validated opaque payload bytes.
261    pub payload: Vec<u8>,
262}
263impl SaveData {
264    /// Borrows metadata/payload without copying.
265    pub fn as_ref(&self) -> SaveRef<'_> {
266        SaveRef {
267            schema_version: self.schema_version,
268            payload: &self.payload,
269        }
270    }
271    /// Strict schema check; migration-capable games can inspect the version.
272    pub fn require_schema(&self, expected: u32) -> Result<(), SaveError> {
273        self.as_ref().require_schema(expected)
274    }
275}
276
277/// Encodes a container into a new vector. Use [`encode_into`] to reuse storage.
278pub 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
288/// Encodes using reusable output storage. Admission/allocation failures preserve
289/// its existing bytes. CRC covers the fixed prefix (including game schema and
290/// payload length) followed by the payload; integers are little-endian.
291pub 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
310/// Validates without allocation and borrows the opaque payload. Unknown engine
311/// formats, truncation, trailing data, oversized payloads and bad checksums fail
312/// before any game decoder runs.
313pub 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;