Skip to main content

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