use alloc::{borrow::Cow, string::String};
use core::{
fmt,
hash::{Hash, Hasher},
};
use jsonx_lib::{DuplicateKeys, Kind, Parser, RawValue, Value};
#[derive(Clone)]
pub struct Raw<'a>(Repr<'a>);
#[derive(Clone)]
enum Repr<'a> {
Checked(RawValue<'a>),
Text(Cow<'a, str>),
}
impl<'a> Raw<'a> {
pub const NULL: Raw<'static> = Raw(Repr::Text(Cow::Borrowed("null")));
pub fn new(text: &'a str) -> Result<Self, jsonx_lib::Error> {
Self::new_with(text, &Parser::new())
}
pub fn new_with(text: &'a str, parser: &Parser) -> Result<Self, jsonx_lib::Error> {
let mut reader = parser.duplicate_keys(DuplicateKeys::KeepAll).reader(text);
match reader.read_raw_value()? {
Some(value) => {
reader.finish()?;
Ok(Raw(Repr::Checked(value)))
}
None => parser.parse(text).map(|_| Raw::trusted(text.trim())),
}
}
pub fn from_string(text: String) -> Result<Raw<'static>, jsonx_lib::Error> {
let value = Raw::new(&text)?;
if value.as_str().len() == text.len() {
Ok(Raw::trusted_owned(text))
} else {
Ok(value.into_owned())
}
}
#[must_use]
pub fn from_value(value: &Value<'_>) -> Raw<'static> {
Raw(Repr::Checked(RawValue::encode(value)))
}
#[inline]
pub(crate) const fn trusted(text: &'a str) -> Self {
Raw(Repr::Text(Cow::Borrowed(text)))
}
#[inline]
pub(crate) const fn trusted_owned(text: String) -> Raw<'static> {
Raw(Repr::Text(Cow::Owned(text)))
}
#[inline]
pub(crate) const fn checked(value: RawValue<'a>) -> Self {
Raw(Repr::Checked(value))
}
#[inline]
pub(crate) fn raw_value(&self) -> Option<&RawValue<'a>> {
match &self.0 {
Repr::Checked(value) => Some(value),
Repr::Text(_) => None,
}
}
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
match &self.0 {
Repr::Checked(value) => value.as_str(),
Repr::Text(text) => text,
}
}
#[must_use]
pub fn kind(&self) -> Kind {
kind_of(self.as_str())
}
pub fn parse(&self) -> Result<Value<'_>, jsonx_lib::Error> {
self.parse_with(&Parser::new())
}
pub fn parse_with(&self, parser: &Parser) -> Result<Value<'_>, jsonx_lib::Error> {
parser.parse(self.as_str())
}
#[must_use]
pub fn into_owned(self) -> Raw<'static> {
Raw(match self.0 {
Repr::Checked(value) => Repr::Checked(value.into_owned()),
Repr::Text(text) => Repr::Text(Cow::Owned(text.into_owned())),
})
}
#[inline]
pub(crate) fn reborrow(&self) -> Raw<'_> {
Raw::trusted(self.as_str())
}
}
impl PartialEq for Raw<'_> {
fn eq(&self, other: &Self) -> bool {
self.as_str() == other.as_str()
}
}
impl Eq for Raw<'_> {}
impl Hash for Raw<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_str().hash(state);
}
}
pub(crate) fn kind_of(text: &str) -> Kind {
match text.as_bytes().first() {
Some(b'{') => Kind::Object,
Some(b'[') => Kind::Array,
Some(b'"') => Kind::String,
Some(b't' | b'f') => Kind::Bool,
Some(b'n') => Kind::Null,
_ => Kind::Number,
}
}
impl fmt::Display for Raw<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl fmt::Debug for Raw<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, PartialEq)]
pub enum Json<'a> {
Value(Value<'a>),
Raw(Raw<'a>),
}
impl Json<'_> {
#[must_use]
pub fn kind(&self) -> Kind {
match self {
Json::Value(value) => value.kind(),
Json::Raw(raw) => raw.kind(),
}
}
#[must_use]
pub fn into_owned(self) -> Json<'static> {
match self {
Json::Value(value) => Json::Value(value.into_owned()),
Json::Raw(raw) => Json::Raw(raw.into_owned()),
}
}
pub(crate) fn write(&self, out: &mut String) {
match self {
Json::Value(value) => jsonx_lib::write_value(out, value),
Json::Raw(raw) => out.push_str(raw.as_str()),
}
}
pub(crate) fn into_raw(self) -> Raw<'static> {
match self {
Json::Value(value) => Raw::checked(RawValue::encode(&value)),
Json::Raw(raw) => raw.into_owned(),
}
}
}
impl<'a, T: Into<Value<'a>>> From<T> for Json<'a> {
#[inline]
fn from(value: T) -> Self {
Json::Value(value.into())
}
}
impl<'a> From<Raw<'a>> for Json<'a> {
#[inline]
fn from(raw: Raw<'a>) -> Self {
Json::Raw(raw)
}
}
impl fmt::Display for Json<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Json::Value(value) => fmt::Display::fmt(value, f),
Json::Raw(raw) => f.write_str(raw.as_str()),
}
}
}
impl fmt::Debug for Json<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
#[cfg(test)]
#[allow(clippy::panic)]
mod tests {
use super::*;
#[test]
fn test_new_trims_and_validates() {
assert_eq!(Raw::new("\t null \n").map(|r| r.kind()), Ok(Kind::Null));
assert!(Raw::new("").is_err());
assert!(Raw::new(" ").is_err());
assert!(Raw::new("1 2").is_err());
assert!(Raw::new("[1,]").is_err());
}
#[test]
fn test_from_string_keeps_or_trims() {
let kept = Raw::from_string(String::from("[1]"));
assert_eq!(kept.as_ref().map(Raw::as_str), Ok("[1]"));
let trimmed = Raw::from_string(String::from(" [1] "));
assert_eq!(trimmed.as_ref().map(Raw::as_str), Ok("[1]"));
}
#[test]
fn test_kind_of_every_kind() {
for (text, kind) in [
("{}", Kind::Object),
("[]", Kind::Array),
("\"\"", Kind::String),
("true", Kind::Bool),
("false", Kind::Bool),
("null", Kind::Null),
("-0", Kind::Number),
] {
assert_eq!(kind_of(text), kind, "{text}");
}
}
}