summaryrefslogtreecommitdiff
path: root/src/persistence.rs
blob: 1808652fd4276bb480de6ff22a661d22e29d282d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

use std::path::PathBuf;
use std::fs;
use serde_json;
use serde_json::Value;
use crate::{
	PlayerId,
	savestate::SaveState,
	playerstate::PlayerState,
	util::Result,
	aerr
};

pub trait PersistentStorage {
	
	fn load_room(&self, name: String) -> Result<SaveState>;
	
	fn load_player(&self, id: PlayerId) -> Result<PlayerState>;
	
	fn save_room(&self, name: String, state: SaveState) -> Result<()>;
	
	fn save_player(&self, id: PlayerId, sate: PlayerState) -> Result<()>;
	
}


pub struct FileStorage {
	directory: PathBuf
}

impl FileStorage {
	pub fn new(path: &str) -> Self {
		Self {
			directory: PathBuf::from(path)
		}
	}
}

impl PersistentStorage for FileStorage {
	
	fn load_room(&self, name: String) -> Result<SaveState> {
		let mut path = self.directory.clone();
		path.push("rooms");
		let fname = name + ".save.json";
		path.push(fname);
		let text = fs::read_to_string(path)?;
		let json: Value = serde_json::from_str(&text)?;
		SaveState::from_json(&json).ok_or(aerr!("not a valid save state"))
	}
	
	fn load_player(&self, id: PlayerId) -> Result<PlayerState> {
		let mut path = self.directory.clone();
		path.push("players");
		let fname = id.name + ".save.json";
		path.push(fname);
		let text = fs::read_to_string(path)?;
		let json: Value = serde_json::from_str(&text)?;
		PlayerState::from_json(&json).ok_or(aerr!("not a valid save state"))
	}
	
	fn save_room(&self, name: String, state: SaveState) -> Result<()> {
		let mut path = self.directory.clone();
		path.push("rooms");
		fs::create_dir_all(&path)?;
		let fname = name + ".save.json";
		path.push(fname);
		let text = state.to_json().to_string();
		// todo: write to a temp file first
		fs::write(path, text)?;
		Ok(())
	}
	
	fn save_player(&self, id: PlayerId, state: PlayerState) -> Result<()> {
		let mut path = self.directory.clone();
		path.push("players");
		fs::create_dir_all(&path)?;
		let fname = id.name + ".save.json";
		path.push(fname);
		let text = state.to_json().to_string();
		// todo: write to a temp file first
		fs::write(path, text)?;
		Ok(())
	}
}