= 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 tracing: Value = map.remove("tracing").ok_or_else(|| Error::custom("missing tracing"))?;
let tracing = tracing.as_bool().ok_or_else(|| Error::custom("invalid tracing value"))?;
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 mode: Value = map.remove("mode").unwrap_or_else(|| Value::String("active".to_owned()));
let mode = match mode.as_str().ok_or_else(|| Error::custom("invalid mode value"))? {
"offline" => Mode::Off,
"dark" => {
let timeout = map.remove("mode.timeout").and_then(|v| v.as_u64()).ok_or_else(|| Error::custom("invalid/missing mode.timeout value"))?;
Mode::Dark(Duration::from_secs(timeout))
},
"passive" => {
let timeout = map.remove("mode.timeout").and_then(|v| v.as_u64()).ok_or_else(|| Error::custom("invalid/missing mode.timeout value"))?;
let alarm = map.remove("mode.alarm").and_then(|v| v.as_u64()).ok_or_else(|| Error::custom("invalid/missing mode.alarm value"))?;
Mode::Passive(Duration::from_secs(timeout), Duration::from_secs(alarm))
},
"active" => Mode::Active,
_ => { return Err(Error::custom("invalid mode value")); },
};
let user_defaults = UserDefaults {
is_first_launch: false,
pruning: pruning,
tracing: tracing,
fat_db: fat_db,
mode: mode,
};
Ok(user_defaults)
}
}
impl Default for UserDefaults {
fn default() -> Self {
UserDefaults {
is_first_launch: true,
pruning: Algorithm::default(),
tracing: false,
fat_db: false,
mode: Mode::Active,
}
}
}
impl UserDefaults {
pub fn load(path: P) -> Result where P: AsRef {
match File::open(path) {
Ok(file) => match from_reader(file) {
Ok(defaults) => Ok(defaults),
Err(e) => {
warn!("Error loading user defaults file: {:?}", e);
Ok(UserDefaults::default())
},
},
_ => Ok(UserDefaults::default()),
}
}
pub fn save(&self, path: P) -> Result<(), String> where P: AsRef {
let mut file: File = File::create(path).map_err(|_| "Cannot create user defaults file".to_owned())?;
file.write_all(to_string(&self).unwrap().as_bytes()).map_err(|_| "Failed to save user defaults".to_owned())
}
}