use std::path::PathBuf;
pub trait FromRaw: Sized {
fn from_raw(s: &str) -> Option<Self>;
}
impl FromRaw for bool {
fn from_raw(s: &str) -> Option<bool> {
match s.trim() {
"1" | "true" | "True" | "on" | "yes" => Some(true),
"0" | "false" | "False" | "off" | "no" | "" => Some(false),
_ => None,
}
}
}
impl FromRaw for String {
fn from_raw(s: &str) -> Option<String> {
Some(s.to_string())
}
}
impl FromRaw for PathBuf {
fn from_raw(s: &str) -> Option<PathBuf> {
if s.trim().is_empty() {
None
} else {
Some(PathBuf::from(s))
}
}
}
macro_rules! impl_from_raw_number {
($($t:ty),*) => { $(
impl FromRaw for $t {
fn from_raw(s: &str) -> Option<$t> { s.trim().parse::<$t>().ok() }
}
)* };
}
impl_from_raw_number!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64);
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Tristate {
#[default]
Auto,
On,
Off,
}
impl Tristate {
pub const TOKENS: &'static [&'static str] = &["auto", "on", "off"];
}
impl FromRaw for Tristate {
fn from_raw(s: &str) -> Option<Tristate> {
Some(match s.trim() {
"auto" | "" => Tristate::Auto,
"on" | "1" | "true" | "yes" => Tristate::On,
"off" | "0" | "false" | "no" => Tristate::Off,
_ => return None,
})
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum LogLevel {
Trace,
Debug,
Info,
Warn,
Error,
None,
}
impl LogLevel {
pub const TOKENS: &'static [&'static str] =
&["trace", "debug", "info", "warn", "error", "none"];
}
impl FromRaw for LogLevel {
fn from_raw(s: &str) -> Option<LogLevel> {
Some(match s.trim() {
"trace" => LogLevel::Trace,
"debug" => LogLevel::Debug,
"info" => LogLevel::Info,
"warn" | "warning" => LogLevel::Warn,
"error" | "err" => LogLevel::Error,
"none" | "off" => LogLevel::None,
_ => return None,
})
}
}