1use std::{
2 fs,
3 path::{Path, PathBuf},
4};
5
6use crate::fs_extra;
7
8use self::room::Room;
9
10mod room;
11
12pub struct Store {
13 name: String,
14 root_dir: PathBuf,
15 store_dir: PathBuf,
16}
17
18impl Store {
19 pub fn init<S: AsRef<str>>(path: PathBuf, name: S) -> Store {
23 let name_ref = name.as_ref();
24 let hexed_name = hex::encode(name_ref);
25 let store_dir = Path::new(path.as_path()).join(hexed_name);
26 fs_extra::ensure_dir(store_dir.clone());
27 Store {
28 name: name_ref.to_string(),
29 store_dir,
30 root_dir: path,
31 }
32 }
33
34 pub fn get_name(&self) -> String {
38 self.name.clone()
39 }
40
41 pub fn set_name<S: AsRef<str>>(&mut self, new_name: S) -> bool {
45 self.name = new_name.as_ref().to_string();
46 let hexed_name = hex::encode(self.name.clone());
47 let new_db_dir = Path::new(self.root_dir.as_path()).join(hexed_name);
48 let success = fs::rename(self.store_dir.clone(), new_db_dir.clone());
49 self.store_dir = new_db_dir;
50 success.is_ok()
51 }
52
53 pub fn init_room<S: AsRef<str>>(&self, name: S) -> Room {
57 Room::init(self.store_dir.clone(), name)
58 }
59
60 pub fn drop_room<S: AsRef<str>>(&self, name: S) -> bool {
64 let name_ref = name.as_ref();
65 let hexed_name = hex::encode(name_ref);
66 let room_dir = Path::new(self.store_dir.as_path()).join(hexed_name);
67 fs::remove_dir_all(room_dir.clone()).is_ok() && fs::remove_dir(room_dir).is_ok()
68 }
69}