schemars/json_schema_impls/
array.rs

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