Skip to main content

ntex/http/
json.rs

1//! JSON encoding and decoding backend.
2//!
3//! JSON bodies are encoded and decoded with `sonic-rs`, or with `serde_json`
4//! when the `serde` feature is enabled.
5use std::{error, fmt};
6
7use serde::{Serialize, de::DeserializeOwned};
8
9#[cfg(not(feature = "serde"))]
10use ntex_bytes::SpareWriter;
11
12use crate::util::{Bytes, BytesMut};
13
14/// An error that occurred while encoding or decoding a JSON body.
15///
16/// JSON bodies are encoded and decoded with `sonic-rs`, or with `serde_json`
17/// when the `serde` feature is enabled. Errors of both crates convert into
18/// `JsonError`.
19///
20/// The `Display` text is a single line. It does not include the input
21/// fragment that `sonic-rs` appends to syntax errors.
22pub struct JsonError(Inner);
23
24enum Inner {
25    Serde(serde_json::Error),
26    Sonic(sonic_rs::Error),
27}
28
29impl JsonError {
30    /// Returns the one-based line of the input at which the error occurred.
31    ///
32    /// Returns `0` if the error has no input position, for example an
33    /// encoding error.
34    pub fn line(&self) -> usize {
35        match &self.0 {
36            Inner::Serde(err) => err.line(),
37            Inner::Sonic(err) => err.line(),
38        }
39    }
40
41    /// Returns the one-based column of the input at which the error occurred.
42    ///
43    /// Returns `0` if the error has no input position, for example an
44    /// encoding error.
45    pub fn column(&self) -> usize {
46        match &self.0 {
47            Inner::Serde(err) => err.column(),
48            Inner::Sonic(err) => err.column(),
49        }
50    }
51
52    /// Returns `true` if the error was caused by a failure to read or write
53    /// bytes on an I/O stream.
54    pub fn is_io(&self) -> bool {
55        match &self.0 {
56            Inner::Serde(err) => err.is_io(),
57            Inner::Sonic(err) => err.is_io(),
58        }
59    }
60
61    /// Returns `true` if the input is not syntactically valid JSON.
62    pub fn is_syntax(&self) -> bool {
63        match &self.0 {
64            Inner::Serde(err) => err.is_syntax(),
65            Inner::Sonic(err) => err.is_syntax(),
66        }
67    }
68
69    /// Returns `true` if the input is valid JSON but does not match the
70    /// expected type, for example a missing field or a value of another type.
71    pub fn is_data(&self) -> bool {
72        match &self.0 {
73            Inner::Serde(err) => err.is_data(),
74            Inner::Sonic(err) => err.is_unmatched_type() || err.is_not_found(),
75        }
76    }
77
78    /// Returns `true` if the input ended before the JSON value was complete.
79    pub fn is_eof(&self) -> bool {
80        match &self.0 {
81            Inner::Serde(err) => err.is_eof(),
82            Inner::Sonic(err) => err.is_eof(),
83        }
84    }
85}
86
87impl From<serde_json::Error> for JsonError {
88    fn from(err: serde_json::Error) -> Self {
89        JsonError(Inner::Serde(err))
90    }
91}
92
93impl From<sonic_rs::Error> for JsonError {
94    fn from(err: sonic_rs::Error) -> Self {
95        JsonError(Inner::Sonic(err))
96    }
97}
98
99impl fmt::Display for JsonError {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        match &self.0 {
102            Inner::Serde(err) => fmt::Display::fmt(err, f),
103            Inner::Sonic(err) => {
104                // sonic-rs appends the input fragment on the following lines
105                let msg = err.to_string();
106                f.write_str(msg.split('\n').next().unwrap_or_default())
107            }
108        }
109    }
110}
111
112impl fmt::Debug for JsonError {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        f.debug_tuple("JsonError")
115            .field(&format_args!("{self}"))
116            .finish()
117    }
118}
119
120impl error::Error for JsonError {
121    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
122        match &self.0 {
123            Inner::Serde(err) => err.source(),
124            Inner::Sonic(err) => err.source(),
125        }
126    }
127}
128
129/// Deserializes a `T` from a JSON body.
130pub(crate) fn from_slice<T: DeserializeOwned>(body: &[u8]) -> Result<T, JsonError> {
131    #[cfg(feature = "serde")]
132    {
133        Ok(serde_json::from_slice(body)?)
134    }
135    #[cfg(not(feature = "serde"))]
136    {
137        Ok(sonic_rs::from_slice(body)?)
138    }
139}
140
141/// Initial buffer capacity of an encoded JSON body.
142const INITIAL_CAPACITY: usize = 256;
143
144/// Serializes `value` as a JSON body.
145pub(crate) fn to_bytes<T: ?Sized + Serialize>(value: &T) -> Result<Bytes, JsonError> {
146    let mut buf = BytesMut::with_capacity(INITIAL_CAPACITY);
147    // The serializer issues many small writes, `SpareWriter` keeps the write
148    // position local instead of updating the buffer header on every write.
149    #[cfg(feature = "serde")]
150    serde_json::to_writer(buf.spare_writer(0), value)?;
151    #[cfg(not(feature = "serde"))]
152    sonic_rs::to_writer(SonicWriter(buf.spare_writer(0)), value)?;
153    Ok(buf.freeze())
154}
155
156/// Lets `sonic-rs` encode strings directly into the spare capacity of a
157/// `BytesMut`.
158#[cfg(not(feature = "serde"))]
159struct SonicWriter<'a>(SpareWriter<'a>);
160
161#[cfg(not(feature = "serde"))]
162#[allow(clippy::inline_always)]
163impl std::io::Write for SonicWriter<'_> {
164    #[inline(always)]
165    fn write(&mut self, src: &[u8]) -> std::io::Result<usize> {
166        self.0.extend_from_slice(src);
167        Ok(src.len())
168    }
169
170    #[inline]
171    fn flush(&mut self) -> std::io::Result<()> {
172        Ok(())
173    }
174}
175
176#[cfg(not(feature = "serde"))]
177#[allow(clippy::inline_always)]
178impl sonic_rs::writer::WriteExt for SonicWriter<'_> {
179    #[inline(always)]
180    fn reserve_with(
181        &mut self,
182        additional: usize,
183    ) -> std::io::Result<&mut [std::mem::MaybeUninit<u8>]> {
184        self.0.reserve(additional);
185        Ok(&mut self.0.spare_capacity_mut()[..additional])
186    }
187
188    #[inline(always)]
189    unsafe fn flush_len(&mut self, additional: usize) -> std::io::Result<()> {
190        // SAFETY: The caller initialized `additional` bytes of the slice
191        // returned by `reserve_with`, which starts at the spare capacity.
192        unsafe { self.0.advance(additional) };
193        Ok(())
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use std::collections::{BTreeMap, HashMap};
200
201    use super::*;
202
203    #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
204    struct Item {
205        name: String,
206        value: f64,
207        tags: Vec<String>,
208        extra: Option<BTreeMap<String, i64>>,
209    }
210
211    /// STATEMENT: The JSON body encoder produces the same bytes as `serde_json::to_string`.
212    ///
213    /// HOW:
214    /// - Encode collections, a map, escaped and unicode strings, floats, non-finite floats,
215    ///   and an empty string, and compare each body with the `serde_json` output.
216    /// - Assert a small body is stored inline.
217    #[test]
218    fn to_bytes_matches_serde_json() {
219        fn check<T: ?Sized + Serialize>(value: &T) {
220            assert_eq!(
221                to_bytes(value).unwrap(),
222                serde_json::to_string(value).unwrap()
223            );
224        }
225
226        let small = vec![1, 2, 3];
227        let large: Vec<String> = (0..1000).map(|i| format!("item-{i}")).collect();
228        let map: BTreeMap<_, _> = (0..50).map(|i| (i.to_string(), i)).collect();
229        let item = Item {
230            name: "quote \" backslash \\ ctrl \u{1} tab \t nl \n é 😀 </script>".to_string(),
231            value: 0.1 + 0.2,
232            tags: vec![String::new(), "a".repeat(100)],
233            extra: Some([("k".to_string(), -1), ("m".to_string(), i64::MAX)].into()),
234        };
235        let floats = [
236            0.0,
237            -0.0,
238            1.5,
239            1e300,
240            1e-300,
241            123_456_789.012_345_68,
242            f64::MIN,
243        ];
244        check(&small);
245        check(&large);
246        check(&map);
247        check(&item);
248        check(&floats);
249        check(&[f64::NAN, f64::INFINITY]);
250        check(&(u64::MAX, i64::MIN, true, (), None::<u8>));
251        check("");
252
253        assert!(to_bytes(&small).unwrap().is_inline());
254    }
255
256    /// STATEMENT: The JSON body encoder reports values that cannot be encoded.
257    ///
258    /// HOW:
259    /// - Encode a map with a sequence key and assert an error with no input position.
260    #[test]
261    fn to_bytes_error() {
262        let mut map = HashMap::new();
263        map.insert(vec![1u8], 1);
264        let err = to_bytes(&map).unwrap_err();
265        assert_eq!(err.line(), 0);
266        assert!(!err.is_io());
267    }
268
269    /// STATEMENT: The JSON body decoder parses the same values as `serde_json` and rejects
270    /// trailing data.
271    ///
272    /// HOW:
273    /// - Decode a struct and a `serde_json::Value` from the encoded body and compare them.
274    /// - Assert trailing characters after the value are rejected and trailing whitespace is not.
275    #[test]
276    fn from_slice_roundtrip() {
277        let item = Item {
278            name: "é \" 😀".to_string(),
279            value: -2.5,
280            tags: vec!["x".to_string()],
281            extra: None,
282        };
283        let body = to_bytes(&item).unwrap();
284        assert_eq!(from_slice::<Item>(&body).unwrap(), item);
285        assert_eq!(
286            from_slice::<serde_json::Value>(&body).unwrap(),
287            serde_json::from_slice::<serde_json::Value>(&body).unwrap()
288        );
289
290        assert!(from_slice::<serde_json::Value>(b"{\"a\":1} \n").is_ok());
291        assert!(from_slice::<serde_json::Value>(b"{\"a\":1} x").is_err());
292    }
293
294    /// STATEMENT: The JSON body decoder rejects invalid input without panicking.
295    ///
296    /// HOW:
297    /// - Decode invalid UTF-8 in a string, a truncated object, and a too deeply nested array,
298    ///   and assert each fails with the expected classification.
299    /// - Decode a value of the wrong type and a missing field and assert data errors.
300    #[test]
301    fn from_slice_errors() {
302        let err = from_slice::<String>(b"\"\xff\xfe\"").unwrap_err();
303        assert!(!err.is_data());
304
305        let err = from_slice::<serde_json::Value>(b"{\"a\":").unwrap_err();
306        assert!(err.is_eof());
307
308        let nested = format!("{}{}", "[".repeat(100_000), "]".repeat(100_000));
309        let err = from_slice::<serde_json::Value>(nested.as_bytes()).unwrap_err();
310        assert!(err.is_syntax());
311
312        let err = from_slice::<u32>(b"\"x\"").unwrap_err();
313        assert!(err.is_data());
314        let err = from_slice::<Item>(b"{\"name\":\"a\"}").unwrap_err();
315        assert!(err.is_data());
316    }
317
318    /// STATEMENT: `JsonError` keeps the position of both backends and displays one line.
319    ///
320    /// HOW:
321    /// - Convert `serde_json` and `sonic-rs` syntax errors for a multi-line input.
322    /// - Assert line and column match the backend, `Display` has no newline and no input
323    ///   fragment, and `Debug` wraps the same text.
324    #[test]
325    fn error_display() {
326        let input = b"{\n  \"secret\": tru }";
327        let serde =
328            JsonError::from(serde_json::from_slice::<serde_json::Value>(input).unwrap_err());
329        let sonic = JsonError::from(sonic_rs::from_slice::<serde_json::Value>(input).unwrap_err());
330
331        for err in [serde, sonic] {
332            assert!(err.is_syntax());
333            assert_eq!(err.line(), 2);
334            assert!(err.column() > 0);
335            let msg = err.to_string();
336            assert!(!msg.contains('\n'), "{msg:?}");
337            assert!(!msg.contains("secret"), "{msg:?}");
338            assert!(msg.contains("line 2"), "{msg:?}");
339            assert_eq!(format!("{err:?}"), format!("JsonError({msg})"));
340        }
341    }
342}