use serde::Deserialize;
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub enum TomlValue {
String(String),
Integer(i64),
Float(f64),
Boolean(bool),
DateTime(String),
Array(TomlArray),
Table(TomlTable),
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct TomlArray {
pub list: Vec<TomlValue>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct TomlTable {
pub dict: HashMap<String, TomlValue>,
}
impl TomlValue {
pub fn as_str(&self) -> Option<&str> {
match self {
TomlValue::String(s) => Some(s),
_ => None,
}
}
pub fn as_integer(&self) -> Option<i64> {
match self {
TomlValue::Integer(i) => Some(*i),
_ => None,
}
}
pub fn as_bool(&self) -> Option<bool> {
match self {
TomlValue::Boolean(b) => Some(*b),
_ => None,
}
}
pub fn as_array(&self) -> Option<&Vec<TomlValue>> {
match self {
TomlValue::Array(TomlArray { list: a }) => Some(a),
_ => None,
}
}
pub fn as_table(&self) -> Option<&HashMap<String, TomlValue>> {
match self {
TomlValue::Table(TomlTable { dict: t }) => Some(t),
_ => None,
}
}
pub fn get(&self, key: &str) -> Option<&TomlValue> {
match self {
TomlValue::Table(TomlTable { dict: t }) => t.get(key),
_ => None,
}
}
}
impl std::fmt::Display for TomlValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TomlValue::String(s) => write!(f, "\"{}\"", s),
TomlValue::Integer(i) => write!(f, "{}", i),
TomlValue::Float(fl) => write!(f, "{}", fl),
TomlValue::Boolean(b) => write!(f, "{}", b),
TomlValue::DateTime(dt) => write!(f, "{}", dt),
TomlValue::Array(TomlArray { list: a }) => {
write!(f, "[")?;
for (i, item) in a.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}", item)?;
}
write!(f, "]")
}
TomlValue::Table(TomlTable { dict: t }) => {
write!(f, "{{")?;
for (i, (key, value)) in t.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{} = {}", key, value)?;
}
write!(f, "}}")
}
}
}
}