roezio/config: implement ConfigValue::to_*

Signed-off-by: Maxime “pep” Buquet <pep@bouah.net>
This commit is contained in:
Maxime “pep” Buquet 2022-08-25 10:39:22 +02:00
parent cc791af917
commit 937d30195b
Signed by: pep
GPG key ID: DEDA74AEECA9D0F2
2 changed files with 22 additions and 8 deletions

View file

@ -19,6 +19,7 @@ use std::cell::LazyCell;
use std::collections::HashMap;
use std::fmt;
use std::path::PathBuf;
use std::str::FromStr;
use configparser::ini::Ini;
use jid::Jid;
@ -32,20 +33,31 @@ pub(crate) enum ConfigValue {
}
impl ConfigValue {
pub(crate) fn to_bool<S: Into<String>>(_val: S) -> Result<ConfigValue, Error> {
Ok(ConfigValue::Bool(true))
pub(crate) fn to_bool<S: Into<String>>(val: S) -> Result<ConfigValue, Error> {
let val: String = val.into();
Ok(match val.trim().to_lowercase().as_str() {
"t" | "true" | "y" | "yes" | "on" | "1" => ConfigValue::Bool(true),
"f" | "false" | "n" | "no" | "off" | "0" => ConfigValue::Bool(false),
_ => return Err(Error::InvalidValueType(val)),
})
}
pub(crate) fn to_uint<S: Into<String>>(_val: S) -> Result<ConfigValue, Error> {
Ok(ConfigValue::UInt(0u64))
pub(crate) fn to_uint<S: Into<String>>(val: S) -> Result<ConfigValue, Error> {
let val: String = val.into();
u64::from_str(val.as_str())
.map(|v| ConfigValue::UInt(v))
.map_err(|_| Error::InvalidValueType(val))
}
pub(crate) fn to_int<S: Into<String>>(_val: S) -> Result<ConfigValue, Error> {
Ok(ConfigValue::Int(0i64))
pub(crate) fn to_int<S: Into<String>>(val: S) -> Result<ConfigValue, Error> {
let val: String = val.into();
i64::from_str(val.as_str())
.map(|v| ConfigValue::Int(v))
.map_err(|_| Error::InvalidValueType(val))
}
pub(crate) fn to_string<S: Into<String>>(_val: S) -> Result<ConfigValue, Error> {
Ok(ConfigValue::String(String::new()))
pub(crate) fn to_string<S: Into<String>>(val: S) -> Result<ConfigValue, Error> {
Ok(ConfigValue::String(val.into()))
}
}

View file

@ -24,6 +24,7 @@ pub(crate) enum Error {
IOError(io::Error),
UnableToCreateConfigDir,
InvalidConfigValueType(ConfigValue),
InvalidValueType(String),
}
impl fmt::Display for Error {
@ -32,6 +33,7 @@ impl fmt::Display for Error {
Error::IOError(e) => write!(f, "io error: {}", e),
Error::UnableToCreateConfigDir => write!(f, "Unable to create config dir"),
Error::InvalidConfigValueType(err) => write!(f, "Invalid ConfigValue type: {}", err),
Error::InvalidValueType(err) => write!(f, "Invalid value type: {}", err),
}
}
}