1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use crate::JsonValue;
use std::collections::HashMap;
use std::fmt;
#[derive(Debug)]
pub struct JsonGenerateError {
msg: &'static str,
}
impl JsonGenerateError {
fn new(msg: &'static str) -> Self {
JsonGenerateError { msg }
}
pub fn message(&self) -> &str {
&self.msg
}
}
impl fmt::Display for JsonGenerateError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Generate error: {}", &self.msg)
}
}
pub type JsonGenerateResult = Result<String, JsonGenerateError>;
fn quote(s: &str) -> String {
let mut to = '"'.to_string();
for c in s.chars() {
match c {
'\\' => to.push_str("\\\\"),
'\u{0008}' => to.push_str("\\b"),
'\u{000c}' => to.push_str("\\f"),
'\n' => to.push_str("\\n"),
'\r' => to.push_str("\\r"),
'\t' => to.push_str("\\t"),
'"' => to.push_str("\\\""),
c if c.is_control() => to.push_str(&format!("\\u{:04x}", c as u32)),
c => to.push(c),
}
}
to.push('"');
to
}
fn array(array: &[JsonValue]) -> JsonGenerateResult {
let mut to = '['.to_string();
for elem in array.iter() {
let s: String = stringify(elem)?;
to += &s;
to.push(',');
}
to.pop();
to.push(']');
Ok(to)
}
fn object(m: &HashMap<String, JsonValue>) -> JsonGenerateResult {
let mut to = '{'.to_string();
for (k, v) in m {
to += "e(k);
to.push(':');
let s: String = stringify(v)?;
to += &s;
to.push(',');
}
to.pop();
to.push('}');
Ok(to)
}
fn number(f: f64) -> JsonGenerateResult {
if f.is_infinite() {
Err(JsonGenerateError::new("JSON cannot represent inf"))
} else if f.is_nan() {
Err(JsonGenerateError::new("JSON cannot represent NaN"))
} else {
Ok(f.to_string())
}
}
pub fn stringify(value: &JsonValue) -> JsonGenerateResult {
match value {
JsonValue::Number(n) => number(*n),
JsonValue::Boolean(b) => Ok(b.to_string()),
JsonValue::String(s) => Ok(quote(s)),
JsonValue::Null => Ok("null".to_string()),
JsonValue::Array(a) => array(a),
JsonValue::Object(o) => object(o),
}
}