schemars/json_schema_impls/
array.rs
1use crate::gen::SchemaGenerator;
2use crate::schema::*;
3use crate::JsonSchema;
4use std::borrow::Cow;
5
6impl<T> JsonSchema for [T; 0] {
8 no_ref_schema!();
9
10 fn schema_name() -> String {
11 "EmptyArray".to_owned()
12 }
13
14 fn schema_id() -> Cow<'static, str> {
15 Cow::Borrowed("[]")
16 }
17
18 fn json_schema(_: &mut SchemaGenerator) -> Schema {
19 SchemaObject {
20 instance_type: Some(InstanceType::Array.into()),
21 array: Some(Box::new(ArrayValidation {
22 max_items: Some(0),
23 ..Default::default()
24 })),
25 ..Default::default()
26 }
27 .into()
28 }
29}
30
31macro_rules! array_impls {
32 ($($len:tt)+) => {
33 $(
34 impl<T: JsonSchema> JsonSchema for [T; $len] {
35 no_ref_schema!();
36
37 fn schema_name() -> String {
38 format!("Array_size_{}_of_{}", $len, T::schema_name())
39 }
40
41 fn schema_id() -> Cow<'static, str> {
42 Cow::Owned(
43 format!("[{}; {}]", $len, T::schema_id()))
44 }
45
46 fn json_schema(gen: &mut SchemaGenerator) -> Schema {
47 SchemaObject {
48 instance_type: Some(InstanceType::Array.into()),
49 array: Some(Box::new(ArrayValidation {
50 items: Some(gen.subschema_for::<T>().into()),
51 max_items: Some($len),
52 min_items: Some($len),
53 ..Default::default()
54 })),
55 ..Default::default()
56 }
57 .into()
58 }
59 }
60 )+
61 }
62}
63
64array_impls! {
65 1 2 3 4 5 6 7 8 9 10
66 11 12 13 14 15 16 17 18 19 20
67 21 22 23 24 25 26 27 28 29 30
68 31 32
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74 use crate::tests::{schema_for, schema_object_for};
75 use pretty_assertions::assert_eq;
76
77 #[test]
78 fn schema_for_array() {
79 let schema = schema_object_for::<[i32; 8]>();
80 assert_eq!(
81 schema.instance_type,
82 Some(SingleOrVec::from(InstanceType::Array))
83 );
84 let array_validation = schema.array.unwrap();
85 assert_eq!(
86 array_validation.items,
87 Some(SingleOrVec::from(schema_for::<i32>()))
88 );
89 assert_eq!(array_validation.max_items, Some(8));
90 assert_eq!(array_validation.min_items, Some(8));
91 }
92
93 struct SomeStruct;
95
96 #[test]
97 fn schema_for_empty_array() {
98 let schema = schema_object_for::<[SomeStruct; 0]>();
99 assert_eq!(
100 schema.instance_type,
101 Some(SingleOrVec::from(InstanceType::Array))
102 );
103 let array_validation = schema.array.unwrap();
104 assert_eq!(array_validation.max_items, Some(0));
105 }
106}