use core::fmt;
use std::{any::Any, borrow::Cow, sync::Arc};
use smallvec::SmallVec;
use crate::types::names_eq;
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
Null,
Boolean(bool),
Int(i32),
BigInt(Box<i128>),
Float(f64),
String(Arc<str>),
Enum(Arc<str>),
List(Vec<Value>),
Object(Arc<Object>),
External(External),
}
#[derive(Clone)]
pub struct External(Arc<dyn Any + Send + Sync>);
impl External {
#[must_use]
pub fn new<T: Any + Send + Sync>(value: T) -> Self {
Self(Arc::new(value))
}
#[must_use]
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
self.0.downcast_ref()
}
}
impl fmt::Debug for External {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("External(<model>)")
}
}
impl PartialEq for External {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl Value {
#[must_use]
pub fn string(value: impl Into<Arc<str>>) -> Self {
Self::String(value.into())
}
#[must_use]
pub fn enumeration(value: impl Into<Arc<str>>) -> Self {
Self::Enum(value.into())
}
#[must_use]
pub fn object(object: impl Into<Object>) -> Self {
Self::Object(Arc::new(object.into()))
}
#[must_use]
pub fn integer(value: i128) -> Self {
i32::try_from(value).map_or_else(|_| Self::BigInt(Box::new(value)), Self::Int)
}
#[must_use]
pub const fn is_null(&self) -> bool {
matches!(self, Self::Null)
}
#[must_use]
pub const fn kind(&self) -> &'static str {
match self {
Self::Null => "null",
Self::Boolean(_) => "boolean",
Self::Int(_) | Self::BigInt(_) | Self::Float(_) => "number",
Self::String(_) => "string",
Self::Enum(_) => "enum",
Self::List(_) => "list",
Self::Object(_) => "object",
Self::External(_) => "model",
}
}
#[must_use]
pub fn as_str(&self) -> Option<&str> {
match self {
Self::String(value) => Some(value),
Self::Enum(value) => Some(value),
_ => None,
}
}
#[must_use]
pub const fn as_bool(&self) -> Option<bool> {
match self {
Self::Boolean(value) => Some(*value),
_ => None,
}
}
#[must_use]
pub const fn as_i32(&self) -> Option<i32> {
match self {
Self::Int(value) => Some(*value),
Self::BigInt(value) => {
if **value >= i32::MIN as i128 && **value <= i32::MAX as i128 {
Some(**value as i32)
} else {
None
}
}
_ => None,
}
}
#[must_use]
pub const fn as_i64(&self) -> Option<i64> {
match self {
Self::Int(value) => Some(*value as i64),
Self::BigInt(value) => {
if **value >= i64::MIN as i128 && **value <= i64::MAX as i128 {
Some(**value as i64)
} else {
None
}
}
_ => None,
}
}
#[must_use]
pub const fn as_i128(&self) -> Option<i128> {
match self {
Self::Int(value) => Some(*value as i128),
Self::BigInt(value) => Some(**value),
_ => None,
}
}
#[must_use]
pub fn as_f64(&self) -> Option<f64> {
match self {
Self::Float(value) => Some(*value),
Self::Int(value) => Some(f64::from(*value)),
Self::BigInt(value) => Some(**value as f64),
_ => None,
}
}
#[must_use]
pub fn as_object(&self) -> Option<&Object> {
match self {
Self::Object(object) => Some(object),
_ => None,
}
}
#[must_use]
pub fn as_object_mut(&mut self) -> Option<&mut Object> {
match self {
Self::Object(object) => Some(Arc::make_mut(object)),
_ => None,
}
}
#[must_use]
pub fn as_list(&self) -> Option<&[Value]> {
match self {
Self::List(list) => Some(list),
_ => None,
}
}
#[must_use]
pub fn external<T: Any + Send + Sync>(value: T) -> Self {
Self::External(External::new(value))
}
#[must_use]
pub const fn is_external(&self) -> bool {
matches!(self, Self::External(_))
}
#[must_use]
pub fn as_external<T: Any>(&self) -> Option<&T> {
match self {
Self::External(value) => value.downcast_ref(),
_ => None,
}
}
#[must_use]
pub fn into_list(self) -> Option<Vec<Value>> {
match self {
Self::List(list) => Some(list),
_ => None,
}
}
#[must_use]
pub fn into_string(self) -> Option<Arc<str>> {
match self {
Self::String(value) | Self::Enum(value) => Some(value),
_ => None,
}
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Null => f.write_str("null"),
Self::Boolean(value) => write!(f, "{value}"),
Self::Int(value) => write!(f, "{value}"),
Self::BigInt(value) => write!(f, "{value}"),
Self::Float(value) => write!(f, "{value}"),
Self::String(value) => write!(f, "{value}"),
Self::Enum(value) => f.write_str(value),
Self::List(_) => f.write_str("[list]"),
Self::Object(_) => f.write_str("{object}"),
Self::External(_) => f.write_str("<model>"),
}
}
}
impl From<bool> for Value {
fn from(value: bool) -> Self {
Self::Boolean(value)
}
}
macro_rules! impl_from_int {
($($ty:ty),* $(,)?) => {
$(
impl From<$ty> for Value {
fn from(value: $ty) -> Self {
Self::Int(value as i32)
}
}
)*
};
}
impl_from_int!(i8, i16, i32, u8, u16);
impl From<i64> for Value {
fn from(value: i64) -> Self {
Self::integer(i128::from(value))
}
}
impl From<i128> for Value {
fn from(value: i128) -> Self {
Self::integer(value)
}
}
impl From<u32> for Value {
fn from(value: u32) -> Self {
Self::integer(i128::from(value))
}
}
impl From<u64> for Value {
fn from(value: u64) -> Self {
Self::integer(i128::from(value))
}
}
impl From<f32> for Value {
fn from(value: f32) -> Self {
Self::Float(f64::from(value))
}
}
impl From<f64> for Value {
fn from(value: f64) -> Self {
Self::Float(value)
}
}
impl From<&str> for Value {
fn from(value: &str) -> Self {
Self::String(Arc::from(value))
}
}
impl From<String> for Value {
fn from(value: String) -> Self {
Self::String(Arc::from(value))
}
}
impl From<Arc<str>> for Value {
fn from(value: Arc<str>) -> Self {
Self::String(value)
}
}
impl From<Cow<'_, str>> for Value {
fn from(value: Cow<'_, str>) -> Self {
Self::String(Arc::from(value.as_ref()))
}
}
impl From<Vec<Value>> for Value {
fn from(value: Vec<Value>) -> Self {
Self::List(value)
}
}
impl From<Object> for Value {
fn from(value: Object) -> Self {
Self::Object(Arc::new(value))
}
}
impl<T: Into<Value>> From<Option<T>> for Value {
fn from(value: Option<T>) -> Self {
value.map_or(Self::Null, Into::into)
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Object {
fields: SmallVec<[(Arc<str>, Value); 8]>,
}
impl Object {
#[must_use]
pub fn new() -> Self {
Self {
fields: SmallVec::new(),
}
}
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
Self {
fields: SmallVec::with_capacity(capacity),
}
}
#[must_use]
pub fn from_fields(fields: impl IntoIterator<Item = (impl Into<Arc<str>>, Value)>) -> Self {
let mut object = Self::new();
for (key, value) in fields {
object.insert(key, value);
}
object
}
#[must_use]
pub fn len(&self) -> usize {
self.fields.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.fields.is_empty()
}
#[must_use]
pub fn get(&self, key: &str) -> Option<&Value> {
self.fields
.iter()
.find(|(name, _)| names_eq(name, key))
.map(|(_, value)| value)
}
pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
self.fields
.iter_mut()
.find(|(name, _)| names_eq(name, key))
.map(|(_, value)| value)
}
#[must_use]
pub fn contains_key(&self, key: &str) -> bool {
self.get(key).is_some()
}
pub fn insert(&mut self, key: impl Into<Arc<str>>, value: impl Into<Value>) -> Option<Value> {
let key = key.into();
let value = value.into();
if let Some((_, existing)) = self
.fields
.iter_mut()
.find(|(name, _)| names_eq(name, &key))
{
return Some(core::mem::replace(existing, value));
}
self.fields.push((key, value));
None
}
#[doc(hidden)]
pub fn push_unchecked(&mut self, key: impl Into<Arc<str>>, value: Value) {
self.fields.push((key.into(), value));
}
pub fn remove(&mut self, key: &str) -> Option<Value> {
let index = self
.fields
.iter()
.position(|(name, _)| names_eq(name, key))?;
Some(self.fields.remove(index).1)
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = (&Arc<str>, &Value)> {
self.fields.iter().map(|(key, value)| (key, value))
}
pub fn keys(&self) -> impl ExactSizeIterator<Item = &Arc<str>> {
self.fields.iter().map(|(key, _)| key)
}
pub fn values(&self) -> impl ExactSizeIterator<Item = &Value> {
self.fields.iter().map(|(_, value)| value)
}
pub fn into_fields(self) -> impl Iterator<Item = (Arc<str>, Value)> {
self.fields.into_iter()
}
pub fn reserve(&mut self, additional: usize) {
self.fields.reserve(additional);
}
}
impl FromIterator<(Arc<str>, Value)> for Object {
fn from_iter<T: IntoIterator<Item = (Arc<str>, Value)>>(iter: T) -> Self {
let mut object = Self::new();
for (key, value) in iter {
object.insert(key, value);
}
object
}
}
impl IntoIterator for Object {
type Item = (Arc<str>, Value);
type IntoIter = smallvec::IntoIter<[(Arc<str>, Value); 8]>;
fn into_iter(self) -> Self::IntoIter {
self.fields.into_iter()
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for Value {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> core::result::Result<S::Ok, S::Error> {
match self {
Self::Null => serializer.serialize_none(),
Self::Boolean(value) => serializer.serialize_bool(*value),
Self::Int(value) => serializer.serialize_i32(*value),
Self::BigInt(value) => serializer.serialize_i128(**value),
Self::Float(value) => serializer.serialize_f64(*value),
Self::String(value) | Self::Enum(value) => serializer.serialize_str(value),
Self::List(values) => {
use serde::ser::SerializeSeq as _;
let mut seq = serializer.serialize_seq(Some(values.len()))?;
for value in values {
seq.serialize_element(value)?;
}
seq.end()
}
Self::Object(object) => (**object).serialize(serializer),
Self::External(_) => Err(serde::ser::Error::custom(
"an opaque model value reached the serializer; was an object field resolved?",
)),
}
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for Object {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> core::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeMap as _;
let mut map = serializer.serialize_map(Some(self.fields.len()))?;
for (key, value) in &self.fields {
map.serialize_entry(&**key, value)?;
}
map.end()
}
}