use crate::error::Result;
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Domain {
Boolean,
PositiveInteger,
NonNegativeInteger,
IntegerInRange(u64, u64),
Enumeration(&'static [&'static str]),
Text,
}
impl Domain {
#[must_use]
pub fn described(self) -> String {
match self {
Self::Boolean => "one of: true, false".to_owned(),
Self::PositiveInteger => "a whole number above zero".to_owned(),
Self::NonNegativeInteger => "a whole number from zero upwards".to_owned(),
Self::IntegerInRange(low, high) => format!("a whole number from {low} to {high}"),
Self::Enumeration(values) => format!("one of: {}", values.join(", ")),
Self::Text => "text that is not empty".to_owned(),
}
}
#[must_use]
pub const fn token(self) -> &'static str {
match self {
Self::Boolean => "boolean",
Self::PositiveInteger => "positive-integer",
Self::NonNegativeInteger => "non-negative-integer",
Self::IntegerInRange(..) => "integer-in-range",
Self::Enumeration(_) => "enumeration",
Self::Text => "text",
}
}
#[must_use]
pub fn accepted(self) -> String {
match self {
Self::Enumeration(values) => values.join(", "),
Self::Boolean => "true, false".to_owned(),
Self::IntegerInRange(low, high) => format!("{low}-{high}"),
_ => String::new(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Fallback {
Builtin(&'static str),
Server,
Host,
Absent,
}
#[derive(Debug, Clone, Copy)]
pub struct KeySpec {
pub name: &'static str,
pub domain: Domain,
pub fallback: Fallback,
pub about: &'static str,
}
impl KeySpec {
pub fn default_value(&self) -> Result<Option<Value>> {
match self.fallback {
Fallback::Builtin(raw) => super::validate(self.name, raw).map(Some),
Fallback::Server | Fallback::Host | Fallback::Absent => Ok(None),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Value {
Boolean(bool),
Integer(u64),
Enumeration(&'static str),
Text(String),
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Boolean(value) => write!(f, "{value}"),
Self::Integer(value) => write!(f, "{value}"),
Self::Enumeration(value) => write!(f, "{value}"),
Self::Text(value) => write!(f, "{value}"),
}
}
}
impl From<&Value> for serde_json::Value {
fn from(value: &Value) -> Self {
match value {
Value::Boolean(inner) => Self::Bool(*inner),
Value::Integer(inner) => Self::from(*inner),
Value::Enumeration(inner) => Self::from(*inner),
Value::Text(inner) => Self::from(inner.clone()),
}
}
}