1pub mod deserialize;
2pub mod error;
3pub mod serialize;
4pub use deserialize::{from_str, Deserialize};
5pub use serialize::Serialize;
6pub use tiny_serde_derive::Serialize;
7
8use std::collections::HashMap;
9
10#[derive(Clone, Debug)]
11pub enum Number {
12 Integer(u128),
13 SignedInteger(i128),
14 Decimal(f64),
15}
16
17impl ToString for Number {
18 fn to_string(&self) -> String {
19 match self {
20 Self::Integer(int) => int.to_string(),
21 Self::SignedInteger(int) => int.to_string(),
22 Self::Decimal(dec) => dec.to_string(),
23 }
24 }
25}
26
27#[derive(Clone, Debug)]
28pub enum Value {
29 Null,
30 Boolean(bool),
31 Number(Number),
32 String(String),
33 Array(Vec<Value>),
34 Object(HashMap<String, Value>),
35}
36
37impl ToString for Value {
38 fn to_string(&self) -> String {
39 match self {
40 Self::Null => "null".to_string(),
41 Self::Boolean(b) => match b {
42 true => "true",
43 false => "false",
44 }
45 .to_string(),
46 Self::Number(nb) => nb.to_string(),
47 Self::String(value) => {
48 let value = value
49 .replace('"', r#"\""#)
50 .replace('\\', r#"\\"#)
51 .replace('\n', r#"\n"#)
52 .replace('\r', r#"\r"#);
53 format!("\"{value}\"")
54 }
55 Self::Array(array) => array_to_json(array),
56 Self::Object(object) => object_to_json(object),
57 }
58 }
59}
60
61fn array_to_json(array: &[Value]) -> String {
62 let mut final_value = "[".to_string();
63 let last_index = array.len() - 1;
64 for (i, value) in array.iter().enumerate() {
65 final_value += &value.to_string();
66 if i < last_index {
67 final_value.push(',');
68 }
69 }
70 final_value += "]";
71 final_value
72}
73
74fn object_to_json(object: &HashMap<String, Value>) -> String {
75 let mut final_value = "{".to_string();
76 let last_index = object.len() - 1;
77 let mut i = 0;
78 for (key, value) in object.iter() {
79 if i < last_index {
80 final_value += &format!("\"{key}\":{},", value.to_string());
81 } else {
82 final_value += &format!("\"{key}\":{}", value.to_string());
83 }
84 i += 1;
85 }
86 final_value += "}";
87 final_value
88}