MudEngine Part 7: Save & Load
Add the persistence functions
The types are still useless without the functions that move data between the two files and the runtime GameState. Add four functions to src/game/persistence.rs:
load_world(path)— readsGame.tomland returns its rooms. BecauseRoomInfois the deserialization target, this is a one-liner: parseTomlWorld, returnrooms. It panics on a missing or malformed file — the world must always existload_players(path)— readsPlayers.tomlinto its players. A missing file is fine — it is gitignored and may not exist yet, so an empty player list is returned. A corrupt file still panics.PlayerInfodeserializes straight off the file, so the only work is turning each player into a(id, player)hash-map entrysave_players(&state)— serializes the current players straight fromGameStateintoPlayers.toml. Called after every mutation. Notice it never writesGame.tomlcan_move(&state, from_room, direction)— searches a room's exits by ID to validate a movement
The block below is the complete file — it contains the type definitions from the previous step plus the new functions. If you already built the types into persistence.rs, you can keep them and just append the // ── Persistence functions (server only) ── section that follows.
All four are #[cfg(feature = "server")] — the client never runs them.
This is the straightforward save-on-every-mutation version. In the final step we'll replace it with a sync-style design: the game stays in memory and an autosave task flushes it once a minute — so the functions we add now get refined there.
Because the leaf types are already the runtime types, none of these functions contains a field-by-field conversion — the only "mapping" left is packaging a Vec into its TOML wrapper and back.
use std::collections::HashMap; use serde::{Deserialize, Serialize}; // ── Shared models: one type per concept, reused for TOML, runtime, and wire ── /// A single exit — matches the `{ direction, destination }` entries in Game.toml, /// lives on every runtime room, and is sent to clients for the world grid. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct Exit { pub direction: String, pub destination: usize, } /// Room info sent to clients — and the same type Game.toml deserializes into. /// Carries id, name, description, and the exits the WorldGrid uses to highlight /// which cells are clickable. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct RoomInfo { pub id: usize, pub name: String, pub description: String, pub exits: Vec<Exit>, } /// A connected player — the type Players.toml deserializes into, the value in /// GameState.players, and the wire type broadcast to clients. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct PlayerInfo { pub id: String, pub name: String, pub room: usize, } // ── TOML wrappers: thin containers for the file shape only ── #[derive(Serialize, Deserialize)] struct TomlWorld { rooms: Vec<RoomInfo>, } #[derive(Serialize, Deserialize)] struct TomlPlayers { #[serde(default)] players: Vec<PlayerInfo>, } // ── Runtime game state (server only) ── #[cfg(feature = "server")] pub struct GameState { pub rooms: Vec<RoomInfo>, pub players: HashMap<String, PlayerInfo>, } // ── Persistence functions (server only) ── #[cfg(feature = "server")] pub fn load_world(path: &str) -> Vec<RoomInfo> { let content = std::fs::read_to_string(path).unwrap_or_else(|e| panic!("Failed to read {}: {}", path, e)); let toml_world: TomlWorld = toml::from_str(&content).unwrap_or_else(|e| panic!("Failed to parse {}: {}", path, e)); toml_world.rooms } #[cfg(feature = "server")] pub fn load_players(path: &str) -> HashMap<String, PlayerInfo> { let Ok(content) = std::fs::read_to_string(path) else { return HashMap::new(); }; let toml_players: TomlPlayers = toml::from_str(&content).unwrap_or_else(|e| panic!("Failed to parse {}: {}", path, e)); toml_players .players .into_iter() .map(|p| (p.id.clone(), p)) .collect() } #[cfg(feature = "server")] pub fn save_players(state: &GameState) { let toml_players = TomlPlayers { players: state.players.values().cloned().collect(), }; let toml_str = toml::to_string_pretty(&toml_players).unwrap(); std::fs::write("Players.toml", toml_str).unwrap(); } #[cfg(feature = "server")] pub fn can_move(state: &GameState, from_room: usize, direction: &str) -> Option<usize> { state .rooms .iter() .find(|r| r.id == from_room) .and_then(|r| { r.exits .iter() .find(|e| e.direction == direction) .map(|e| e.destination) }) }