From 937d30195bdfaa0c0fb3a20beee22b89ad8e3a3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maxime=20=E2=80=9Cpep=E2=80=9D=20Buquet?= Date: Thu, 25 Aug 2022 10:39:22 +0200 Subject: [PATCH] roezio/config: implement ConfigValue::to_* MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Maxime “pep” Buquet --- src/config.rs | 28 ++++++++++++++++++++-------- src/error.rs | 2 ++ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/config.rs b/src/config.rs index df6da054..0c5bf7b1 100644 --- a/src/config.rs +++ b/src/config.rs @@ -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>(_val: S) -> Result { - Ok(ConfigValue::Bool(true)) + pub(crate) fn to_bool>(val: S) -> Result { + 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>(_val: S) -> Result { - Ok(ConfigValue::UInt(0u64)) + pub(crate) fn to_uint>(val: S) -> Result { + 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>(_val: S) -> Result { - Ok(ConfigValue::Int(0i64)) + pub(crate) fn to_int>(val: S) -> Result { + 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>(_val: S) -> Result { - Ok(ConfigValue::String(String::new())) + pub(crate) fn to_string>(val: S) -> Result { + Ok(ConfigValue::String(val.into())) } } diff --git a/src/error.rs b/src/error.rs index 4d9028a3..bc16f1bc 100644 --- a/src/error.rs +++ b/src/error.rs @@ -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), } } }