stratum-node-config 0.1.0-alpha.3

Versioned stratum.toml schema, comment-preserving editor, semantic validator, change preview and public-config hash for Stratum nodes
Documentation
//! The configuration value type and its TOML encodings.

use std::fmt;
use std::fmt::Write as _;

use serde::{Deserialize, Serialize};

/// A configuration value, independent of any TOML or JSON library.
///
/// Every schema field holds exactly one of these shapes. Secret references
/// are carried as [`Value::String`]; whether a string is a secret reference is
/// a property of the field, not of the value.
///
/// With `serde`, a value serialises as the bare JSON scalar or array
/// (`"text"`, `42`, `true`, `["a", "b"]`) and deserialises from the same.
///
/// # Examples
///
/// ```
/// use stratum_node_config::Value;
///
/// let v = Value::from(262_144);
/// assert_eq!(v.as_integer(), Some(262_144));
/// assert_eq!(v.to_string(), "262144");
/// assert_eq!(Value::from("a\"b").to_string(), r#""a\"b""#);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum Value {
    /// A boolean.
    Boolean(bool),
    /// A signed 64-bit integer, the range of a TOML integer.
    Integer(i64),
    /// A UTF-8 string.
    String(String),
    /// An ordered list of strings.
    StringList(Vec<String>),
}

impl Value {
    /// Returns the string if this is a [`Value::String`].
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(s) => Some(s),
            _ => None,
        }
    }

    /// Returns the integer if this is a [`Value::Integer`].
    pub fn as_integer(&self) -> Option<i64> {
        match self {
            Self::Integer(i) => Some(*i),
            _ => None,
        }
    }

    /// Returns the boolean if this is a [`Value::Boolean`].
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Boolean(b) => Some(*b),
            _ => None,
        }
    }

    /// Returns the elements if this is a [`Value::StringList`].
    pub fn as_string_list(&self) -> Option<&[String]> {
        match self {
            Self::StringList(l) => Some(l),
            _ => None,
        }
    }

    /// Names the shape of this value for error messages.
    pub(crate) fn kind_name(&self) -> &'static str {
        match self {
            Self::Boolean(_) => "a boolean",
            Self::Integer(_) => "an integer",
            Self::String(_) => "a string",
            Self::StringList(_) => "a list of strings",
        }
    }

    /// Converts to a fresh `toml_edit` value with default decoration.
    pub(crate) fn to_toml(&self) -> toml_edit::Value {
        match self {
            Self::Boolean(b) => toml_edit::Value::from(*b),
            Self::Integer(i) => toml_edit::Value::from(*i),
            Self::String(s) => toml_edit::Value::from(s.as_str()),
            Self::StringList(l) => {
                let array: toml_edit::Array = l.iter().map(String::as_str).collect();
                toml_edit::Value::Array(array)
            }
        }
    }

    /// Reads a TOML item, or names the TOML type found when it has no
    /// [`Value`] shape (floats, datetimes, tables, mixed arrays).
    pub(crate) fn from_toml(item: &toml_edit::Item) -> Result<Self, &'static str> {
        let Some(value) = item.as_value() else {
            return Err(if item.is_array_of_tables() {
                "an array of tables"
            } else {
                "a table"
            });
        };
        match value {
            toml_edit::Value::String(s) => Ok(Self::String(s.value().clone())),
            toml_edit::Value::Integer(i) => Ok(Self::Integer(*i.value())),
            toml_edit::Value::Boolean(b) => Ok(Self::Boolean(*b.value())),
            toml_edit::Value::Float(_) => Err("a float"),
            toml_edit::Value::Datetime(_) => Err("a datetime"),
            toml_edit::Value::InlineTable(_) => Err("an inline table"),
            toml_edit::Value::Array(a) => a
                .iter()
                .map(|v| v.as_str().map(str::to_owned))
                .collect::<Option<Vec<String>>>()
                .map(Self::StringList)
                .ok_or("an array containing non-string elements"),
        }
    }

    /// Appends the canonical TOML encoding of this value to `out`.
    ///
    /// Strings are basic strings in which `"` and `\` are backslash-escaped
    /// and every control character (U+0000 to U+001F and U+007F) is written as
    /// `\uXXXX` with upper-case hex; all other characters are literal UTF-8.
    /// Integers are decimal with a leading `-` when negative. Lists are
    /// `[` elements separated by `", "` `]`. The encoding never contains a raw
    /// newline, so one value always fits on one line.
    pub(crate) fn write_canonical(&self, out: &mut String) {
        match self {
            Self::Boolean(b) => out.push_str(if *b { "true" } else { "false" }),
            Self::Integer(i) => out.push_str(&i.to_string()),
            Self::String(s) => write_canonical_str(s, out),
            Self::StringList(l) => {
                out.push('[');
                for (n, s) in l.iter().enumerate() {
                    if n > 0 {
                        out.push_str(", ");
                    }
                    write_canonical_str(s, out);
                }
                out.push(']');
            }
        }
    }
}

fn write_canonical_str(s: &str, out: &mut String) {
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            c if c.is_control() && u32::from(c) <= 0x7f => {
                // Writing to a String cannot fail.
                let _ = write!(out, "\\u{:04X}", u32::from(c));
            }
            c => out.push(c),
        }
    }
    out.push('"');
}

/// Formats the value in its canonical TOML encoding.
impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = String::new();
        self.write_canonical(&mut s);
        f.write_str(&s)
    }
}

impl From<bool> for Value {
    fn from(b: bool) -> Self {
        Self::Boolean(b)
    }
}

impl From<i64> for Value {
    fn from(i: i64) -> Self {
        Self::Integer(i)
    }
}

impl From<&str> for Value {
    fn from(s: &str) -> Self {
        Self::String(s.to_owned())
    }
}

impl From<String> for Value {
    fn from(s: String) -> Self {
        Self::String(s)
    }
}

impl From<Vec<String>> for Value {
    fn from(l: Vec<String>) -> Self {
        Self::StringList(l)
    }
}

impl From<&[&str]> for Value {
    fn from(l: &[&str]) -> Self {
        Self::StringList(l.iter().map(|s| (*s).to_owned()).collect())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn canonical_strings_escape_quotes_backslashes_and_controls() {
        let v = Value::from("a\"b\\c\nd\u{7f}é");
        assert_eq!(
            v.to_string(),
            r#""a\"b\\c\u000Ad\u007Fé""#,
            "canonical escaping"
        );
    }

    #[test]
    fn canonical_lists() {
        assert_eq!(Value::StringList(vec![]).to_string(), "[]", "empty list");
        let l = Value::from(&["a", "b, c"][..]);
        assert_eq!(l.to_string(), r#"["a", "b, c"]"#, "list encoding");
    }
}