1use std::borrow::Cow;
5
6use crate::def::{Class, Definitions, Kind, Registry, ShapeDef};
7use crate::path::{Issues, Path};
8use crate::validate::check;
9use crate::value::{MAX_SAFE_INTEGER, Value};
10
11pub trait Shape: Sized {
13 const OPTIONAL: bool = false;
15
16 const CLASS: Class;
18
19 const IS_OBJECT: bool = false;
21
22 const CATCH_ALL: bool = false;
24
25 fn catch_all_shape() -> Option<ShapeDef> {
27 None
28 }
29
30 const KEYS: &'static [&'static str] = &[];
32
33 fn reference() -> ShapeDef;
36
37 fn definition() -> ShapeDef {
39 Self::reference()
40 }
41
42 fn register(registry: &mut Registry);
44
45 fn register_members(registry: &mut Registry) {
48 Self::register(registry);
49 }
50
51 fn absent() -> Option<Self> {
53 None
54 }
55
56 fn definitions() -> Cow<'static, Definitions> {
58 Cow::Owned(Definitions::of::<Self>())
59 }
60
61 fn build_rest(value: &Value, path: &mut Path, known: &[&str]) -> Result<Self, Issues> {
63 let _ = (value, known);
64 mismatch(path, "a type that collects the other members")
65 }
66
67 fn build(value: &Value, path: &mut Path) -> Result<Self, Issues>;
70
71 fn from_json(value: &Value) -> Result<Self, Issues> {
74 let issues = check(&Self::definitions(), &Self::reference(), value);
75 if !issues.is_empty() {
76 return Err(Issues(issues));
77 }
78 Self::build(value, &mut Path::new())
79 }
80
81 fn accepts(value: &Value) -> bool {
83 check(&Self::definitions(), &Self::reference(), value).is_empty()
84 }
85}
86
87fn mismatch<T>(path: &Path, expected: &str) -> Result<T, Issues> {
88 Err(Issues::at(
89 path,
90 format!("the shape and the conversion disagree: expected {expected}"),
91 ))
92}
93
94impl Shape for String {
95 const CLASS: Class = Class::String;
96 fn reference() -> ShapeDef {
97 ShapeDef::new(Kind::String {
98 min_length: None,
99 pattern: None,
100 })
101 }
102 fn register(_: &mut Registry) {}
103 fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
104 match value.as_str() {
105 Some(text) => Ok(text.to_owned()),
106 None => mismatch(path, "a string"),
107 }
108 }
109}
110
111impl Shape for bool {
112 const CLASS: Class = Class::Bool;
113 fn reference() -> ShapeDef {
114 ShapeDef::new(Kind::Bool)
115 }
116 fn register(_: &mut Registry) {}
117 fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
118 match value.as_bool() {
119 Some(flag) => Ok(flag),
120 None => mismatch(path, "a boolean"),
121 }
122 }
123}
124
125impl Shape for f64 {
126 const CLASS: Class = Class::Number;
127 fn reference() -> ShapeDef {
128 ShapeDef::new(Kind::Number {
129 min: None,
130 exclusive_min: None,
131 max: None,
132 })
133 }
134 fn register(_: &mut Registry) {}
135 fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
136 match value.as_f64() {
137 Some(number) => Ok(number),
138 None => mismatch(path, "a number"),
139 }
140 }
141}
142
143impl Shape for Value {
145 const CLASS: Class = Class::Any;
146 fn reference() -> ShapeDef {
147 ShapeDef::new(Kind::Any)
148 }
149 fn register(_: &mut Registry) {}
150 fn build(value: &Value, _: &mut Path) -> Result<Self, Issues> {
151 Ok(value.clone())
152 }
153}
154
155macro_rules! integer_shape {
156 ($type:ty, $min:expr, $max:expr, $convert:expr) => {
157 impl Shape for $type {
158 const CLASS: Class = Class::Integer;
159 fn reference() -> ShapeDef {
160 ShapeDef::new(Kind::Integer {
161 min: Some($min),
162 exclusive_min: None,
163 max: Some($max),
164 })
165 }
166 fn register(_: &mut Registry) {}
167 fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
168 match value.as_f64() {
169 Some(number) if number.fract() == 0.0 => {
171 let convert: fn(i64) -> Option<$type> = $convert;
172 convert(number as i64)
173 .map_or_else(|| mismatch(path, "an integer in range"), Ok)
174 }
175 _ => mismatch(path, "an integer"),
176 }
177 }
178 }
179 };
180}
181
182integer_shape!(u8, 0.0, f64::from(u8::MAX), |n| u8::try_from(n).ok());
183integer_shape!(u16, 0.0, f64::from(u16::MAX), |n| u16::try_from(n).ok());
184integer_shape!(u32, 0.0, f64::from(u32::MAX), |n| u32::try_from(n).ok());
185integer_shape!(i32, f64::from(i32::MIN), f64::from(i32::MAX), |n| {
186 i32::try_from(n).ok()
187});
188integer_shape!(u64, 0.0, MAX_SAFE_INTEGER, |n| u64::try_from(n).ok());
190integer_shape!(usize, 0.0, MAX_SAFE_INTEGER, |n| usize::try_from(n).ok());
191integer_shape!(i64, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, Some);
192
193impl<T: Shape> Shape for Vec<T> {
194 const CLASS: Class = Class::Array;
195 fn reference() -> ShapeDef {
196 ShapeDef::new(Kind::Array {
197 items: Box::new(T::reference()),
198 min_items: None,
199 max_items: None,
200 unique: false,
201 })
202 }
203 fn register(registry: &mut Registry) {
204 T::register(registry);
205 }
206 fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
207 let Some(elements) = value.as_array() else {
208 return mismatch(path, "an array");
209 };
210 let mut built = Vec::with_capacity(elements.len());
211 for (position, element) in elements.iter().enumerate() {
212 path.push_index(position);
213 let item = T::build(element, path);
214 path.pop();
215 built.push(item?);
216 }
217 Ok(built)
218 }
219}
220
221impl<T: Shape> Shape for Option<T> {
225 const OPTIONAL: bool = true;
226 const CLASS: Class = T::CLASS;
227 fn reference() -> ShapeDef {
228 T::reference()
229 }
230 fn register(registry: &mut Registry) {
231 T::register(registry);
232 }
233 fn absent() -> Option<Self> {
234 Some(None)
235 }
236 fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
237 T::build(value, path).map(Some)
238 }
239}
240
241impl<T: Shape> Shape for Box<T> {
242 const CLASS: Class = T::CLASS;
243 const IS_OBJECT: bool = T::IS_OBJECT;
244 const KEYS: &'static [&'static str] = T::KEYS;
245 fn reference() -> ShapeDef {
246 T::reference()
247 }
248 fn definition() -> ShapeDef {
249 T::definition()
250 }
251 fn register(registry: &mut Registry) {
252 T::register(registry);
253 }
254 fn register_members(registry: &mut Registry) {
255 T::register_members(registry);
256 }
257 fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
258 T::build(value, path).map(Box::new)
259 }
260}
261
262#[derive(Clone, Debug, PartialEq)]
266pub struct Map<T>(pub Vec<(String, T)>);
267
268impl<T: Shape> Shape for Map<T> {
269 const CLASS: Class = Class::Map;
270 const CATCH_ALL: bool = true;
271 fn catch_all_shape() -> Option<ShapeDef> {
272 Some(T::reference())
273 }
274 fn build_rest(value: &Value, path: &mut Path, known: &[&str]) -> Result<Self, Issues> {
275 let Some(pairs) = value.as_object() else {
276 return mismatch(path, "an object");
277 };
278 let mut built = Vec::new();
279 for (key, entry) in pairs
280 .iter()
281 .filter(|(key, _)| !known.contains(&key.as_str()))
282 {
283 path.push_key(key);
284 let item = T::build(entry, path);
285 path.pop();
286 built.push((key.clone(), item?));
287 }
288 Ok(Map(built))
289 }
290 fn reference() -> ShapeDef {
291 ShapeDef::new(Kind::Map {
292 values: Box::new(T::reference()),
293 min_properties: None,
294 key_pattern: None,
295 })
296 }
297 fn register(registry: &mut Registry) {
298 T::register(registry);
299 }
300 fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
301 let Some(pairs) = value.as_object() else {
302 return mismatch(path, "an object");
303 };
304 let mut built = Vec::with_capacity(pairs.len());
305 for (key, entry) in pairs.iter().filter(|(key, _)| key != "__proto__") {
306 path.push_key(key);
307 let item = T::build(entry, path);
308 path.pop();
309 built.push((key.clone(), item?));
310 }
311 Ok(Map(built))
312 }
313}
314
315#[derive(Clone, Debug, PartialEq)]
317pub struct OpenObject(pub Vec<(String, Value)>);
318
319impl Shape for OpenObject {
320 const CLASS: Class = Class::OpenObject;
321 const CATCH_ALL: bool = true;
322 fn catch_all_shape() -> Option<ShapeDef> {
323 Some(ShapeDef::new(Kind::Any))
324 }
325 fn build_rest(value: &Value, path: &mut Path, known: &[&str]) -> Result<Self, Issues> {
326 match value.as_object() {
327 Some(pairs) => Ok(OpenObject(
328 pairs
329 .iter()
330 .filter(|(key, _)| !known.contains(&key.as_str()))
331 .cloned()
332 .collect(),
333 )),
334 None => mismatch(path, "an object"),
335 }
336 }
337 fn reference() -> ShapeDef {
338 ShapeDef::new(Kind::Object(crate::def::ObjectDef::default()))
339 }
340 fn register(_: &mut Registry) {}
341 fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
342 match value.as_object() {
343 Some(pairs) => Ok(OpenObject(pairs.to_vec())),
344 None => mismatch(path, "an object"),
345 }
346 }
347}