use std::borrow::Cow;
use crate::def::{Class, Definitions, Kind, Registry, ShapeDef};
use crate::path::{Issues, Path};
use crate::validate::check;
use crate::value::{MAX_SAFE_INTEGER, Value};
pub trait Shape: Sized {
const OPTIONAL: bool = false;
const CLASS: Class;
const IS_OBJECT: bool = false;
const CATCH_ALL: bool = false;
fn catch_all_shape() -> Option<ShapeDef> {
None
}
const KEYS: &'static [&'static str] = &[];
fn reference() -> ShapeDef;
fn definition() -> ShapeDef {
Self::reference()
}
fn register(registry: &mut Registry);
fn register_members(registry: &mut Registry) {
Self::register(registry);
}
fn absent() -> Option<Self> {
None
}
fn definitions() -> Cow<'static, Definitions> {
Cow::Owned(Definitions::of::<Self>())
}
fn build_rest(value: &Value, path: &mut Path, known: &[&str]) -> Result<Self, Issues> {
let _ = (value, known);
mismatch(path, "a type that collects the other members")
}
fn build(value: &Value, path: &mut Path) -> Result<Self, Issues>;
fn from_json(value: &Value) -> Result<Self, Issues> {
let issues = check(&Self::definitions(), &Self::reference(), value);
if !issues.is_empty() {
return Err(Issues(issues));
}
Self::build(value, &mut Path::new())
}
fn accepts(value: &Value) -> bool {
check(&Self::definitions(), &Self::reference(), value).is_empty()
}
}
fn mismatch<T>(path: &Path, expected: &str) -> Result<T, Issues> {
Err(Issues::at(
path,
format!("the shape and the conversion disagree: expected {expected}"),
))
}
impl Shape for String {
const CLASS: Class = Class::String;
fn reference() -> ShapeDef {
ShapeDef::new(Kind::String {
min_length: None,
pattern: None,
})
}
fn register(_: &mut Registry) {}
fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
match value.as_str() {
Some(text) => Ok(text.to_owned()),
None => mismatch(path, "a string"),
}
}
}
impl Shape for bool {
const CLASS: Class = Class::Bool;
fn reference() -> ShapeDef {
ShapeDef::new(Kind::Bool)
}
fn register(_: &mut Registry) {}
fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
match value.as_bool() {
Some(flag) => Ok(flag),
None => mismatch(path, "a boolean"),
}
}
}
impl Shape for f64 {
const CLASS: Class = Class::Number;
fn reference() -> ShapeDef {
ShapeDef::new(Kind::Number {
min: None,
exclusive_min: None,
max: None,
})
}
fn register(_: &mut Registry) {}
fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
match value.as_f64() {
Some(number) => Ok(number),
None => mismatch(path, "a number"),
}
}
}
impl Shape for Value {
const CLASS: Class = Class::Any;
fn reference() -> ShapeDef {
ShapeDef::new(Kind::Any)
}
fn register(_: &mut Registry) {}
fn build(value: &Value, _: &mut Path) -> Result<Self, Issues> {
Ok(value.clone())
}
}
macro_rules! integer_shape {
($type:ty, $min:expr, $max:expr, $convert:expr) => {
impl Shape for $type {
const CLASS: Class = Class::Integer;
fn reference() -> ShapeDef {
ShapeDef::new(Kind::Integer {
min: Some($min),
exclusive_min: None,
max: Some($max),
})
}
fn register(_: &mut Registry) {}
fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
match value.as_f64() {
Some(number) if number.fract() == 0.0 => {
let convert: fn(i64) -> Option<$type> = $convert;
convert(number as i64)
.map_or_else(|| mismatch(path, "an integer in range"), Ok)
}
_ => mismatch(path, "an integer"),
}
}
}
};
}
integer_shape!(u8, 0.0, f64::from(u8::MAX), |n| u8::try_from(n).ok());
integer_shape!(u16, 0.0, f64::from(u16::MAX), |n| u16::try_from(n).ok());
integer_shape!(u32, 0.0, f64::from(u32::MAX), |n| u32::try_from(n).ok());
integer_shape!(i32, f64::from(i32::MIN), f64::from(i32::MAX), |n| {
i32::try_from(n).ok()
});
integer_shape!(u64, 0.0, MAX_SAFE_INTEGER, |n| u64::try_from(n).ok());
integer_shape!(usize, 0.0, MAX_SAFE_INTEGER, |n| usize::try_from(n).ok());
integer_shape!(i64, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, Some);
impl<T: Shape> Shape for Vec<T> {
const CLASS: Class = Class::Array;
fn reference() -> ShapeDef {
ShapeDef::new(Kind::Array {
items: Box::new(T::reference()),
min_items: None,
max_items: None,
unique: false,
})
}
fn register(registry: &mut Registry) {
T::register(registry);
}
fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
let Some(elements) = value.as_array() else {
return mismatch(path, "an array");
};
let mut built = Vec::with_capacity(elements.len());
for (position, element) in elements.iter().enumerate() {
path.push_index(position);
let item = T::build(element, path);
path.pop();
built.push(item?);
}
Ok(built)
}
}
impl<T: Shape> Shape for Option<T> {
const OPTIONAL: bool = true;
const CLASS: Class = T::CLASS;
fn reference() -> ShapeDef {
T::reference()
}
fn register(registry: &mut Registry) {
T::register(registry);
}
fn absent() -> Option<Self> {
Some(None)
}
fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
T::build(value, path).map(Some)
}
}
impl<T: Shape> Shape for Box<T> {
const CLASS: Class = T::CLASS;
const IS_OBJECT: bool = T::IS_OBJECT;
const KEYS: &'static [&'static str] = T::KEYS;
fn reference() -> ShapeDef {
T::reference()
}
fn definition() -> ShapeDef {
T::definition()
}
fn register(registry: &mut Registry) {
T::register(registry);
}
fn register_members(registry: &mut Registry) {
T::register_members(registry);
}
fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
T::build(value, path).map(Box::new)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Map<T>(pub Vec<(String, T)>);
impl<T: Shape> Shape for Map<T> {
const CLASS: Class = Class::Map;
const CATCH_ALL: bool = true;
fn catch_all_shape() -> Option<ShapeDef> {
Some(T::reference())
}
fn build_rest(value: &Value, path: &mut Path, known: &[&str]) -> Result<Self, Issues> {
let Some(pairs) = value.as_object() else {
return mismatch(path, "an object");
};
let mut built = Vec::new();
for (key, entry) in pairs
.iter()
.filter(|(key, _)| !known.contains(&key.as_str()))
{
path.push_key(key);
let item = T::build(entry, path);
path.pop();
built.push((key.clone(), item?));
}
Ok(Map(built))
}
fn reference() -> ShapeDef {
ShapeDef::new(Kind::Map {
values: Box::new(T::reference()),
min_properties: None,
key_pattern: None,
})
}
fn register(registry: &mut Registry) {
T::register(registry);
}
fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
let Some(pairs) = value.as_object() else {
return mismatch(path, "an object");
};
let mut built = Vec::with_capacity(pairs.len());
for (key, entry) in pairs.iter().filter(|(key, _)| key != "__proto__") {
path.push_key(key);
let item = T::build(entry, path);
path.pop();
built.push((key.clone(), item?));
}
Ok(Map(built))
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct OpenObject(pub Vec<(String, Value)>);
impl Shape for OpenObject {
const CLASS: Class = Class::OpenObject;
const CATCH_ALL: bool = true;
fn catch_all_shape() -> Option<ShapeDef> {
Some(ShapeDef::new(Kind::Any))
}
fn build_rest(value: &Value, path: &mut Path, known: &[&str]) -> Result<Self, Issues> {
match value.as_object() {
Some(pairs) => Ok(OpenObject(
pairs
.iter()
.filter(|(key, _)| !known.contains(&key.as_str()))
.cloned()
.collect(),
)),
None => mismatch(path, "an object"),
}
}
fn reference() -> ShapeDef {
ShapeDef::new(Kind::Object(crate::def::ObjectDef::default()))
}
fn register(_: &mut Registry) {}
fn build(value: &Value, path: &mut Path) -> Result<Self, Issues> {
match value.as_object() {
Some(pairs) => Ok(OpenObject(pairs.to_vec())),
None => mismatch(path, "an object"),
}
}
}