use std::collections::HashMap;
use serde_json::Map;
use super::json::{number_to_json, write_number, write_str};
pub enum Value {
Null,
Bool(bool),
Number(f64),
String(String),
Array(Vec<Value>),
Object(Object),
Variable(Variable),
Function(Function),
}
impl Clone for Value {
fn clone(&self) -> Self {
crate::depth::grow!(match self {
Value::Null => Value::Null,
Value::Bool(b) => Value::Bool(*b),
Value::Number(n) => Value::Number(*n),
Value::String(s) => Value::String(s.clone()),
Value::Array(items) => Value::Array(items.clone()),
Value::Object(object) => Value::Object(object.clone()),
Value::Variable(variable) => Value::Variable(variable.clone()),
Value::Function(function) => Value::Function(function.clone()),
})
}
}
impl PartialEq for Value {
fn eq(&self, other: &Value) -> bool {
crate::depth::grow!(match (self, other) {
(Value::Null, Value::Null) => true,
(Value::Bool(a), Value::Bool(b)) => a == b,
(Value::Number(a), Value::Number(b)) => a == b,
(Value::String(a), Value::String(b)) => a == b,
(Value::Array(a), Value::Array(b)) => a == b,
(Value::Object(a), Value::Object(b)) => a == b,
(Value::Variable(a), Value::Variable(b)) => a == b,
(Value::Function(a), Value::Function(b)) => a == b,
_ => false,
})
}
}
impl std::fmt::Debug for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
crate::types::debug_level(f, |f| match self {
Value::Null => f.write_str("Null"),
Value::Bool(b) => f.debug_tuple("Bool").field(b).finish(),
Value::Number(n) => f.debug_tuple("Number").field(n).finish(),
Value::String(s) => f.debug_tuple("String").field(s).finish(),
Value::Array(items) => f.debug_tuple("Array").field(items).finish(),
Value::Object(object) => f.debug_tuple("Object").field(object).finish(),
Value::Variable(variable) => f.debug_tuple("Variable").field(variable).finish(),
Value::Function(function) => f.debug_tuple("Function").field(function).finish(),
})
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Variable {
pub path: Vec<Value>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Function {
pub name: String,
pub parameters: Object,
}
#[derive(Clone, Debug, Default)]
pub struct Object {
props: Vec<(String, Value)>,
index: Option<HashMap<String, usize>>,
proto: Prototype,
}
const INDEXED_FROM: usize = 16;
impl PartialEq for Object {
fn eq(&self, other: &Object) -> bool {
self.props == other.props && self.proto == other.proto
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub enum Prototype {
#[default]
ObjectPrototype,
Null,
Value(Box<Value>),
}
impl Value {
pub fn truthy(&self) -> bool {
match self {
Value::Null => false,
Value::Bool(b) => *b,
Value::Number(n) => !(*n == 0.0 || n.is_nan()),
Value::String(s) => !s.is_empty(),
Value::Array(_) | Value::Object(_) | Value::Variable(_) | Value::Function(_) => true,
}
}
fn is_object(&self) -> bool {
matches!(
self,
Value::Array(_) | Value::Object(_) | Value::Variable(_) | Value::Function(_)
)
}
pub fn to_json(&self) -> serde_json::Value {
crate::depth::grow!(self.to_json_here())
}
#[inline(always)]
fn to_json_here(&self) -> serde_json::Value {
match self {
Value::Null => serde_json::Value::Null,
Value::Bool(b) => serde_json::Value::Bool(*b),
Value::Number(n) => number_to_json(*n),
Value::String(s) => serde_json::Value::String(s.clone()),
Value::Array(items) => {
serde_json::Value::Array(items.iter().map(Value::to_json).collect())
}
Value::Object(o) => o.to_json(),
Value::Variable(v) => {
let mut m = Map::new();
m.insert("$$mdtype".into(), "Variable".into());
m.insert(
"path".into(),
serde_json::Value::Array(v.path.iter().map(Value::to_json).collect()),
);
serde_json::Value::Object(m)
}
Value::Function(f) => {
let mut m = Map::new();
m.insert("$$mdtype".into(), "Function".into());
m.insert("name".into(), f.name.clone().into());
m.insert("parameters".into(), f.parameters.to_json());
serde_json::Value::Object(m)
}
}
}
pub fn to_json_string(&self) -> String {
let mut out = String::new();
self.write_json(&mut out);
out
}
pub(crate) fn write_json(&self, out: &mut String) {
crate::depth::grow!(self.write_json_here(out));
}
#[inline(always)]
fn write_json_here(&self, out: &mut String) {
match self {
Value::Null => out.push_str("null"),
Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Value::Number(n) => write_number(out, *n),
Value::String(s) => write_str(out, s),
Value::Array(items) => write_array(out, items),
Value::Object(o) => o.write_json(out),
Value::Variable(v) => {
out.push_str("{\"$$mdtype\":\"Variable\",\"path\":");
write_array(out, &v.path);
out.push('}');
}
Value::Function(f) => {
out.push_str("{\"$$mdtype\":\"Function\",\"name\":");
write_str(out, &f.name);
out.push_str(",\"parameters\":");
f.parameters.write_json(out);
out.push('}');
}
}
}
}
fn write_array(out: &mut String, items: &[Value]) {
out.push('[');
for (i, item) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
item.write_json(out);
}
out.push(']');
}
fn array_index(key: &str) -> Option<u32> {
let bytes = key.as_bytes();
if bytes.is_empty() || bytes.len() > 10 || !bytes.iter().all(u8::is_ascii_digit) {
return None;
}
if bytes.len() > 1 && bytes[0] == b'0' {
return None;
}
let n: u64 = key.parse().ok()?;
(n < u64::from(u32::MAX)).then_some(n as u32)
}
impl Object {
pub fn new() -> Object {
Object::default()
}
pub(crate) fn with_property(key: String, value: Value) -> Object {
let mut object = Object::new();
object.create_data_property(key, value);
object
}
fn position(&self, key: &str) -> Option<usize> {
match &self.index {
Some(index) => index.get(key).copied(),
None => self.props.iter().position(|(k, _)| k == key),
}
}
fn create_data_property(&mut self, key: String, value: Value) {
if let Some(index) = &mut self.index {
index.insert(key.clone(), self.props.len());
} else if self.props.len() >= INDEXED_FROM {
let mut index: HashMap<String, usize> = self
.props
.iter()
.enumerate()
.map(|(i, (k, _))| (k.clone(), i))
.collect();
index.insert(key.clone(), self.props.len());
self.index = Some(index);
}
self.props.push((key, value));
}
pub fn set(&mut self, key: String, value: Value) {
if let Some(i) = self.position(&key) {
self.props[i].1 = value;
return;
}
if key == "__proto__" && inherits_proto_accessor(&self.proto) {
if let Value::Null = value {
self.proto = Prototype::Null;
} else if value.is_object() {
self.proto = Prototype::Value(Box::new(value));
}
return;
}
self.create_data_property(key, value);
}
pub(crate) fn assign(&mut self, source: Object) {
let order = source.order();
let mut props: Vec<Option<(String, Value)>> = source.props.into_iter().map(Some).collect();
for i in order {
let (key, value) = props[i].take().expect("each property is visited once");
self.set(key, value);
}
}
fn order(&self) -> Vec<usize> {
let mut indices: Vec<(u32, usize)> = self
.props
.iter()
.enumerate()
.filter_map(|(i, (k, _))| array_index(k).map(|n| (n, i)))
.collect();
indices.sort_unstable();
let mut order: Vec<usize> = indices.into_iter().map(|(_, i)| i).collect();
order.extend((0..self.props.len()).filter(|&i| array_index(&self.props[i].0).is_none()));
order
}
pub fn entries(&self) -> Vec<(&str, &Value)> {
self.order()
.into_iter()
.map(|i| (self.props[i].0.as_str(), &self.props[i].1))
.collect()
}
pub fn get(&self, key: &str) -> Option<&Value> {
self.position(key).map(|i| &self.props[i].1)
}
pub fn len(&self) -> usize {
self.props.len()
}
pub fn is_empty(&self) -> bool {
self.props.is_empty()
}
pub fn prototype(&self) -> &Prototype {
&self.proto
}
pub fn to_json(&self) -> serde_json::Value {
let mut m = Map::new();
for (k, v) in self.entries() {
m.insert(k.to_string(), v.to_json());
}
serde_json::Value::Object(m)
}
pub(crate) fn write_json(&self, out: &mut String) {
out.push('{');
for (i, (k, v)) in self.entries().into_iter().enumerate() {
if i > 0 {
out.push(',');
}
write_str(out, k);
out.push(':');
v.write_json(out);
}
out.push('}');
}
}
fn inherits_proto_accessor(mut proto: &Prototype) -> bool {
loop {
match proto {
Prototype::ObjectPrototype => return true,
Prototype::Null => return false,
Prototype::Value(value) => match &**value {
Value::Object(o) => {
if o.get("__proto__").is_some() {
return false;
}
proto = &o.proto;
}
_ => return true,
},
}
}
}