use alloc::{borrow::Cow, string::String};
use core::fmt;
use jsonx_lib::{Kind, Parser, Value};
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Raw<'a>(Cow<'a, str>);
impl<'a> Raw<'a> {
pub const NULL: Raw<'static> = Raw(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.reader(text);
match reader.read_raw()? {
Some(value) => {
reader.finish()?;
Ok(Raw(Cow::Borrowed(value)))
}
None => parser.parse(text).map(|_| Raw(Cow::Borrowed(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(Cow::Owned(text)))
} else {
Ok(value.into_owned())
}
}
#[must_use]
pub fn from_value(value: &Value<'_>) -> Raw<'static> {
Raw(Cow::Owned(jsonx_lib::to_string(value)))
}
#[inline]
pub(crate) const fn trusted(text: &'a str) -> Self {
Raw(Cow::Borrowed(text))
}
#[inline]
pub(crate) const fn trusted_owned(text: String) -> Raw<'static> {
Raw(Cow::Owned(text))
}
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[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(Cow::Owned(self.0.into_owned()))
}
#[inline]
pub(crate) fn reborrow(&self) -> Raw<'_> {
Raw(Cow::Borrowed(&self.0))
}
}
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::trusted_owned(jsonx_lib::to_string(&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}");
}
}
}