-
Notifications
You must be signed in to change notification settings - Fork 11
/
user_defaults.rs
141 lines (127 loc) · 4.62 KB
/
user_defaults.rs
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/*******************************************************************************
* Copyright (c) 2018-2019 Aion foundation.
*
* This file is part of the aion network project.
*
* The aion network project is free software: you can redistribute it
* and/or modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or any later version.
*
* The aion network project is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the aion network project source files.
* If not, see <https://www.gnu.org/licenses/>.
*
******************************************************************************/
use std::fmt;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::collections::BTreeMap;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
use serde::de::{Error, Visitor, MapAccess};
use serde::de::value::MapAccessDeserializer;
use serde_json::Value;
use serde_json::de::from_reader;
use serde_json::ser::to_string;
use journaldb::Algorithm;
/// Default value of some config params
pub struct UserDefaults {
pub is_first_launch: bool,
pub pruning: Algorithm,
pub fat_db: bool,
}
impl Serialize for UserDefaults {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer {
let mut map: BTreeMap<String, Value> = BTreeMap::new();
map.insert("is_first_launch".into(), Value::Bool(self.is_first_launch));
map.insert(
"pruning".into(),
Value::String(self.pruning.as_str().into()),
);
map.insert("fat_db".into(), Value::Bool(self.fat_db));
map.serialize(serializer)
}
}
struct UserDefaultsVisitor;
impl<'a> Deserialize<'a> for UserDefaults {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'a> {
deserializer.deserialize_any(UserDefaultsVisitor)
}
}
impl<'a> Visitor<'a> for UserDefaultsVisitor {
type Value = UserDefaults;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a valid UserDefaults object")
}
fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error>
where V: MapAccess<'a> {
let mut map: BTreeMap<String, Value> =
Deserialize::deserialize(MapAccessDeserializer::new(visitor))?;
let pruning: Value = map
.remove("pruning")
.ok_or_else(|| Error::custom("missing pruning"))?;
let pruning = pruning
.as_str()
.ok_or_else(|| Error::custom("invalid pruning value"))?;
let pruning = pruning
.parse()
.map_err(|_| Error::custom("invalid pruning method"))?;
let fat_db: Value = map.remove("fat_db").unwrap_or_else(|| Value::Bool(false));
let fat_db = fat_db
.as_bool()
.ok_or_else(|| Error::custom("invalid fat_db value"))?;
let user_defaults = UserDefaults {
is_first_launch: false,
pruning,
fat_db,
};
Ok(user_defaults)
}
}
impl Default for UserDefaults {
fn default() -> Self {
UserDefaults {
is_first_launch: true,
pruning: Algorithm::default(),
fat_db: false,
}
}
}
impl UserDefaults {
/// load default config value from the given path
pub fn load<P>(path: P) -> Result<Self, String>
where P: AsRef<Path> {
match File::open(path) {
Ok(file) => {
match from_reader(file) {
Ok(defaults) => Ok(defaults),
Err(e) => {
warn!(target:"run","Error loading user defaults file: {:?}", e);
Ok(UserDefaults::default())
}
}
}
_ => Ok(UserDefaults::default()),
}
}
/// save default config value to the given path
pub fn save<P>(&self, path: P) -> Result<(), String>
where P: AsRef<Path> {
let mut file: File =
File::create(path).map_err(|_| "Cannot create user defaults file".to_owned())?;
file.write_all(
to_string(&self)
.map_err(|_| format!("User default can't parse into string"))?
.as_bytes(),
)
.map_err(|_| "Failed to save user defaults".to_owned())
}
}