62 lines
1.4 KiB
Rust
62 lines
1.4 KiB
Rust
use std::{fmt::Display, str::FromStr};
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use super::parser::ParseError;
|
|
|
|
#[inline(always)]
|
|
pub fn from_hlwm_string(s: &str) -> Result<bool, ParseError> {
|
|
match s {
|
|
"on" | "true" => Ok(true),
|
|
"off" | "false" => Ok(false),
|
|
_ => Err(ParseError::PrimitiveError(format!(
|
|
"value [{s}] is not a {}",
|
|
std::any::type_name::<bool>()
|
|
))),
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
|
pub enum ToggleBool {
|
|
Bool(bool),
|
|
Toggle,
|
|
}
|
|
|
|
impl From<bool> for ToggleBool {
|
|
fn from(value: bool) -> Self {
|
|
Self::Bool(value)
|
|
}
|
|
}
|
|
|
|
impl FromStr for ToggleBool {
|
|
type Err = ParseError;
|
|
|
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
|
if let Ok(b) = from_hlwm_string(s) {
|
|
Ok(Self::Bool(b))
|
|
} else if s == "toggle" {
|
|
Ok(Self::Toggle)
|
|
} else {
|
|
Err(ParseError::PrimitiveError(format!(
|
|
"value [{s}] is not a {}",
|
|
std::any::type_name::<ToggleBool>()
|
|
)))
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Default for ToggleBool {
|
|
fn default() -> Self {
|
|
Self::Toggle
|
|
}
|
|
}
|
|
|
|
impl Display for ToggleBool {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
match self {
|
|
ToggleBool::Bool(b) => write!(f, "{b}"),
|
|
ToggleBool::Toggle => f.write_str("toggle"),
|
|
}
|
|
}
|
|
}
|