Skip to main content

sm64_binds/sm64/
save_state.rs

1//! [`SaveState`]: a game's state as bytes, to keep on disk or send elsewhere.
2//!
3//! The bytes are a header and then the mutable regions of linear memory (see
4//! `memory.rs`): the stack before the read-only data, then everything after
5//! it (called the heap here):
6//!
7//! ```text
8//!   offset  size  field
9//!        0     8  magic "SM64SAVE"
10//!        8     4  format version (little endian), currently 1
11//!       12    20  build id: SHA-1 of the WASM code (the module without data)
12//!       32     4  stack length (little endian)
13//!       36     8  heap length (little endian)
14//!       44     -  stack bytes, then heap bytes
15//! ```
16//!
17//! A state only means something to the build that made it (addresses and
18//! layouts differ between builds), so loading checks the build id.
19
20use anyhow::{Error, Result};
21
22use super::SM64Game;
23use super::wasm_module::BuildId;
24
25const MAGIC: &[u8; 8] = b"SM64SAVE";
26const VERSION: u32 = 1;
27const HEADER_LEN: usize = 44;
28
29/// A game's state, made by [`SM64Game::save_state`] and loaded by
30/// [`SM64Game::load_state`]. Turn it into bytes with [`SaveState::as_bytes`]
31/// to store or send it, and back with [`SaveState::from_bytes`].
32///
33/// For branching games within a process, [`SM64Game::copy_from`] and
34/// [`SM64Game::sync_from`] are faster: they copy memory directly.
35#[derive(Clone, PartialEq, Eq)]
36pub struct SaveState {
37    bytes: Vec<u8>,
38}
39
40impl std::fmt::Debug for SaveState {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("SaveState")
43            .field("build", &hex(self.build_id()))
44            .field("len", &self.bytes.len())
45            .finish()
46    }
47}
48
49impl SaveState {
50    fn new(build_id: &BuildId, stack: &[u8], heap: &[u8]) -> SaveState {
51        let mut bytes = Vec::with_capacity(HEADER_LEN + stack.len() + heap.len());
52        bytes.extend_from_slice(MAGIC);
53        bytes.extend_from_slice(&VERSION.to_le_bytes());
54        bytes.extend_from_slice(build_id);
55        bytes.extend_from_slice(&(stack.len() as u32).to_le_bytes());
56        bytes.extend_from_slice(&(heap.len() as u64).to_le_bytes());
57        bytes.extend_from_slice(stack);
58        bytes.extend_from_slice(heap);
59        SaveState { bytes }
60    }
61
62    /// The state as bytes, header included: what [`SaveState::from_bytes`]
63    /// takes back.
64    pub fn as_bytes(&self) -> &[u8] {
65        &self.bytes
66    }
67
68    /// Like [`SaveState::as_bytes`], without copying.
69    pub fn into_bytes(self) -> Vec<u8> {
70        self.bytes
71    }
72
73    /// A state from bytes written by [`SaveState::as_bytes`]. Fails if they
74    /// are not a save state of this format, or are truncated; whether it is
75    /// for the right build is checked by [`SM64Game::load_state`].
76    pub fn from_bytes(bytes: Vec<u8>) -> Result<SaveState> {
77        if bytes.len() < HEADER_LEN || &bytes[..8] != MAGIC {
78            return Err(Error::msg("not an sm64-binds save state"));
79        }
80        let version = u32::from_le_bytes(bytes[8..12].try_into().unwrap());
81        if version != VERSION {
82            return Err(Error::msg(format!(
83                "save state format version {version}, expected {VERSION}"
84            )));
85        }
86        let stack = u64::from(u32::from_le_bytes(bytes[32..36].try_into().unwrap()));
87        let heap = u64::from_le_bytes(bytes[36..44].try_into().unwrap());
88        let expected = (HEADER_LEN as u64 + stack).saturating_add(heap);
89        if bytes.len() as u64 != expected {
90            return Err(Error::msg(format!(
91                "save state is {} bytes, its header says {expected}",
92                bytes.len()
93            )));
94        }
95        Ok(SaveState { bytes })
96    }
97
98    fn build_id(&self) -> &[u8] {
99        &self.bytes[12..32]
100    }
101
102    fn stack_len(&self) -> usize {
103        u32::from_le_bytes(self.bytes[32..36].try_into().unwrap()) as usize
104    }
105
106    /// The stack bytes, then the heap bytes.
107    fn memory(&self) -> &[u8] {
108        &self.bytes[HEADER_LEN..]
109    }
110}
111
112impl SM64Game {
113    /// This game's state: its stack and heap, which are everything that
114    /// changes as it plays.
115    pub fn save_state(&self) -> SaveState {
116        self.with_memory(|memory| {
117            let (stack, heap) = self.mutable_parts(memory);
118            SaveState::new(&self.build_id, stack, heap)
119        })
120    }
121
122    /// Makes this game the one `state` was saved from. Fails, leaving the game
123    /// as it was, if `state` came from a different build of the game.
124    pub fn load_state(&mut self, state: &SaveState) -> Result<()> {
125        if state.build_id() != self.build_id {
126            return Err(Error::msg(format!(
127                "save state is from build {}, this game is build {}",
128                hex(state.build_id()),
129                hex(&self.build_id)
130            )));
131        }
132        if state.stack_len() != self.layout.stack_len() {
133            return Err(Error::msg(format!(
134                "save state has a {} byte stack, this game's is {}",
135                state.stack_len(),
136                self.layout.stack_len()
137            )));
138        }
139        self.write_mutable_bytes(state.memory())
140    }
141}
142
143fn hex(bytes: &[u8]) -> String {
144    bytes.iter().map(|b| format!("{b:02x}")).collect()
145}