use alloc::{borrow::Cow, string::String};
use core::fmt;
use crate::{
DecodeError, DuplicateKeys, Error, FromJson, Limits, Parser, Reader, ToJson, Value,
ValueWriter, Written, decode::DecodeErrorKind, error::ErrorKind,
};
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct RawValue<'a>(Cow<'a, str>);
impl<'a> RawValue<'a> {
pub fn new(text: &'a str) -> Result<Self, Error> {
let mut reader = Reader::new(text);
match reader.read_raw_value()? {
Some(raw) => {
reader.read_to_end()?;
Ok(raw)
}
None => Err(Error::new(ErrorKind::UnexpectedEnd, text.len())),
}
}
pub fn from_string(text: String) -> Result<RawValue<'static>, Error> {
let len = RawValue::new(&text)?.as_str().len();
Ok(if len == text.len() {
RawValue(Cow::Owned(text))
} else {
RawValue::new(&text)?.into_owned()
})
}
#[must_use]
pub fn encode<T: ToJson + ?Sized>(value: &T) -> RawValue<'static> {
RawValue(Cow::Owned(crate::to_string(value)))
}
#[inline]
pub(crate) const fn trusted(text: &'a str) -> Self {
Self(Cow::Borrowed(text))
}
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_owned(self) -> RawValue<'static> {
RawValue(Cow::Owned(self.0.into_owned()))
}
pub fn parse(&self) -> Result<Value<'_>, Error> {
Parser::new()
.limits(Limits::unlimited())
.duplicate_keys(DuplicateKeys::KeepAll)
.parse(&self.0)
}
pub fn decode<'s, T: FromJson<'s>>(&'s self) -> Result<T, DecodeError> {
Parser::new()
.limits(Limits::new().with_max_input_bytes(usize::MAX))
.decode(&self.0)
}
}
impl fmt::Display for RawValue<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl fmt::Debug for RawValue<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl<'de> FromJson<'de> for RawValue<'de> {
fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
match reader.read_raw_value()? {
Some(raw) => Ok(raw),
None => Err(DecodeError::new(
DecodeErrorKind::Syntax(ErrorKind::ExpectedValue),
reader.offset(),
)),
}
}
}
impl ToJson for RawValue<'_> {
#[inline]
fn to_json(&self, out: ValueWriter<'_>) -> Written {
out.raw(self)
}
}