cuddle-v2/crates/cuddle-value/src/lib.rs
kjuulh 6729f6e794
feat: refactor projects
Signed-off-by: kjuulh <contact@kjuulh.io>
2024-10-26 22:27:16 +02:00

44 lines
1.3 KiB
Rust

use std::collections::BTreeMap;
use serde::Serialize;
#[derive(Clone, PartialEq, Eq, Debug, Serialize)]
#[serde(untagged)]
pub enum Value {
String(String),
Bool(bool),
Array(Vec<Value>),
Map(BTreeMap<String, Value>),
}
impl From<&toml::Value> for Value {
fn from(value: &toml::Value) -> Self {
match value {
toml::Value::String(s) => Self::String(s.clone()),
toml::Value::Integer(i) => Self::String(i.to_string()),
toml::Value::Float(f) => Self::String(f.to_string()),
toml::Value::Boolean(b) => Self::Bool(*b),
toml::Value::Datetime(dt) => Self::String(dt.to_string()),
toml::Value::Array(array) => Self::Array(array.iter().map(|i| i.into()).collect()),
toml::Value::Table(tbl) => {
Self::Map(tbl.iter().map(|(k, v)| (k.clone(), v.into())).collect())
}
}
}
}
impl Value {
pub fn get(&self, path: &[&str]) -> Option<&Value> {
match path.split_first() {
Some((current, rest)) => match self {
Value::Map(map) => match map.get(&current.to_string()) {
Some(value) => value.get(rest),
None => None,
},
_ => None,
},
None => Some(self),
}
}
}