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