Skip to main content

ctl_input/
json_format.rs

1//! The JSON [`Format`]: the own reader's tree, each scalar carrying the type
2//! its syntax gave it, and each scalar resolves by that type.
3
4use std::borrow::Cow;
5
6use super::exceeded::Exceeded;
7use super::format::{Format, Mismatch, Raise, Reading, Refusal, Resolved, Wanted};
8use super::json;
9use super::limits::Limits;
10use super::tree::{Node, Scalar, ScalarSyntax, Tag};
11
12/// JSON by RFC 8259, with no option that loosens it. Its extension is `json`.
13///
14/// A strict reading refuses a key written twice in one object, comparing keys
15/// after their escapes are decoded, and a listing reading keeps both entries.
16/// A number keeps its source text, and a field decides whether it fits.
17#[derive(Clone, Copy, Debug)]
18pub struct Json;
19
20/// The JSON format, for [`Formats::add`](crate::Formats::add).
21pub static JSON: Json = Json;
22
23impl Format for Json {
24    fn name(&self) -> &'static str {
25        "json"
26    }
27
28    fn extensions(&self) -> &'static [&'static str] {
29        &["json"]
30    }
31
32    /// Checks `max_reader_input_bytes` before the first token, `max_depth`
33    /// when an array or an object opens, and `max_nodes` when a value is
34    /// added.
35    fn read(&self, text: &str, limits: &Limits, reading: Reading) -> Result<Node, Refusal> {
36        let bounds = limits.bounds();
37        if text.len() > bounds.input_bytes {
38            let exceeded = Exceeded::input_bytes(bounds.input_bytes, Raise::FOR_TEXT);
39            return Err(Refusal::new(exceeded.fault(), None, None));
40        }
41        json::read(text, bounds, reading)
42    }
43
44    /// Resolves by the type the scalar's syntax gave it, and never by its
45    /// text. A scalar that carries no syntax, such as one another format built,
46    /// is text. A typeless read has no field to say what was expected, so a
47    /// number it cannot hold is refused with its text and `out of range`.
48    fn resolve<'a>(
49        &self,
50        scalar: &'a Scalar,
51        _tag: Option<&Tag>,
52        wanted: Wanted,
53    ) -> Result<Resolved<'a>, Mismatch> {
54        let text = scalar.value();
55        let syntax = scalar.syntax().unwrap_or(ScalarSyntax::Text);
56        let resolved = match (syntax, wanted) {
57            (ScalarSyntax::Text, Wanted::Any | Wanted::Str) => {
58                Some(Resolved::Str(Cow::Borrowed(text)))
59            }
60            (ScalarSyntax::Boolean, Wanted::Any | Wanted::Bool) => {
61                Some(Resolved::Bool(text == "true"))
62            }
63            (ScalarSyntax::Integer, Wanted::Int) => integer(text),
64            (ScalarSyntax::Integer, Wanted::Any) => integer(text).or_else(|| float(text)),
65            (ScalarSyntax::Integer | ScalarSyntax::Float, Wanted::Any | Wanted::Float) => {
66                float(text)
67            }
68            (ScalarSyntax::Null, Wanted::Any | Wanted::Null) => Some(Resolved::Null),
69            _ => None,
70        };
71        resolved.ok_or_else(|| {
72            let mismatch = Mismatch::new(wanted);
73            if wanted == Wanted::Any
74                && matches!(syntax, ScalarSyntax::Integer | ScalarSyntax::Float)
75            {
76                mismatch.with_detail(format!("number `{text}` is out of range"))
77            } else {
78                mismatch
79            }
80        })
81    }
82}
83
84/// The integer a JSON integer's text spells: an `i128`, or a `u128` above it.
85/// A text no `u128` holds is no integer.
86fn integer(text: &str) -> Option<Resolved<'static>> {
87    text.parse()
88        .map(Resolved::Int)
89        .or_else(|_| text.parse().map(Resolved::Uint))
90        .ok()
91}
92
93/// The float a number's text spells. A value that overflows to infinity is
94/// refused.
95fn float(text: &str) -> Option<Resolved<'static>> {
96    text.parse::<f64>()
97        .ok()
98        .filter(|value| value.is_finite())
99        .map(Resolved::Float)
100}