use ::serde_json::Number;
use std::fmt::{Debug, Display};
#[cfg(feature = "jsonbb")]
mod jsonbb;
mod serde_json;
#[cfg(feature = "simd-json")]
mod simd_json;
#[derive(Debug)]
pub enum Cow<'a, T: Json + 'a> {
Borrowed(T::Borrowed<'a>),
Owned(T),
}
impl<'a, T: Json> Cow<'a, T> {
pub fn as_ref<'b>(&'b self) -> T::Borrowed<'b>
where
'a: 'b,
{
match self {
Cow::Borrowed(v) => T::borrow(*v),
Cow::Owned(v) => v.as_ref(),
}
}
pub fn into_owned(self) -> T {
match self {
Cow::Borrowed(v) => v.to_owned(),
Cow::Owned(v) => v,
}
}
}
impl<T: Json> Display for Cow<'_, T>
where
for<'a> T::Borrowed<'a>: Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.as_ref(), f)
}
}
pub trait Json: Clone + Debug {
type Borrowed<'a>: JsonRef<'a, Owned = Self>
where
Self: 'a;
fn as_ref(&self) -> Self::Borrowed<'_>;
fn null() -> Self;
fn bool(b: bool) -> Self;
fn from_u64(v: u64) -> Self;
fn from_i64(v: i64) -> Self;
fn from_f64(v: f64) -> Self;
fn from_number(n: Number) -> Self;
fn from_string(s: &str) -> Self;
fn object<'a, I: IntoIterator<Item = (&'a str, Self)>>(i: I) -> Self;
fn borrow<'b, 'a: 'b>(p: Self::Borrowed<'a>) -> Self::Borrowed<'b> {
unsafe { std::mem::transmute(p) }
}
}
pub trait JsonRef<'a>: Copy + Debug {
type Owned: Json<Borrowed<'a> = Self> + 'a;
type Array: ArrayRef<'a, JsonRef = Self>;
type Object: ObjectRef<'a, JsonRef = Self>;
fn to_owned(self) -> Self::Owned;
fn null() -> Self;
fn as_bool(self) -> Option<bool>;
fn as_number(self) -> Option<Number>;
fn as_str(self) -> Option<&'a str>;
fn as_array(self) -> Option<Self::Array>;
fn as_object(self) -> Option<Self::Object>;
fn is_null(self) -> bool;
fn is_bool(self) -> bool {
self.as_bool().is_some()
}
fn is_number(self) -> bool {
self.as_number().is_some()
}
fn is_string(self) -> bool {
self.as_str().is_some()
}
fn is_array(self) -> bool {
self.as_array().is_some()
}
fn is_object(self) -> bool {
self.as_object().is_some()
}
}
pub trait ArrayRef<'a>: Copy {
type JsonRef: JsonRef<'a>;
fn len(self) -> usize;
fn get(self, index: usize) -> Option<Self::JsonRef>;
fn list(self) -> Vec<Self::JsonRef>;
fn is_empty(self) -> bool {
self.len() == 0
}
}
pub trait ObjectRef<'a>: Copy {
type JsonRef: JsonRef<'a>;
fn len(self) -> usize;
fn get(self, key: &str) -> Option<Self::JsonRef>;
fn list(self) -> Vec<(&'a str, Self::JsonRef)>;
fn list_value(self) -> Vec<Self::JsonRef>;
fn is_empty(self) -> bool {
self.len() == 0
}
}