oak_toml/language/
value.rs1use serde::Deserialize;
2use std::collections::HashMap;
3
4#[derive(Debug, Clone, PartialEq, Deserialize)]
8pub enum TomlValue {
9 String(String),
11 Integer(i64),
13 Float(f64),
15 Boolean(bool),
17 DateTime(String),
19 Array(TomlArray),
21 Table(TomlTable),
23}
24
25#[derive(Debug, Clone, PartialEq, Deserialize)]
27pub struct TomlArray {
28 pub list: Vec<TomlValue>,
29}
30
31#[derive(Debug, Clone, PartialEq, Deserialize)]
33pub struct TomlTable {
34 pub dict: HashMap<String, TomlValue>,
35}
36
37impl TomlValue {
38 pub fn as_str(&self) -> Option<&str> {
40 match self {
41 TomlValue::String(s) => Some(s),
42 _ => None,
43 }
44 }
45
46 pub fn as_integer(&self) -> Option<i64> {
48 match self {
49 TomlValue::Integer(i) => Some(*i),
50 _ => None,
51 }
52 }
53
54 pub fn as_bool(&self) -> Option<bool> {
56 match self {
57 TomlValue::Boolean(b) => Some(*b),
58 _ => None,
59 }
60 }
61
62 pub fn as_array(&self) -> Option<&Vec<TomlValue>> {
64 match self {
65 TomlValue::Array(TomlArray { list: a }) => Some(a),
66 _ => None,
67 }
68 }
69
70 pub fn as_table(&self) -> Option<&HashMap<String, TomlValue>> {
72 match self {
73 TomlValue::Table(TomlTable { dict: t }) => Some(t),
74 _ => None,
75 }
76 }
77
78 pub fn get(&self, key: &str) -> Option<&TomlValue> {
80 match self {
81 TomlValue::Table(TomlTable { dict: t }) => t.get(key),
82 _ => None,
83 }
84 }
85}
86
87impl std::fmt::Display for TomlValue {
88 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89 match self {
90 TomlValue::String(s) => write!(f, "\"{}\"", s),
91 TomlValue::Integer(i) => write!(f, "{}", i),
92 TomlValue::Float(fl) => write!(f, "{}", fl),
93 TomlValue::Boolean(b) => write!(f, "{}", b),
94 TomlValue::DateTime(dt) => write!(f, "{}", dt),
95 TomlValue::Array(TomlArray { list: a }) => {
96 write!(f, "[")?;
97 for (i, item) in a.iter().enumerate() {
98 if i > 0 {
99 write!(f, ", ")?;
100 }
101 write!(f, "{}", item)?;
102 }
103 write!(f, "]")
104 }
105 TomlValue::Table(TomlTable { dict: t }) => {
106 write!(f, "{{")?;
107 for (i, (key, value)) in t.iter().enumerate() {
108 if i > 0 {
109 write!(f, ", ")?;
110 }
111 write!(f, "{} = {}", key, value)?;
112 }
113 write!(f, "}}")
114 }
115 }
116 }
117}