use alloc::{
borrow::Cow,
string::{String, ToString},
vec::Vec,
};
use core::{
fmt,
hash::{Hash, Hasher},
ops::Index,
};
use crate::{Array, Number, Object, tree};
pub(crate) static NULL: Value<'static> = Value::Null;
#[derive(Default)]
pub enum Value<'a> {
#[default]
Null,
Bool(bool),
Number(Number<'a>),
String(Cow<'a, str>),
Array(Array<'a>),
Object(Object<'a>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Kind {
Null,
Bool,
Number,
String,
Array,
Object,
}
impl Kind {
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Null => "null",
Self::Bool => "boolean",
Self::Number => "number",
Self::String => "string",
Self::Array => "array",
Self::Object => "object",
}
}
}
impl fmt::Display for Kind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
impl<'a> Value<'a> {
#[must_use]
pub const fn kind(&self) -> Kind {
match self {
Self::Null => Kind::Null,
Self::Bool(_) => Kind::Bool,
Self::Number(_) => Kind::Number,
Self::String(_) => Kind::String,
Self::Array(_) => Kind::Array,
Self::Object(_) => Kind::Object,
}
}
#[inline]
#[must_use]
pub const fn is_null(&self) -> bool {
matches!(self, Self::Null)
}
#[inline]
#[must_use]
pub const fn is_bool(&self) -> bool {
matches!(self, Self::Bool(_))
}
#[inline]
#[must_use]
pub const fn is_number(&self) -> bool {
matches!(self, Self::Number(_))
}
#[inline]
#[must_use]
pub const fn is_string(&self) -> bool {
matches!(self, Self::String(_))
}
#[inline]
#[must_use]
pub const fn is_array(&self) -> bool {
matches!(self, Self::Array(_))
}
#[inline]
#[must_use]
pub const fn is_object(&self) -> bool {
matches!(self, Self::Object(_))
}
#[inline]
#[must_use]
pub const fn as_bool(&self) -> Option<bool> {
match self {
Self::Bool(b) => Some(*b),
_ => None,
}
}
#[inline]
#[must_use]
pub const fn as_number(&self) -> Option<&Number<'a>> {
match self {
Self::Number(n) => Some(n),
_ => None,
}
}
#[must_use]
pub fn as_i64(&self) -> Option<i64> {
self.as_number().and_then(Number::as_i64)
}
#[must_use]
pub fn as_u64(&self) -> Option<u64> {
self.as_number().and_then(Number::as_u64)
}
#[must_use]
pub fn as_i128(&self) -> Option<i128> {
self.as_number().and_then(Number::as_i128)
}
#[must_use]
pub fn as_u128(&self) -> Option<u128> {
self.as_number().and_then(Number::as_u128)
}
#[must_use]
pub fn as_f64(&self) -> Option<f64> {
self.as_number().and_then(Number::as_f64)
}
#[inline]
#[must_use]
pub fn as_str(&self) -> Option<&str> {
match self {
Self::String(s) => Some(s),
_ => None,
}
}
#[inline]
#[must_use]
pub const fn as_array(&self) -> Option<&Array<'a>> {
match self {
Self::Array(a) => Some(a),
_ => None,
}
}
#[inline]
#[must_use]
pub fn as_array_mut(&mut self) -> Option<&mut Array<'a>> {
match self {
Self::Array(a) => Some(a),
_ => None,
}
}
#[inline]
#[must_use]
pub const fn as_object(&self) -> Option<&Object<'a>> {
match self {
Self::Object(o) => Some(o),
_ => None,
}
}
#[inline]
#[must_use]
pub fn as_object_mut(&mut self) -> Option<&mut Object<'a>> {
match self {
Self::Object(o) => Some(o),
_ => None,
}
}
#[must_use]
pub fn get(&self, key: &str) -> Option<&Value<'a>> {
self.as_object().and_then(|o| o.get(key))
}
#[must_use]
pub fn get_mut(&mut self, key: &str) -> Option<&mut Value<'a>> {
self.as_object_mut().and_then(|o| o.get_mut(key))
}
#[must_use]
pub fn get_index(&self, index: usize) -> Option<&Value<'a>> {
self.as_array().and_then(|a| a.get(index))
}
#[must_use]
pub fn pointer(&self, pointer: &str) -> Option<&Value<'a>> {
if pointer.is_empty() {
return Some(self);
}
let rest = pointer.strip_prefix('/')?;
let mut target = self;
for token in rest.split('/') {
let token = unescape_pointer_token(token)?;
target = match target {
Self::Object(o) => o.get(&token)?,
Self::Array(a) => a.get(array_index(&token)?)?,
_ => return None,
};
}
Some(target)
}
#[must_use]
pub fn pointer_mut(&mut self, pointer: &str) -> Option<&mut Value<'a>> {
if pointer.is_empty() {
return Some(self);
}
let rest = pointer.strip_prefix('/')?;
let mut target = self;
for token in rest.split('/') {
let token = unescape_pointer_token(token)?;
target = match target {
Self::Object(o) => o.get_mut(&token)?,
Self::Array(a) => a.get_mut(array_index(&token)?)?,
_ => return None,
};
}
Some(target)
}
#[inline]
pub fn take(&mut self) -> Value<'a> {
core::mem::take(self)
}
#[must_use]
pub fn into_owned(self) -> Value<'static> {
tree::into_owned(self)
}
}
pub(crate) fn unescape_pointer_token(token: &str) -> Option<Cow<'_, str>> {
if !token.contains('~') {
return Some(Cow::Borrowed(token));
}
let mut out = String::with_capacity(token.len());
let mut chars = token.chars();
while let Some(c) = chars.next() {
if c == '~' {
match chars.next() {
Some('0') => out.push('~'),
Some('1') => out.push('/'),
_ => return None,
}
} else {
out.push(c);
}
}
Some(Cow::Owned(out))
}
pub(crate) fn array_index(token: &str) -> Option<usize> {
let digits = token.as_bytes();
let canonical = !digits.is_empty()
&& digits.iter().all(u8::is_ascii_digit)
&& (digits.len() == 1 || digits.first() != Some(&b'0'));
if canonical { token.parse().ok() } else { None }
}
impl Clone for Value<'_> {
fn clone(&self) -> Self {
match self {
Self::Null => Self::Null,
Self::Bool(b) => Self::Bool(*b),
Self::Number(n) => Self::Number(n.clone()),
Self::String(s) => Self::String(s.clone()),
Self::Array(a) => Self::Array(a.clone()),
Self::Object(o) => Self::Object(o.clone()),
}
}
}
impl PartialEq for Value<'_> {
fn eq(&self, other: &Self) -> bool {
tree::eq(self, other)
}
}
impl Eq for Value<'_> {}
impl Hash for Value<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
tree::hash(self, state);
}
}
impl<'a> Index<&str> for Value<'a> {
type Output = Value<'a>;
fn index(&self, key: &str) -> &Value<'a> {
self.get(key).unwrap_or(&NULL)
}
}
impl<'a> Index<usize> for Value<'a> {
type Output = Value<'a>;
fn index(&self, index: usize) -> &Value<'a> {
self.get_index(index).unwrap_or(&NULL)
}
}
impl From<bool> for Value<'_> {
#[inline]
fn from(b: bool) -> Self {
Self::Bool(b)
}
}
macro_rules! from_integer {
($($t:ty),*) => {$(
impl From<$t> for Value<'_> {
#[inline]
fn from(n: $t) -> Self {
Self::Number(Number::from(n))
}
}
)*};
}
from_integer!(
i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize
);
impl From<f64> for Value<'_> {
fn from(x: f64) -> Self {
Number::from_f64(x).map_or(Self::Null, Self::Number)
}
}
impl From<f32> for Value<'_> {
fn from(x: f32) -> Self {
Self::from(f64::from(x))
}
}
impl<'a> From<Number<'a>> for Value<'a> {
#[inline]
fn from(n: Number<'a>) -> Self {
Self::Number(n)
}
}
impl<'a> From<&'a str> for Value<'a> {
#[inline]
fn from(s: &'a str) -> Self {
Self::String(Cow::Borrowed(s))
}
}
impl<'a> From<&'a String> for Value<'a> {
#[inline]
fn from(s: &'a String) -> Self {
Self::String(Cow::Borrowed(s))
}
}
impl From<String> for Value<'_> {
#[inline]
fn from(s: String) -> Self {
Self::String(Cow::Owned(s))
}
}
impl<'a> From<Cow<'a, str>> for Value<'a> {
#[inline]
fn from(s: Cow<'a, str>) -> Self {
Self::String(s)
}
}
impl From<char> for Value<'_> {
#[inline]
fn from(c: char) -> Self {
Self::String(Cow::Owned(c.to_string()))
}
}
impl<'a> From<Array<'a>> for Value<'a> {
#[inline]
fn from(a: Array<'a>) -> Self {
Self::Array(a)
}
}
impl<'a> From<Object<'a>> for Value<'a> {
#[inline]
fn from(o: Object<'a>) -> Self {
Self::Object(o)
}
}
impl<'a, T: Into<Value<'a>>> From<Vec<T>> for Value<'a> {
fn from(items: Vec<T>) -> Self {
Self::Array(items.into_iter().collect())
}
}
impl<'a, T: Into<Value<'a>>> From<Option<T>> for Value<'a> {
fn from(value: Option<T>) -> Self {
value.map_or(Self::Null, Into::into)
}
}
impl From<()> for Value<'_> {
#[inline]
fn from((): ()) -> Self {
Self::Null
}
}
impl<'a, T: Into<Value<'a>>> FromIterator<T> for Value<'a> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
Self::Array(iter.into_iter().collect())
}
}
impl PartialEq<str> for Value<'_> {
fn eq(&self, other: &str) -> bool {
self.as_str() == Some(other)
}
}
impl PartialEq<&str> for Value<'_> {
fn eq(&self, other: &&str) -> bool {
self.as_str() == Some(*other)
}
}
impl PartialEq<String> for Value<'_> {
fn eq(&self, other: &String) -> bool {
self.as_str() == Some(other.as_str())
}
}
impl PartialEq<bool> for Value<'_> {
fn eq(&self, other: &bool) -> bool {
self.as_bool() == Some(*other)
}
}
impl PartialEq<f32> for Value<'_> {
fn eq(&self, other: &f32) -> bool {
self.as_number().and_then(Number::as_f32) == Some(*other)
}
}
impl PartialEq<i128> for Value<'_> {
fn eq(&self, other: &i128) -> bool {
self.as_i128() == Some(*other)
}
}
impl PartialEq<u128> for Value<'_> {
fn eq(&self, other: &u128) -> bool {
self.as_u128() == Some(*other)
}
}
impl PartialEq<f64> for Value<'_> {
fn eq(&self, other: &f64) -> bool {
self.as_f64() == Some(*other)
}
}
macro_rules! eq_signed {
($($t:ty),*) => {$(
impl PartialEq<$t> for Value<'_> {
fn eq(&self, other: &$t) -> bool {
self.as_i64() == Some(i64::from(*other))
}
}
)*};
}
macro_rules! eq_unsigned {
($($t:ty),*) => {$(
impl PartialEq<$t> for Value<'_> {
fn eq(&self, other: &$t) -> bool {
self.as_u64() == Some(u64::from(*other))
}
}
)*};
}
eq_signed!(i8, i16, i32, i64);
eq_unsigned!(u8, u16, u32, u64);
impl PartialEq<isize> for Value<'_> {
fn eq(&self, other: &isize) -> bool {
i64::try_from(*other).is_ok_and(|n| self.as_i64() == Some(n))
}
}
impl PartialEq<usize> for Value<'_> {
fn eq(&self, other: &usize) -> bool {
u64::try_from(*other).is_ok_and(|n| self.as_u64() == Some(n))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_value_is_four_words() {
assert!(core::mem::size_of::<Value<'_>>() <= 4 * core::mem::size_of::<usize>());
}
#[test]
fn test_pointer_tokens() {
assert_eq!(array_index("0"), Some(0));
assert_eq!(array_index("10"), Some(10));
assert_eq!(array_index("01"), None);
assert_eq!(array_index("-"), None);
assert_eq!(array_index(""), None);
assert_eq!(array_index("+1"), None);
assert_eq!(unescape_pointer_token("a~1b~0c").as_deref(), Some("a/b~c"));
assert_eq!(unescape_pointer_token("~2"), None);
assert_eq!(unescape_pointer_token("~"), None);
}
#[test]
fn test_predicates_wide_integers_and_comparisons() {
let v = crate::json!([null, true, 1, "s", [], {}]);
let kinds: alloc::vec::Vec<[bool; 5]> = v
.as_array()
.map(|a| {
a.iter()
.map(|x| {
[
x.is_bool(),
x.is_number(),
x.is_string(),
x.is_array(),
x.is_object(),
]
})
.collect()
})
.unwrap_or_default();
assert_eq!(kinds.iter().filter(|k| k.iter().any(|&b| b)).count(), 5);
assert!(v[0].is_null() && !v[1].is_null());
assert_eq!(Value::from(u128::MAX), u128::MAX);
assert_eq!(Value::from(i128::MIN), i128::MIN);
assert_ne!(Value::from(1), 2i128);
assert_eq!(Value::from(0.5), 0.5f32);
assert_ne!(Value::from("0.5"), 0.5f32);
assert_eq!(Value::from(-1).as_u128(), None);
}
struct Fnv(u64);
impl Hasher for Fnv {
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, bytes: &[u8]) {
for &b in bytes {
self.0 = (self.0 ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);
}
}
}
#[test]
fn test_hash_agrees_with_eq() {
let h = |v: &Value<'_>| {
let mut state = Fnv(0xcbf2_9ce4_8422_2325);
v.hash(&mut state);
state.finish()
};
let a = crate::json!({ "k": [1, { "x": "y" }], "m": null });
let b = crate::parse(r#"{"k":[1,{"x":"y"}],"m":null}"#).unwrap_or_default();
assert_eq!(a, b);
assert_eq!(h(&a), h(&b));
let reordered = crate::parse(r#"{"m":null,"k":[1,{"x":"y"}]}"#).unwrap_or_default();
assert_ne!(h(&a), h(&reordered));
assert_ne!(
h(&Value::from(1)),
h(&crate::parse("1.0").unwrap_or_default())
);
assert_ne!(h(&crate::json!([[]])), h(&crate::json!([[], []])));
assert_ne!(h(&crate::json!(["a"])), h(&crate::json!({ "a": null })));
}
#[test]
fn test_index_out_of_shape_is_null() {
let v = Value::from(3);
assert!(v["k"].is_null());
assert!(v[0].is_null());
}
}