jsonx_lib/raw.rs
1//! [`RawValue`]: one JSON value kept as its validated text.
2
3use alloc::{borrow::Cow, string::String};
4use core::fmt;
5
6use crate::{
7 DecodeError, DuplicateKeys, Error, FromJson, Limits, Parser, Reader, ToJson, Value,
8 ValueWriter, Written, decode::DecodeErrorKind, error::ErrorKind,
9};
10
11/// One complete JSON value kept as its exact source text: validated once,
12/// then stored, compared, forwarded, or read later.
13///
14/// This is `serde_json`'s `RawValue`. A JSON-RPC server keeps `params` as a
15/// `RawValue` until the handler for the method knows what type to read it
16/// as; a proxy forwards a `result` without decoding it.
17///
18/// A `RawValue` always holds exactly one value with no whitespace around
19/// it. Every way of making one validates, or takes text this crate has
20/// just validated or written: [`new`](Self::new) and
21/// [`from_string`](Self::from_string) check the text,
22/// [`Reader::read_raw_value`] and `FromJson` take it from a read that
23/// checked it, and [`encode`](Self::encode) takes it from this crate's
24/// writer. So writing one ([`ToJson`]) copies the text with no second
25/// check, and the output stays valid JSON. Under
26/// [`Format::html_safe`](crate::Format::html_safe) or
27/// [`Format::ascii`](crate::Format::ascii) the characters those formats
28/// escape are escaped inside the text's strings as well (see
29/// [`ValueWriter::raw`](crate::ValueWriter::raw)); otherwise the text is
30/// copied unchanged.
31///
32/// Valid means grammatical JSON. A `RawValue` taken under
33/// [`DuplicateKeys::KeepAll`](crate::DuplicateKeys::KeepAll), or made by
34/// [`encode`](Self::encode) from a `ToJson` that writes a key twice, can
35/// hold an object with a repeated key: [`decode`](Self::decode) (default
36/// policy) refuses that text, [`parse`](Self::parse) keeps every member.
37///
38/// # Examples
39///
40/// ```
41/// use jsonx_lib::{DecodeError, FromJson, RawValue, Reader};
42///
43/// struct Request<'a> { method: &'a str, params: RawValue<'a> }
44///
45/// impl<'de> FromJson<'de> for Request<'de> {
46/// fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
47/// let (mut method, mut params) = (None, None);
48/// let mut o = reader.read_object()?;
49/// while let Some(key) = o.next_key()? {
50/// match &*key {
51/// "method" => o.field(&mut method)?,
52/// "params" => o.field(&mut params)?,
53/// _ => {}
54/// }
55/// }
56/// Ok(Request { method: o.required(method, "method")?, params: o.required(params, "params")? })
57/// }
58/// }
59///
60/// let req: Request = jsonx_lib::from_str(r#"{"method": "add", "params": [2, 3]}"#)?;
61/// assert_eq!(req.params.as_str(), "[2, 3]"); // not decoded yet
62/// let (a, b): (i32, i32) = req.params.decode()?; // now, once the method is known
63/// assert_eq!(a + b, 5);
64/// # Ok::<(), DecodeError>(())
65/// ```
66#[derive(Clone, PartialEq, Eq, Hash)]
67pub struct RawValue<'a>(Cow<'a, str>);
68
69impl<'a> RawValue<'a> {
70 /// Validates `text` as one JSON value under the default [`Limits`] and
71 /// keeps it, minus surrounding whitespace, as a borrowed slice.
72 ///
73 /// # Errors
74 ///
75 /// The parse error of text that is not exactly one JSON value.
76 ///
77 /// # Examples
78 ///
79 /// ```
80 /// use jsonx_lib::RawValue;
81 ///
82 /// assert_eq!(RawValue::new(" {\"a\": 1} ")?.as_str(), "{\"a\": 1}");
83 /// assert!(RawValue::new("[1,").is_err());
84 /// assert!(RawValue::new("1 2").is_err());
85 /// # Ok::<(), jsonx_lib::Error>(())
86 /// ```
87 pub fn new(text: &'a str) -> Result<Self, Error> {
88 let mut reader = Reader::new(text);
89 match reader.read_raw_value()? {
90 Some(raw) => {
91 reader.read_to_end()?;
92 Ok(raw)
93 }
94 // `read_raw` sees no value only in input that holds none.
95 None => Err(Error::new(ErrorKind::UnexpectedEnd, text.len())),
96 }
97 }
98
99 /// Validates an owned string, as [`new`](Self::new), keeping its buffer
100 /// when it has no surrounding whitespace.
101 ///
102 /// # Errors
103 ///
104 /// As [`new`](Self::new).
105 ///
106 /// # Examples
107 ///
108 /// ```
109 /// let raw = jsonx_lib::RawValue::from_string(String::from("[true]"))?;
110 /// assert_eq!(raw.as_str(), "[true]");
111 /// # Ok::<(), jsonx_lib::Error>(())
112 /// ```
113 pub fn from_string(text: String) -> Result<RawValue<'static>, Error> {
114 let len = RawValue::new(&text)?.as_str().len();
115 Ok(if len == text.len() {
116 RawValue(Cow::Owned(text))
117 } else {
118 RawValue::new(&text)?.into_owned()
119 })
120 }
121
122 /// Writes `value` as compact JSON and keeps the text.
123 ///
124 /// # Examples
125 ///
126 /// ```
127 /// let raw = jsonx_lib::RawValue::encode(&[1, 2]);
128 /// assert_eq!(raw.as_str(), "[1,2]");
129 /// ```
130 #[must_use]
131 pub fn encode<T: ToJson + ?Sized>(value: &T) -> RawValue<'static> {
132 RawValue(Cow::Owned(crate::to_string(value)))
133 }
134
135 /// Wraps text this crate has just validated as one value.
136 #[inline]
137 pub(crate) const fn trusted(text: &'a str) -> Self {
138 Self(Cow::Borrowed(text))
139 }
140
141 /// The JSON text.
142 ///
143 /// # Examples
144 ///
145 /// ```
146 /// assert_eq!(jsonx_lib::RawValue::new("null")?.as_str(), "null");
147 /// # Ok::<(), jsonx_lib::Error>(())
148 /// ```
149 #[inline]
150 #[must_use]
151 pub fn as_str(&self) -> &str {
152 &self.0
153 }
154
155 /// Copies borrowed text so the value no longer borrows from the input.
156 ///
157 /// # Examples
158 ///
159 /// ```
160 /// let owned = jsonx_lib::RawValue::new(&String::from("1"))?.into_owned();
161 /// assert_eq!(owned.as_str(), "1");
162 /// # Ok::<(), jsonx_lib::Error>(())
163 /// ```
164 #[must_use]
165 pub fn into_owned(self) -> RawValue<'static> {
166 RawValue(Cow::Owned(self.0.into_owned()))
167 }
168
169 /// Parses the text into a [`Value`]. The text was validated when the
170 /// `RawValue` was made, so no budget applies, and every member is kept
171 /// as written.
172 ///
173 /// # Errors
174 ///
175 /// None in practice: the text is valid JSON.
176 ///
177 /// # Examples
178 ///
179 /// ```
180 /// let raw = jsonx_lib::RawValue::new(r#"{"line": 3}"#)?;
181 /// assert_eq!(raw.parse()?["line"], 3);
182 /// # Ok::<(), jsonx_lib::Error>(())
183 /// ```
184 pub fn parse(&self) -> Result<Value<'_>, Error> {
185 Parser::new()
186 .limits(Limits::unlimited())
187 .duplicate_keys(DuplicateKeys::KeepAll)
188 .parse(&self.0)
189 }
190
191 /// Reads the text as a `T` ([`FromJson`]), with the default [`Limits`]
192 /// (which bound a recursive type's depth) and duplicate keys refused.
193 ///
194 /// # Errors
195 ///
196 /// The [`DecodeError`] of `T`; offsets count from the start of the raw
197 /// text.
198 ///
199 /// # Examples
200 ///
201 /// ```
202 /// let raw = jsonx_lib::RawValue::new("[1, 2, 3]")?;
203 /// assert_eq!(raw.decode::<Vec<u8>>()?, [1, 2, 3]);
204 /// # Ok::<(), jsonx_lib::DecodeError>(())
205 /// ```
206 pub fn decode<'s, T: FromJson<'s>>(&'s self) -> Result<T, DecodeError> {
207 Parser::new()
208 .limits(Limits::new().with_max_input_bytes(usize::MAX))
209 .decode(&self.0)
210 }
211}
212
213impl fmt::Display for RawValue<'_> {
214 /// Writes the JSON text.
215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216 f.write_str(&self.0)
217 }
218}
219
220impl fmt::Debug for RawValue<'_> {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222 f.write_str(&self.0)
223 }
224}
225
226impl<'de> FromJson<'de> for RawValue<'de> {
227 fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
228 match reader.read_raw_value()? {
229 Some(raw) => Ok(raw),
230 None => Err(DecodeError::new(
231 DecodeErrorKind::Syntax(ErrorKind::ExpectedValue),
232 reader.offset(),
233 )),
234 }
235 }
236}
237
238impl ToJson for RawValue<'_> {
239 #[inline]
240 fn to_json(&self, out: ValueWriter<'_>) -> Written {
241 out.raw(self)
242 }
243}