Skip to main content

stratum_node_config/
value.rs

1//! The configuration value type and its TOML encodings.
2
3use std::fmt;
4use std::fmt::Write as _;
5
6use serde::{Deserialize, Serialize};
7
8/// A configuration value, independent of any TOML or JSON library.
9///
10/// Every schema field holds exactly one of these shapes. Secret references
11/// are carried as [`Value::String`]; whether a string is a secret reference is
12/// a property of the field, not of the value.
13///
14/// With `serde`, a value serialises as the bare JSON scalar or array
15/// (`"text"`, `42`, `true`, `["a", "b"]`) and deserialises from the same.
16///
17/// # Examples
18///
19/// ```
20/// use stratum_node_config::Value;
21///
22/// let v = Value::from(262_144);
23/// assert_eq!(v.as_integer(), Some(262_144));
24/// assert_eq!(v.to_string(), "262144");
25/// assert_eq!(Value::from("a\"b").to_string(), r#""a\"b""#);
26/// ```
27#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
28#[serde(untagged)]
29#[non_exhaustive]
30pub enum Value {
31    /// A boolean.
32    Boolean(bool),
33    /// A signed 64-bit integer, the range of a TOML integer.
34    Integer(i64),
35    /// A UTF-8 string.
36    String(String),
37    /// An ordered list of strings.
38    StringList(Vec<String>),
39}
40
41impl Value {
42    /// Returns the string if this is a [`Value::String`].
43    pub fn as_str(&self) -> Option<&str> {
44        match self {
45            Self::String(s) => Some(s),
46            _ => None,
47        }
48    }
49
50    /// Returns the integer if this is a [`Value::Integer`].
51    pub fn as_integer(&self) -> Option<i64> {
52        match self {
53            Self::Integer(i) => Some(*i),
54            _ => None,
55        }
56    }
57
58    /// Returns the boolean if this is a [`Value::Boolean`].
59    pub fn as_bool(&self) -> Option<bool> {
60        match self {
61            Self::Boolean(b) => Some(*b),
62            _ => None,
63        }
64    }
65
66    /// Returns the elements if this is a [`Value::StringList`].
67    pub fn as_string_list(&self) -> Option<&[String]> {
68        match self {
69            Self::StringList(l) => Some(l),
70            _ => None,
71        }
72    }
73
74    /// Names the shape of this value for error messages.
75    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    /// Converts to a fresh `toml_edit` value with default decoration.
85    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    /// Reads a TOML item, or names the TOML type found when it has no
98    /// [`Value`] shape (floats, datetimes, tables, mixed arrays).
99    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    /// Appends the canonical TOML encoding of this value to `out`.
124    ///
125    /// Strings are basic strings in which `"` and `\` are backslash-escaped
126    /// and every control character (U+0000 to U+001F and U+007F) is written as
127    /// `\uXXXX` with upper-case hex; all other characters are literal UTF-8.
128    /// Integers are decimal with a leading `-` when negative. Lists are
129    /// `[` elements separated by `", "` `]`. The encoding never contains a raw
130    /// newline, so one value always fits on one line.
131    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                // Writing to a String cannot fail.
158                let _ = write!(out, "\\u{:04X}", u32::from(c));
159            }
160            c => out.push(c),
161        }
162    }
163    out.push('"');
164}
165
166/// Formats the value in its canonical TOML encoding.
167impl 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}