stratum_node_config/
value.rs1use std::fmt;
4use std::fmt::Write as _;
5
6use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
28#[serde(untagged)]
29#[non_exhaustive]
30pub enum Value {
31 Boolean(bool),
33 Integer(i64),
35 String(String),
37 StringList(Vec<String>),
39}
40
41impl Value {
42 pub fn as_str(&self) -> Option<&str> {
44 match self {
45 Self::String(s) => Some(s),
46 _ => None,
47 }
48 }
49
50 pub fn as_integer(&self) -> Option<i64> {
52 match self {
53 Self::Integer(i) => Some(*i),
54 _ => None,
55 }
56 }
57
58 pub fn as_bool(&self) -> Option<bool> {
60 match self {
61 Self::Boolean(b) => Some(*b),
62 _ => None,
63 }
64 }
65
66 pub fn as_string_list(&self) -> Option<&[String]> {
68 match self {
69 Self::StringList(l) => Some(l),
70 _ => None,
71 }
72 }
73
74 pub(crate) fn kind_name(&self) -> &'static str {
76 match self {
77 Self::Boolean(_) => "a boolean",
78 Self::Integer(_) => "an integer",
79 Self::String(_) => "a string",
80 Self::StringList(_) => "a list of strings",
81 }
82 }
83
84 pub(crate) fn to_toml(&self) -> toml_edit::Value {
86 match self {
87 Self::Boolean(b) => toml_edit::Value::from(*b),
88 Self::Integer(i) => toml_edit::Value::from(*i),
89 Self::String(s) => toml_edit::Value::from(s.as_str()),
90 Self::StringList(l) => {
91 let array: toml_edit::Array = l.iter().map(String::as_str).collect();
92 toml_edit::Value::Array(array)
93 }
94 }
95 }
96
97 pub(crate) fn from_toml(item: &toml_edit::Item) -> Result<Self, &'static str> {
100 let Some(value) = item.as_value() else {
101 return Err(if item.is_array_of_tables() {
102 "an array of tables"
103 } else {
104 "a table"
105 });
106 };
107 match value {
108 toml_edit::Value::String(s) => Ok(Self::String(s.value().clone())),
109 toml_edit::Value::Integer(i) => Ok(Self::Integer(*i.value())),
110 toml_edit::Value::Boolean(b) => Ok(Self::Boolean(*b.value())),
111 toml_edit::Value::Float(_) => Err("a float"),
112 toml_edit::Value::Datetime(_) => Err("a datetime"),
113 toml_edit::Value::InlineTable(_) => Err("an inline table"),
114 toml_edit::Value::Array(a) => a
115 .iter()
116 .map(|v| v.as_str().map(str::to_owned))
117 .collect::<Option<Vec<String>>>()
118 .map(Self::StringList)
119 .ok_or("an array containing non-string elements"),
120 }
121 }
122
123 pub(crate) fn write_canonical(&self, out: &mut String) {
132 match self {
133 Self::Boolean(b) => out.push_str(if *b { "true" } else { "false" }),
134 Self::Integer(i) => out.push_str(&i.to_string()),
135 Self::String(s) => write_canonical_str(s, out),
136 Self::StringList(l) => {
137 out.push('[');
138 for (n, s) in l.iter().enumerate() {
139 if n > 0 {
140 out.push_str(", ");
141 }
142 write_canonical_str(s, out);
143 }
144 out.push(']');
145 }
146 }
147 }
148}
149
150fn write_canonical_str(s: &str, out: &mut String) {
151 out.push('"');
152 for c in s.chars() {
153 match c {
154 '"' => out.push_str("\\\""),
155 '\\' => out.push_str("\\\\"),
156 c if c.is_control() && u32::from(c) <= 0x7f => {
157 let _ = write!(out, "\\u{:04X}", u32::from(c));
159 }
160 c => out.push(c),
161 }
162 }
163 out.push('"');
164}
165
166impl fmt::Display for Value {
168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169 let mut s = String::new();
170 self.write_canonical(&mut s);
171 f.write_str(&s)
172 }
173}
174
175impl From<bool> for Value {
176 fn from(b: bool) -> Self {
177 Self::Boolean(b)
178 }
179}
180
181impl From<i64> for Value {
182 fn from(i: i64) -> Self {
183 Self::Integer(i)
184 }
185}
186
187impl From<&str> for Value {
188 fn from(s: &str) -> Self {
189 Self::String(s.to_owned())
190 }
191}
192
193impl From<String> for Value {
194 fn from(s: String) -> Self {
195 Self::String(s)
196 }
197}
198
199impl From<Vec<String>> for Value {
200 fn from(l: Vec<String>) -> Self {
201 Self::StringList(l)
202 }
203}
204
205impl From<&[&str]> for Value {
206 fn from(l: &[&str]) -> Self {
207 Self::StringList(l.iter().map(|s| (*s).to_owned()).collect())
208 }
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214
215 #[test]
216 fn canonical_strings_escape_quotes_backslashes_and_controls() {
217 let v = Value::from("a\"b\\c\nd\u{7f}é");
218 assert_eq!(
219 v.to_string(),
220 r#""a\"b\\c\u000Ad\u007Fé""#,
221 "canonical escaping"
222 );
223 }
224
225 #[test]
226 fn canonical_lists() {
227 assert_eq!(Value::StringList(vec![]).to_string(), "[]", "empty list");
228 let l = Value::from(&["a", "b, c"][..]);
229 assert_eq!(l.to_string(), r#"["a", "b, c"]"#, "list encoding");
230 }
231}