1use 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#[derive(Clone, Copy, Debug)]
18pub struct Json;
19
20pub 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 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 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
84fn 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
93fn float(text: &str) -> Option<Resolved<'static>> {
96 text.parse::<f64>()
97 .ok()
98 .filter(|value| value.is_finite())
99 .map(Resolved::Float)
100}