use std::fmt;
use std::fmt::Write as _;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum Value {
Boolean(bool),
Integer(i64),
String(String),
StringList(Vec<String>),
}
impl Value {
pub fn as_str(&self) -> Option<&str> {
match self {
Self::String(s) => Some(s),
_ => None,
}
}
pub fn as_integer(&self) -> Option<i64> {
match self {
Self::Integer(i) => Some(*i),
_ => None,
}
}
pub fn as_bool(&self) -> Option<bool> {
match self {
Self::Boolean(b) => Some(*b),
_ => None,
}
}
pub fn as_string_list(&self) -> Option<&[String]> {
match self {
Self::StringList(l) => Some(l),
_ => None,
}
}
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",
}
}
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)
}
}
}
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"),
}
}
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 => {
let _ = write!(out, "\\u{:04X}", u32::from(c));
}
c => out.push(c),
}
}
out.push('"');
}
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");
}
}