Implement JsonSchema for nonzero signed ints

This commit is contained in:
Graham Esau 2019-10-29 21:40:50 +00:00
parent a35b469475
commit 50f00be97b
6 changed files with 92 additions and 2 deletions

View file

@ -39,6 +39,8 @@ mod chrono;
mod core;
mod ffi;
mod maps;
#[cfg(num_nonzero_signed)]
mod nonzero_signed;
mod nonzero_unsigned;
mod primitives;
mod sequences;

View file

@ -0,0 +1,34 @@
use crate::gen::SchemaGenerator;
use crate::schema::*;
use crate::JsonSchema;
use std::num::*;
macro_rules! nonzero_unsigned_impl {
($type:ty => $primitive:ty) => {
impl JsonSchema for $type {
no_ref_schema!();
fn schema_name() -> String {
stringify!($type).to_owned()
}
fn json_schema(gen: &mut SchemaGenerator) -> Schema {
let zero_schema: Schema = SchemaObject {
const_value: Some(0.into()),
..Default::default()
}
.into();
let mut schema: SchemaObject = <$primitive>::json_schema(gen).into();
schema.subschemas().not = Some(Box::from(zero_schema));
schema.into()
}
}
};
}
nonzero_unsigned_impl!(NonZeroI8 => i8);
nonzero_unsigned_impl!(NonZeroI16 => i16);
nonzero_unsigned_impl!(NonZeroI32 => i32);
nonzero_unsigned_impl!(NonZeroI64 => i64);
nonzero_unsigned_impl!(NonZeroI128 => i128);
nonzero_unsigned_impl!(NonZeroIsize => isize);

View file

@ -35,7 +35,7 @@ mod tests {
use pretty_assertions::assert_eq;
#[test]
fn schema_for_atomics() {
fn schema_for_nonzero_u32() {
let schema = schema_object_for::<NonZeroU32>();
assert_eq!(schema.number.unwrap().minimum, Some(1.0));
assert_eq!(schema.instance_type, Some(InstanceType::Integer.into()));

View file

@ -16,7 +16,7 @@ impl JsonSchema for Value {
}
}
forward_impl!(Map<String, Value> => BTreeMap::<String, Value>);
forward_impl!(Map<String, Value> => BTreeMap<String, Value>);
impl JsonSchema for Number {
no_ref_schema!();

View file

@ -0,0 +1,33 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "MyStruct",
"type": "object",
"required": [
"nonzero_signed",
"nonzero_unsigned",
"signed",
"unsigned"
],
"properties": {
"nonzero_signed": {
"type": "integer",
"format": "int32",
"not": {
"const": 0
}
},
"nonzero_unsigned": {
"type": "integer",
"format": "uint32",
"minimum": 1.0
},
"signed": {
"type": "integer",
"format": "int32"
},
"unsigned": {
"type": "integer",
"format": "uint32"
}
}
}

View file

@ -0,0 +1,21 @@
mod util;
#[cfg(num_nonzero_signed)]
mod nonzero_ints {
use super::*;
use schemars::JsonSchema;
use util::*;
#[derive(Debug, JsonSchema)]
struct MyStruct {
unsigned: u32,
nonzero_unsigned: std::num::NonZeroU32,
signed: i32,
nonzero_signed: std::num::NonZeroI32,
}
#[test]
fn nonzero_ints() -> TestResult {
test_default_generated_schema::<MyStruct>("nonzero_ints")
}
}