use crate::{Duration, Error, Instant};
use serde_core::de::{
self, Deserialize, Deserializer, EnumAccess, MapAccess, SeqAccess, VariantAccess, Visitor,
};
use serde_core::ser::{Serialize, Serializer};
use std::collections::BTreeMap;
use std::collections::btree_map::Entry;
use std::fmt::{self, Display};
use std::str::FromStr;
pub type Object = BTreeMap<String, Value>;
#[derive(Debug, Clone, PartialEq, Default)]
pub enum Value {
#[default]
Null,
Bool(bool),
Int(i64),
Float(f64),
String(String),
Instant(Instant),
Duration(Duration),
Array(Vec<Self>),
Object(Object),
}
pub trait Index: private::Sealed {
#[doc(hidden)]
fn index_into(self, value: &Value) -> Option<&Value>;
#[doc(hidden)]
fn index_into_mut(self, value: &mut Value) -> Option<&mut Value>;
}
impl Index for &str {
fn index_into(self, value: &Value) -> Option<&Value> {
value.as_object()?.get(self)
}
fn index_into_mut(self, value: &mut Value) -> Option<&mut Value> {
value.as_object_mut()?.get_mut(self)
}
}
impl Index for &String {
fn index_into(self, value: &Value) -> Option<&Value> {
self.as_str().index_into(value)
}
fn index_into_mut(self, value: &mut Value) -> Option<&mut Value> {
self.as_str().index_into_mut(value)
}
}
impl Index for usize {
fn index_into(self, value: &Value) -> Option<&Value> {
value.as_array()?.get(self)
}
fn index_into_mut(self, value: &mut Value) -> Option<&mut Value> {
value.as_array_mut()?.get_mut(self)
}
}
mod private {
pub trait Sealed {}
impl Sealed for &str {}
impl Sealed for &String {}
impl Sealed for usize {}
}
impl Value {
pub(crate) fn check(&self, depth: usize) -> Result<(), Error> {
match self {
Self::Float(value) if value.is_nan() => Err(Error::write("NaN is not a SOML value")),
Self::String(text) => crate::write::check_representable(text, "string"),
Self::Array(items) => {
let depth = crate::ser::nested_depth(depth)?;
for item in items {
item.check(depth)?;
}
Ok(())
}
Self::Object(object) => {
let depth = crate::ser::nested_depth(depth)?;
for (key, value) in object {
value.check(depth)?;
crate::write::check_representable(key, "key")?;
}
Ok(())
}
_ => Ok(()),
}
}
#[must_use]
pub fn get(&self, index: impl Index) -> Option<&Self> {
index.index_into(self)
}
pub fn get_mut(&mut self, index: impl Index) -> Option<&mut Self> {
index.index_into_mut(self)
}
#[must_use]
pub const fn is_null(&self) -> bool {
matches!(self, Self::Null)
}
#[must_use]
pub const fn as_bool(&self) -> Option<bool> {
match self {
Self::Bool(value) => Some(*value),
_ => None,
}
}
#[must_use]
pub const fn as_i64(&self) -> Option<i64> {
match self {
Self::Int(value) => Some(*value),
_ => None,
}
}
#[must_use]
pub const fn as_f64(&self) -> Option<f64> {
match self {
Self::Float(value) => Some(*value),
_ => None,
}
}
#[must_use]
pub const fn as_str(&self) -> Option<&str> {
match self {
Self::String(value) => Some(value.as_str()),
_ => None,
}
}
#[must_use]
pub const fn as_instant(&self) -> Option<Instant> {
match self {
Self::Instant(value) => Some(*value),
_ => None,
}
}
#[must_use]
pub const fn as_duration(&self) -> Option<Duration> {
match self {
Self::Duration(value) => Some(*value),
_ => None,
}
}
#[must_use]
pub const fn as_array(&self) -> Option<&Vec<Self>> {
match self {
Self::Array(value) => Some(value),
_ => None,
}
}
pub const fn as_array_mut(&mut self) -> Option<&mut Vec<Self>> {
match self {
Self::Array(value) => Some(value),
_ => None,
}
}
#[must_use]
pub const fn as_object(&self) -> Option<&Object> {
match self {
Self::Object(value) => Some(value),
_ => None,
}
}
pub const fn as_object_mut(&mut self) -> Option<&mut Object> {
match self {
Self::Object(value) => Some(value),
_ => None,
}
}
}
impl FromStr for Value {
type Err = Error;
fn from_str(text: &str) -> Result<Self, Error> {
crate::parse::parse(text).map(crate::parse::Node::into_value)
}
}
macro_rules! from_integer {
($($type:ty),*) => {
$(
impl From<$type> for Value {
fn from(value: $type) -> Self {
Self::Int(value.into())
}
}
)*
};
}
from_integer!(i8, i16, i32, i64, u8, u16, u32);
impl From<f64> for Value {
fn from(value: f64) -> Self {
Self::Float(value)
}
}
impl From<f32> for Value {
fn from(value: f32) -> Self {
Self::Float(crate::ser::widen(value))
}
}
impl From<bool> for Value {
fn from(value: bool) -> Self {
Self::Bool(value)
}
}
impl From<String> for Value {
fn from(value: String) -> Self {
Self::String(value)
}
}
impl From<&str> for Value {
fn from(value: &str) -> Self {
Self::String(value.to_owned())
}
}
impl From<Instant> for Value {
fn from(value: Instant) -> Self {
Self::Instant(value)
}
}
impl From<Duration> for Value {
fn from(value: Duration) -> Self {
Self::Duration(value)
}
}
impl<T: Into<Self>> From<Vec<T>> for Value {
fn from(value: Vec<T>) -> Self {
value.into_iter().collect()
}
}
impl<T: Into<Self>, const N: usize> From<[T; N]> for Value {
fn from(value: [T; N]) -> Self {
value.into_iter().collect()
}
}
impl From<Object> for Value {
fn from(value: Object) -> Self {
Self::Object(value)
}
}
impl<T: Into<Self>> From<Option<T>> for Value {
fn from(value: Option<T>) -> Self {
value.map_or(Self::Null, Into::into)
}
}
impl<T: Into<Self>> FromIterator<T> for Value {
fn from_iter<I: IntoIterator<Item = T>>(iterator: I) -> Self {
Self::Array(iterator.into_iter().map(Into::into).collect())
}
}
impl<K: Into<String>, V: Into<Self>> FromIterator<(K, V)> for Value {
fn from_iter<I: IntoIterator<Item = (K, V)>>(iterator: I) -> Self {
Self::Object(
iterator
.into_iter()
.map(|(key, value)| (key.into(), value.into()))
.collect(),
)
}
}
pub(crate) struct TextVisitor<F> {
pub expecting: &'static str,
pub parse: F,
}
impl<'de, T, F: FnOnce(&str) -> Result<T, String>> Visitor<'de> for TextVisitor<F> {
type Value = T;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.expecting)
}
fn visit_str<E: de::Error>(self, text: &str) -> Result<T, E> {
(self.parse)(text).map_err(E::custom)
}
fn visit_newtype_struct<D: Deserializer<'de>>(self, deserializer: D) -> Result<T, D::Error> {
deserializer.deserialize_str(self)
}
}
pub(crate) struct CanonicalText<'a, T: Display>(pub &'a T);
impl<T: Display> Serialize for CanonicalText<'_, T> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self.0)
}
}
impl Serialize for Value {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
Self::Null => serializer.serialize_unit(),
Self::Bool(value) => serializer.serialize_bool(*value),
Self::Int(value) => serializer.serialize_i64(*value),
Self::Float(value) => serializer.serialize_f64(*value),
Self::String(value) => serializer.serialize_str(value),
Self::Instant(value) => value.serialize(serializer),
Self::Duration(value) => value.serialize(serializer),
Self::Array(value) => serializer.collect_seq(value),
Self::Object(value) => serializer.collect_map(value),
}
}
}
pub(crate) const TOKEN: &str = "$soml::Value";
impl<'de> Deserialize<'de> for Value {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_newtype_struct(TOKEN, ValueVisitor)
}
}
struct ValueVisitor;
impl<'de> Visitor<'de> for ValueVisitor {
type Value = Value;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("any SOML value")
}
fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
Ok(Value::from(value))
}
fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
Ok(Value::from(value))
}
fn visit_u64<E: de::Error>(self, value: u64) -> Result<Value, E> {
crate::ser::integer(value)
.map(Value::Int)
.map_err(E::custom)
}
fn visit_i128<E: de::Error>(self, value: i128) -> Result<Value, E> {
crate::ser::integer(value)
.map(Value::Int)
.map_err(E::custom)
}
fn visit_u128<E: de::Error>(self, value: u128) -> Result<Value, E> {
crate::ser::integer(value)
.map(Value::Int)
.map_err(E::custom)
}
fn visit_f32<E>(self, value: f32) -> Result<Value, E> {
Ok(Value::from(value))
}
fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
Ok(Value::from(value))
}
fn visit_str<E>(self, value: &str) -> Result<Value, E> {
Ok(Value::from(value))
}
fn visit_string<E>(self, value: String) -> Result<Value, E> {
Ok(Value::from(value))
}
fn visit_unit<E>(self) -> Result<Value, E> {
Ok(Value::Null)
}
fn visit_none<E: de::Error>(self) -> Result<Value, E> {
self.visit_unit()
}
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Value, D::Error> {
Value::deserialize(deserializer)
}
fn visit_newtype_struct<D: Deserializer<'de>>(
self,
deserializer: D,
) -> Result<Value, D::Error> {
deserializer.deserialize_any(self)
}
fn visit_seq<A: SeqAccess<'de>>(self, mut sequence: A) -> Result<Value, A::Error> {
let mut items = Vec::with_capacity(crate::ser::capacity::<Value>(sequence.size_hint()));
while let Some(item) = sequence.next_element()? {
items.push(item);
}
Ok(Value::Array(items))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
let mut object = Object::new();
while let Some(key) = map.next_key::<String>()? {
match object.entry(key) {
Entry::Vacant(entry) => {
entry.insert(map.next_value()?);
}
Entry::Occupied(entry) => {
return Err(de::Error::custom(Error::data(format!(
"Duplicate key “{}”",
crate::abbreviate(entry.key(), 40)
))));
}
}
}
Ok(Value::Object(object))
}
fn visit_enum<A: EnumAccess<'de>>(self, data: A) -> Result<Value, A::Error> {
let (name, variant): (&str, _) = data.variant()?;
match name {
crate::instant::TOKEN => variant.newtype_variant().map(Value::Instant),
crate::duration::TOKEN => variant.newtype_variant().map(Value::Duration),
_ => Err(de::Error::custom("A SOML value cannot hold an enum")),
}
}
}