1use crate::json::{Object, Value};
6use std::fmt;
7
8#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct DecodeError {
12 pub path: Vec<String>,
13 pub message: String,
14 pub got: String,
16}
17
18impl DecodeError {
19 pub fn new(message: impl Into<String>) -> Self {
20 DecodeError {
21 path: Vec::new(),
22 message: message.into(),
23 got: String::new(),
24 }
25 }
26
27 pub fn at_path(mut self, path: &[&str]) -> Self {
28 self.path = path.iter().map(|s| (*s).to_owned()).collect();
29 self
30 }
31
32 pub fn at(mut self, key: impl Into<String>) -> Self {
34 self.path.insert(0, key.into());
35 self
36 }
37
38 pub fn valita_message(&self) -> String {
42 if self.message == "Missing property"
43 && let Some((key, rest)) = self.path.split_last()
44 {
45 return if rest.is_empty() {
46 format!("Missing property {key}")
47 } else {
48 format!("Missing property {key} at {}", rest.join("."))
49 };
50 }
51 self.to_string()
52 }
53}
54
55impl fmt::Display for DecodeError {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 if self.path.is_empty() {
58 write!(f, "{}{}", self.message, self.got)
59 } else {
60 write!(f, "{} at {}{}", self.message, self.path.join("."), self.got)
61 }
62 }
63}
64
65impl std::error::Error for DecodeError {}
66
67pub type Result<T, E = DecodeError> = std::result::Result<T, E>;
68
69pub trait JsonCodable: Sized {
71 fn from_json(v: &Value) -> Result<Self>;
72 fn to_json(&self) -> Value;
73}
74
75#[derive(Clone, Copy)]
77pub struct Reader<'a>(pub &'a Object);
78
79impl<'a> Reader<'a> {
80 pub fn new(v: &'a Value, what: &str) -> Result<Self> {
81 match v {
82 Value::Object(o) => Ok(Reader(o)),
83 v => Err(DecodeError::new(format!(
84 "Expected {what}, got {}",
85 v.type_name()
86 ))),
87 }
88 }
89
90 pub fn get(&self, key: &str) -> Option<&'a Value> {
91 self.0.get(key)
92 }
93
94 pub fn required<T>(&self, key: &str, decode: impl FnOnce(&'a Value) -> Result<T>) -> Result<T> {
95 let v = self
96 .0
97 .get(key)
98 .ok_or_else(|| DecodeError::new("Missing property").at(key))?;
99 decode(v).map_err(|e| e.at(key))
100 }
101
102 pub fn optional<T>(
103 &self,
104 key: &str,
105 decode: impl FnOnce(&'a Value) -> Result<T>,
106 ) -> Result<Option<T>> {
107 match self.0.get(key) {
108 None => Ok(None),
109 Some(v) => decode(v).map(Some).map_err(|e| e.at(key)),
110 }
111 }
112
113 pub fn string(&self, key: &str) -> Result<String> {
114 self.required(key, string)
115 }
116
117 pub fn optional_string(&self, key: &str) -> Result<Option<String>> {
118 self.optional(key, string)
119 }
120
121 pub fn number(&self, key: &str) -> Result<f64> {
122 self.required(key, number)
123 }
124
125 pub fn optional_number(&self, key: &str) -> Result<Option<f64>> {
126 self.optional(key, number)
127 }
128
129 pub fn bool(&self, key: &str) -> Result<bool> {
130 self.required(key, bool)
131 }
132
133 pub fn optional_bool(&self, key: &str) -> Result<Option<bool>> {
134 self.optional(key, bool)
135 }
136
137 pub fn literal(&self, key: &str, expected: &str) -> Result<()> {
139 let s = self.string(key)?;
140 if s != expected {
141 return Err(
142 DecodeError::new(format!("Expected literal \"{expected}\", got \"{s}\"")).at(key),
143 );
144 }
145 Ok(())
146 }
147}
148
149pub fn string(v: &Value) -> Result<String> {
150 match v {
151 Value::String(s) => Ok(s.clone()),
152 v => Err(DecodeError::new(format!(
153 "Expected string, got {}",
154 v.type_name()
155 ))),
156 }
157}
158
159pub fn number(v: &Value) -> Result<f64> {
160 match v {
161 Value::Number(n) => Ok(*n),
162 v => Err(DecodeError::new(format!(
163 "Expected number, got {}",
164 v.type_name()
165 ))),
166 }
167}
168
169pub fn bool(v: &Value) -> Result<bool> {
170 match v {
171 Value::Bool(b) => Ok(*b),
172 v => Err(DecodeError::new(format!(
173 "Expected boolean, got {}",
174 v.type_name()
175 ))),
176 }
177}
178
179pub fn object(v: &Value) -> Result<Object> {
180 match v {
181 Value::Object(o) => Ok(o.clone()),
182 v => Err(DecodeError::new(format!(
183 "Expected object, got {}",
184 v.type_name()
185 ))),
186 }
187}
188
189pub fn array_value(v: &Value) -> Result<&Vec<Value>> {
190 match v {
191 Value::Array(a) => Ok(a),
192 v => Err(DecodeError::new(format!(
193 "Expected array, got {}",
194 v.type_name()
195 ))),
196 }
197}
198
199pub fn array<T>(v: &Value, mut element: impl FnMut(&Value) -> Result<T>) -> Result<Vec<T>> {
201 array_value(v)?
202 .iter()
203 .enumerate()
204 .map(|(i, e)| element(e).map_err(|err| err.at(i.to_string())))
205 .collect()
206}
207
208pub fn strings(v: &Value) -> Result<Vec<String>> {
209 array(v, string)
210}
211
212pub fn compound_key(v: &Value) -> Result<Vec<String>> {
214 let k = strings(v)?;
215 if k.is_empty() {
216 return Err(DecodeError::new("Expected non-empty array"));
217 }
218 Ok(k)
219}
220
221pub fn record<T>(
223 v: &Value,
224 mut element: impl FnMut(&Value) -> Result<T>,
225) -> Result<Vec<(String, T)>> {
226 let Value::Object(o) = v else {
227 return Err(DecodeError::new(format!(
228 "Expected object, got {}",
229 v.type_name()
230 )));
231 };
232 o.iter()
233 .map(|(k, e)| Ok((k.clone(), element(e).map_err(|err| err.at(k.clone()))?)))
234 .collect()
235}
236
237pub fn primary_key_value(v: &Value) -> Result<Value> {
239 match v {
240 Value::String(_) | Value::Number(_) | Value::Bool(_) => Ok(v.clone()),
241 v => Err(DecodeError::new(format!(
242 "Expected string, number, or boolean, got {}",
243 v.type_name()
244 ))),
245 }
246}
247
248pub fn tagged(v: &Value) -> Result<(&str, &Value)> {
250 match v {
251 Value::Array(a) if a.len() == 2 => match &a[0] {
252 Value::String(tag) => Ok((tag, &a[1])),
253 _ => Err(DecodeError::new("Expected [tag, body] tuple")),
254 },
255 _ => Err(DecodeError::new("Expected [tag, body] tuple")),
256 }
257}
258
259#[derive(Default)]
261pub struct Builder(pub Object);
262
263impl Builder {
264 pub fn new() -> Self {
265 Self::default()
266 }
267
268 pub fn set(mut self, key: &str, value: impl Into<Value>) -> Self {
269 self.0.insert(key, value.into());
270 self
271 }
272
273 pub fn opt(mut self, key: &str, value: Option<impl Into<Value>>) -> Self {
274 if let Some(v) = value {
275 self.0.insert(key, v.into());
276 }
277 self
278 }
279
280 pub fn build(self) -> Value {
281 Value::Object(self.0)
282 }
283}
284
285pub fn strings_json(v: &[String]) -> Value {
287 Value::Array(v.iter().map(|s| Value::String(s.clone())).collect())
288}