use crate::map::{self, OrderedMap};
use std::fmt;
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq, Default)]
pub enum Value {
#[default]
Null,
Bool(bool),
Number(f64),
String(String),
Array(Vec<Value>),
Object(Object),
}
impl Value {
pub fn is_null(&self) -> bool {
matches!(self, Value::Null)
}
pub fn as_str(&self) -> Option<&str> {
match self {
Value::String(s) => Some(s),
_ => None,
}
}
pub fn as_f64(&self) -> Option<f64> {
match self {
Value::Number(n) => Some(*n),
_ => None,
}
}
pub fn as_bool(&self) -> Option<bool> {
match self {
Value::Bool(b) => Some(*b),
_ => None,
}
}
pub fn as_array(&self) -> Option<&Vec<Value>> {
match self {
Value::Array(a) => Some(a),
_ => None,
}
}
pub fn as_object(&self) -> Option<&Object> {
match self {
Value::Object(o) => Some(o),
_ => None,
}
}
pub fn get(&self, key: &str) -> Option<&Value> {
self.as_object().and_then(|o| o.get(key))
}
pub fn at(&self, index: usize) -> Option<&Value> {
self.as_array().and_then(|a| a.get(index))
}
pub fn type_name(&self) -> &'static str {
match self {
Value::Null => "null",
Value::Bool(_) => "boolean",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
}
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&super::stringify(self))
}
}
impl From<bool> for Value {
fn from(b: bool) -> Self {
Value::Bool(b)
}
}
impl From<f64> for Value {
fn from(n: f64) -> Self {
Value::Number(n)
}
}
impl From<i64> for Value {
fn from(n: i64) -> Self {
Value::Number(n as f64)
}
}
impl From<i32> for Value {
fn from(n: i32) -> Self {
Value::Number(n.into())
}
}
impl From<&str> for Value {
fn from(s: &str) -> Self {
Value::String(s.to_owned())
}
}
impl From<String> for Value {
fn from(s: String) -> Self {
Value::String(s)
}
}
impl From<Vec<Value>> for Value {
fn from(a: Vec<Value>) -> Self {
Value::Array(a)
}
}
impl From<Object> for Value {
fn from(o: Object) -> Self {
Value::Object(o)
}
}
impl<T: Into<Value>> From<Option<T>> for Value {
fn from(v: Option<T>) -> Self {
v.map_or(Value::Null, Into::into)
}
}
#[derive(Clone, Default)]
pub struct Object {
entries: Arc<OrderedMap<Value>>,
integer_keys: usize,
}
impl Object {
pub fn new() -> Self {
Self::default()
}
pub fn with_capacity(capacity: usize) -> Self {
Object {
entries: Arc::new(OrderedMap::with_capacity(capacity)),
integer_keys: 0,
}
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn get(&self, key: &str) -> Option<&Value> {
self.entries.get(key)
}
pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
if !self.entries.contains_key(key) {
return None;
}
Arc::make_mut(&mut self.entries).get_mut(key)
}
pub fn contains_key(&self, key: &str) -> bool {
self.entries.contains_key(key)
}
pub fn insert(&mut self, key: impl Into<String>, value: Value) -> Option<Value> {
let key = key.into();
let entries = Arc::make_mut(&mut self.entries);
if let Some(slot) = entries.get_mut(&key) {
return Some(std::mem::replace(slot, value));
}
if let Some(n) = array_index(&key) {
let at = entries
.keys()
.take(self.integer_keys)
.position(|k| array_index(k).is_some_and(|m| m > n));
let at = at.unwrap_or(self.integer_keys);
entries.insert_at(at, key, value);
self.integer_keys += 1;
} else {
entries.insert(key, value);
}
None
}
pub fn remove(&mut self, key: &str) -> Option<Value> {
if !self.entries.contains_key(key) {
return None;
}
let (i, value) = Arc::make_mut(&mut self.entries).remove_full(key)?;
if i < self.integer_keys {
self.integer_keys -= 1;
}
Some(value)
}
pub fn iter(&self) -> map::Iter<'_, Value> {
self.entries.iter()
}
pub fn keys(&self) -> impl DoubleEndedIterator<Item = &String> + ExactSizeIterator + Clone {
self.entries.keys()
}
pub fn values(&self) -> impl DoubleEndedIterator<Item = &Value> + ExactSizeIterator + Clone {
self.entries.values()
}
pub fn get_index(&self, index: usize) -> Option<(&String, &Value)> {
self.entries.get_index(index)
}
}
impl PartialEq for Object {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.entries, &other.entries) || self.entries == other.entries
}
}
impl fmt::Debug for Object {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.entries.iter()).finish()
}
}
impl<'a> IntoIterator for &'a Object {
type Item = (&'a String, &'a Value);
type IntoIter = map::Iter<'a, Value>;
fn into_iter(self) -> Self::IntoIter {
self.entries.iter()
}
}
impl IntoIterator for Object {
type Item = (String, Value);
type IntoIter = map::IntoIter<Value>;
fn into_iter(self) -> Self::IntoIter {
Arc::unwrap_or_clone(self.entries).into_iter()
}
}
impl<K: Into<String>> FromIterator<(K, Value)> for Object {
fn from_iter<I: IntoIterator<Item = (K, Value)>>(iter: I) -> Self {
let mut o = Object::new();
for (k, v) in iter {
o.insert(k, v);
}
o
}
}
pub(crate) fn array_index(key: &str) -> Option<u32> {
let bytes = key.as_bytes();
let (&first, rest) = bytes.split_first()?;
if !first.is_ascii_digit() || bytes.len() > 10 || (first == b'0' && !rest.is_empty()) {
return None;
}
let mut n = u64::from(first - b'0');
for &c in rest {
if !c.is_ascii_digit() {
return None;
}
n = n * 10 + u64::from(c - b'0');
}
(n < 0xFFFF_FFFF).then_some(n as u32)
}
#[macro_export]
macro_rules! json {
(null) => { $crate::json::Value::Null };
([ $($e:tt),* $(,)? ]) => { $crate::json::Value::Array(vec![ $( $crate::json!($e) ),* ]) };
({ $($k:literal : $v:tt),* $(,)? }) => {{
#[allow(unused_mut)]
let mut o = $crate::json::Object::new();
$( o.insert($k, $crate::json!($v)); )*
$crate::json::Value::Object(o)
}};
($e:expr) => { $crate::json::Value::from($e) };
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keys_follow_js_property_order() {
let mut o = Object::new();
for k in ["b", "10", "a", "2", "01", "4294967295", "4294967294", "0"] {
o.insert(k, Value::Null);
}
let keys: Vec<_> = o.keys().map(String::as_str).collect();
assert_eq!(
keys,
["0", "2", "10", "4294967294", "b", "a", "01", "4294967295"]
);
o.remove("2");
o.insert("3", Value::Null);
let keys: Vec<_> = o.keys().map(String::as_str).collect();
assert_eq!(
keys,
["0", "3", "10", "4294967294", "b", "a", "01", "4294967295"]
);
}
#[test]
fn a_change_to_a_copy_leaves_the_original() {
let mut original = Object::new();
original.insert("a", Value::from(1.0));
original.insert("b", Value::from(2.0));
let changes: [fn(&mut Object); 4] = [
|o| _ = o.insert("a", Value::from(9.0)),
|o| _ = o.insert("1", Value::Null),
|o| _ = o.remove("b"),
|o| *o.get_mut("a").unwrap() = Value::Null,
];
for change in changes {
let mut copy = original.clone();
change(&mut copy);
assert_ne!(copy, original);
let keys: Vec<_> = original.iter().collect();
assert_eq!(
keys,
[
(&"a".to_owned(), &Value::from(1.0)),
(&"b".to_owned(), &Value::from(2.0))
]
);
assert_eq!(original.integer_keys, 0);
}
}
}