Skip to main content

ocpi_tariffs/json/
decode.rs

1//! String decoding for JSON values parsed by [`super`].
2//!
3//! # Parsing vs decoding
4//!
5//! The JSON parser is intentionally lenient: it accepts any structurally
6//! valid JSON string, leaving escape sequences and control characters
7//! verbatim inside a raw string. Decoding is a separate step
8//! performed by this module.
9//!
10//! Keeping these concerns apart means the linter can treat string-encoding
11//! problems as warnings rather than fatal parse errors. The caller receives
12//! both a best-effort string value and a list of [`Warning`]s describing what
13//! was wrong and where, which is enough information to suggest a corrected
14//! encoding to the user.
15#[cfg(test)]
16mod test_from_str;
17
18use std::{borrow::Cow, fmt, iter::Peekable, ops::RangeInclusive};
19
20use super::Element;
21use crate::warning;
22
23const ESCAPE_CHAR: char = '\\';
24
25/// The kind of `Warning` that can happen when decoding a `&str`.
26#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
27pub enum Warning {
28    /// Control chars were found while parsing a JSON string.
29    ControlCharacter(usize),
30
31    /// A UTF-16 surrogate pair failed to decode.
32    DecodeUtf16(usize, u16),
33
34    /// A string contains invalid escape chars.
35    InvalidEscape(usize),
36
37    /// The String ended before the parser expected.
38    UnexpectedEndOfString(usize),
39}
40
41impl crate::Warning for Warning {
42    /// A human readable identifier for each `Warning`.
43    fn id(&self) -> warning::Id {
44        match self {
45            Self::ControlCharacter(_) => {
46                warning::Id::from_static("control_character_while_parsing_string")
47            }
48            Self::DecodeUtf16(..) => warning::Id::from_static("decode_utf_1_6"),
49            Self::InvalidEscape(_) => warning::Id::from_static("invalid_escape"),
50            Self::UnexpectedEndOfString(_) => warning::Id::from_static("unexpected_end_of_string"),
51        }
52    }
53}
54
55impl fmt::Display for Warning {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        match self {
58            Self::ControlCharacter(index) => {
59                write!(
60                    f,
61                    "Control chars were found at index `{index}` while decoding a JSON string."
62                )
63            }
64            Self::DecodeUtf16(index, code) => {
65                write!(
66                    f,
67                    "A UTF-16 surrogate pair `{code}` failed to decode at index: `{index}`."
68                )
69            }
70            Self::InvalidEscape(index) => {
71                write!(
72                    f,
73                    "String contains an invalid escape char at index: `{index})`."
74                )
75            }
76            Self::UnexpectedEndOfString(index) => {
77                write!(f, "The String ended prematurely at index: `{index}`.")
78            }
79        }
80    }
81}
82
83/// Return a `PendingStr` that marks the inner `&str` is containing escape codes or not.
84pub(super) fn analyze<'buf>(
85    s: &'buf str,
86    elem: &Element<'buf>,
87    warnings: &mut dyn warning::Gather<Warning>,
88) -> super::PendingStr<'buf> {
89    // Strings are expected to be small so running over all bytes
90    // with the intent of early exiting is acceptable.
91    if let Some((index, _)) = s.char_indices().find(|(_, ch)| ch.is_control()) {
92        warnings.insert(elem, Warning::ControlCharacter(index));
93    }
94
95    if s.chars().any(|ch| ch == ESCAPE_CHAR) {
96        super::PendingStr::HasEscapes
97    } else {
98        super::PendingStr::NoEscapes(s)
99    }
100}
101
102/// Return the `str` with escaped chars replaced with the decoded equivalent, and the
103/// warning that decoding it raised, if any.
104///
105/// Returns `Cow::Owned` when all escapes decoded successfully.
106/// Returns `Cow::Borrowed` if the raw string doesn't contain any escapes,
107/// or if decoding it raised a warning.
108///
109/// `from_raw` stops at the first warning, so a call raises at most one. The caller reports it
110/// against the element the string came from.
111pub(super) fn from_raw(s: &str) -> (Cow<'_, str>, Option<Warning>) {
112    // Strings are expected to be small so running over all
113    // bytes to early out is acceptable.
114    if !s.chars().any(|ch| ch == ESCAPE_CHAR) {
115        let warning = s
116            .char_indices()
117            .find(|(_, ch)| ch.is_control())
118            .map(|(index, _)| Warning::ControlCharacter(index));
119        return (Cow::Borrowed(s), warning);
120    }
121
122    let mut buf = Buffer::with_capacity(s.len());
123    for decoded in Decoded::from_str(s) {
124        match decoded {
125            Ok(ch) => buf.push(ch),
126            Err(warning) => return (Cow::Borrowed(s), Some(warning)),
127        }
128    }
129
130    (Cow::Owned(buf.into_string()), None)
131}
132
133/// Scan a raw JSON string body for the lexical issues
134/// [`super::RawStr::lexical_issues`] reports: whether it contains escape sequences,
135/// and whether its decoded form contains non-printable ASCII. Done in a single pass
136/// without allocating.
137pub(super) fn lexical_issues(s: &str) -> super::LexicalIssues {
138    // `\` is ASCII (`0x5C`) so it cannot appear within a multi-byte UTF-8 sequence; a
139    // raw byte search is therefore a correct escape-presence test.
140    let escapes = s.as_bytes().contains(&b'\\');
141
142    // Without escapes the raw bytes are the content. With escapes we must decode to see
143    // the real chars (` ` decodes to a space, for example). Decoding on the fly
144    // avoids the allocation that `from_raw` would make.
145    let non_printable_ascii = if escapes {
146        decoded_has_non_printable_ascii(s)
147    } else {
148        s.chars().any(is_non_printable_ascii)
149    };
150
151    super::LexicalIssues {
152        escapes,
153        non_printable_ascii,
154    }
155}
156
157/// Whether the decoded form of `s` contains a non-printable ASCII char.
158///
159/// A decode failure mirrors [`from_raw`], which returns the raw string unchanged on
160/// error; the scan then falls back to the raw bytes.
161fn decoded_has_non_printable_ascii(s: &str) -> bool {
162    let mut found = false;
163    for decoded in Decoded::from_str(s) {
164        match decoded {
165            Ok(ch) => {
166                if is_non_printable_ascii(ch) {
167                    found = true;
168                }
169            }
170            Err(_) => return s.chars().any(is_non_printable_ascii),
171        }
172    }
173    found
174}
175
176/// Whether `ch` is an ASCII control character or ASCII whitespace.
177fn is_non_printable_ascii(ch: char) -> bool {
178    ch.is_ascii_whitespace() || ch.is_ascii_control()
179}
180
181/// Compare `other` against the decoded form of the raw JSON string body `raw`,
182/// decoding escape sequences on the fly. Does not allocate.
183///
184/// Returns `Ok(true)` / `Ok(false)` for the comparison, or `Err` if `raw` has a
185/// decoding problem (invalid escape, control character, ...) at or before the
186/// first differing character. Once the two strings are known to differ, decoding
187/// stops, so a decode problem beyond that point is not reported.
188pub(super) fn eq(raw: &str, other: &str) -> Result<bool, Warning> {
189    let mut decoded = Decoded::from_str(raw);
190    let mut expected = other.chars();
191
192    loop {
193        match decoded.next() {
194            Some(Err(warn_kind)) => return Err(warn_kind),
195            Some(Ok(actual)) => {
196                if expected.next() != Some(actual) {
197                    return Ok(false);
198                }
199            }
200            // `raw` is exhausted; the strings are equal only if `other` is too.
201            None => return Ok(expected.next().is_none()),
202        }
203    }
204}
205
206/// Like [`eq`], but compares ASCII letters case-insensitively.
207pub(super) fn eq_ignore_ascii_case(raw: &str, other: &str) -> Result<bool, Warning> {
208    let mut decoded = Decoded::from_str(raw);
209    let mut expected = other.chars();
210
211    loop {
212        match decoded.next() {
213            Some(Err(warn_kind)) => return Err(warn_kind),
214            Some(Ok(actual)) => match expected.next() {
215                Some(expected) if expected.eq_ignore_ascii_case(&actual) => {}
216                _ => return Ok(false),
217            },
218            // `raw` is exhausted; the strings are equal only if `other` is too.
219            None => return Ok(expected.next().is_none()),
220        }
221    }
222}
223
224/// Decode the escape sequence following a backslash and return the character it stands
225/// for. Assumes the backslash has just been read.
226///
227/// The legal shorthands that decode to a control character - `\b`, `\f`, `\n`, `\r` and `\t` -
228/// are rejected with `Warning::ControlCharacter` rather than returned. The decode layer refuses a
229/// control character however it was written.
230///
231/// * See: <https://datatracker.ietf.org/doc/html/rfc8259#section-7>
232fn parse_escape(chars: &mut Chars<'_>) -> Result<char, Warning> {
233    let (index, ch) = chars.next_or_eof()?;
234
235    let ch = match ch {
236        '"' => '"',
237        '\\' => '\\',
238        '/' => '/',
239        'b' => '\x08',
240        'f' => '\x0c',
241        'n' => '\n',
242        'r' => '\r',
243        't' => '\t',
244        'u' => return parse_unicode_escape(chars),
245        _ => {
246            return Err(Warning::InvalidEscape(index));
247        }
248    };
249
250    if ch.is_control() {
251        return Err(Warning::ControlCharacter(index));
252    }
253
254    Ok(ch)
255}
256
257/// Decode a `\u` escape and return the character it stands for. Assumes the `\u` has just
258/// been read.
259///
260/// A high surrogate is half a character, so it is paired with the `\u` escape that follows it. A
261/// lone surrogate, or a value that is no Unicode scalar, is `Warning::InvalidEscape`. A `\u`
262/// escape that decodes to a control character is refused like any other.
263///
264/// * See: <https://datatracker.ietf.org/doc/html/rfc8259#section-8.2>
265fn parse_unicode_escape(chars: &mut Chars<'_>) -> Result<char, Warning> {
266    // High surrogates occupy `U+D800..=U+DBFF`. A high surrogate is the first
267    // code unit of a UTF-16 surrogate pair; it must be followed by a low
268    // surrogate (`U+DC00..=U+DFFF`) to form a valid scalar value. Lone high
269    // surrogates and all low surrogates are not valid Unicode scalar values.
270    const HIGH_SURROGATE: RangeInclusive<u16> = 0xD800..=0xDBFF;
271
272    let n1 = decode_hex_escape(chars)?;
273
274    let ch = if HIGH_SURROGATE.contains(&n1) {
275        // Only look for a surrogate-pair continuation when N1 is a high surrogate.
276        // Calling `is_next_escape` unconditionally would consume the `\` of any
277        // following escape and pass two unrelated BMP codepoints to
278        // decode_surrogate_pair, which only decodes the first and silently drops the second.
279        let Some(n2) = chars.is_next_escape()? else {
280            return Err(Warning::InvalidEscape(chars.index));
281        };
282        decode_surrogate_pair(n1, n2, chars.index)?
283    } else {
284        let Some(ch) = char::from_u32(u32::from(n1)) else {
285            return Err(Warning::InvalidEscape(chars.index));
286        };
287        ch
288    };
289
290    if ch.is_control() {
291        return Err(Warning::ControlCharacter(chars.index));
292    }
293
294    Ok(ch)
295}
296
297/// A char iterator that can fail if the next char is a control char.
298struct Chars<'buf> {
299    /// The `char` iterator.
300    ///
301    /// This needs to be a `CharIndices` as the `Chars` iterator skips over escaped chars.
302    /// And this needs to be `Peekable` as we need to look ahead to detect a potential second
303    /// Unicode literal and treat that as a UTF-16 surrogate pair.
304    char_indices: Peekable<std::str::CharIndices<'buf>>,
305
306    /// A single character pushed back by `is_next_escape` when it consumed a `\`
307    /// speculatively but found it was not the start of a `\uXXXX` sequence.
308    push_back: Option<(usize, char)>,
309
310    /// The last parsed char index.
311    index: usize,
312}
313
314impl<'buf> Chars<'buf> {
315    /// Create a new `Chars` iterator from a `&str`.
316    fn from_str(s: &'buf str) -> Self {
317        Self {
318            char_indices: s.char_indices().peekable(),
319            push_back: None,
320            index: 0,
321        }
322    }
323
324    /// Return the next char as `Ok` or return `Err(UnexpectedEndOfString)` if there is no char
325    /// or return `Err(ControlCharacter)` if the next char is a control char.
326    fn next_or_eof(&mut self) -> Result<(usize, char), Warning> {
327        if let Some((index, ch)) = self.next() {
328            if ch.is_control() {
329                return Err(Warning::ControlCharacter(index));
330            }
331
332            Ok((index, ch))
333        } else {
334            Err(Warning::UnexpectedEndOfString(self.index))
335        }
336    }
337
338    /// Look ahead in the char stream and if there is another `\uXXXX` sequence
339    /// return it as a decoded hex value.
340    ///
341    /// If a `\` is found but not followed by `u`, the `\` is pushed back so the
342    /// outer loop can process it as the start of a different escape sequence.
343    fn is_next_escape(&mut self) -> Result<Option<u16>, Warning> {
344        let Some(backslash) = self.char_indices.next_if(|(_, ch)| *ch == ESCAPE_CHAR) else {
345            return Ok(None);
346        };
347
348        if self.char_indices.next_if(|(_, ch)| *ch == 'u').is_none() {
349            self.push_back = Some(backslash);
350            return Ok(None);
351        }
352
353        let n = decode_hex_escape(self)?;
354        Ok(Some(n))
355    }
356}
357
358impl Iterator for Chars<'_> {
359    type Item = (usize, char);
360
361    fn next(&mut self) -> Option<Self::Item> {
362        if let Some(item) = self.push_back.take() {
363            self.index = item.0;
364            return Some(item);
365        }
366        if let Some((index, char)) = self.char_indices.next() {
367            self.index = index;
368            Some((index, char))
369        } else {
370            None
371        }
372    }
373}
374
375/// Iterator over the decoded `char`s of a JSON string body (quotes removed).
376///
377/// Escape sequences are decoded on the fly; control characters and malformed
378/// escapes are returned as `Err`. Callers typically stop at the first `Err`.
379struct Decoded<'buf> {
380    chars: Chars<'buf>,
381}
382
383impl<'buf> Decoded<'buf> {
384    /// Create a `Decoded` iterator from a JSON string body.
385    fn from_str(s: &'buf str) -> Self {
386        Self {
387            chars: Chars::from_str(s),
388        }
389    }
390}
391
392impl Iterator for Decoded<'_> {
393    type Item = Result<char, Warning>;
394
395    fn next(&mut self) -> Option<Self::Item> {
396        let (index, ch) = self.chars.next()?;
397
398        if ch == ESCAPE_CHAR {
399            Some(parse_escape(&mut self.chars))
400        } else if ch.is_control() {
401            Some(Err(Warning::ControlCharacter(index)))
402        } else {
403            Some(Ok(ch))
404        }
405    }
406}
407
408/// The `String` based buffer where we accumulate the decoded JSON string.
409struct Buffer {
410    /// The `String` to accumulate chars in.
411    buf: String,
412}
413
414impl Buffer {
415    /// Create a new `Buffer`.
416    fn with_capacity(capacity: usize) -> Self {
417        Self {
418            buf: String::with_capacity(capacity),
419        }
420    }
421
422    /// Push an already-decoded char into the `String`.
423    fn push(&mut self, ch: char) {
424        self.buf.push(ch);
425    }
426
427    /// Consume the `Buffer` and return the inner `String`.
428    fn into_string(self) -> String {
429        self.buf
430    }
431}
432
433/// Decode the high and low code units of a UTF-16 surrogate pair into a `char`.
434///
435/// Returns `Err(DecodeUtf16)` if the two code units do not form a valid pair.
436fn decode_surrogate_pair(n1: u16, n2: u16, index: usize) -> Result<char, Warning> {
437    let Some(ch) = char::decode_utf16([n1, n2]).next() else {
438        return Err(Warning::InvalidEscape(index));
439    };
440
441    match ch {
442        Ok(ch) => Ok(ch),
443        Err(err) => Err(Warning::DecodeUtf16(index, err.unpaired_surrogate())),
444    }
445}
446
447/// Munch four chars as bytes and try to convert them into a `char`.
448fn decode_hex_escape(chars: &mut Chars<'_>) -> Result<u16, Warning> {
449    const RADIX: u32 = 16;
450
451    let (_, one) = chars.next_or_eof()?;
452    let (_, two) = chars.next_or_eof()?;
453    let (_, three) = chars.next_or_eof()?;
454    let (index, four) = chars.next_or_eof()?;
455
456    let string = [one, two, three, four].into_iter().collect::<String>();
457    let Ok(n) = u16::from_str_radix(&string, RADIX) else {
458        return Err(Warning::InvalidEscape(index));
459    };
460
461    Ok(n)
462}