1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
use crate as schemars;
use crate::{JsonSchema, JsonSchemaError, Map, Result, Set};
use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]
#[serde(untagged)]
pub enum Schema {
    Bool(bool),
    Ref(Ref),
    Object(SchemaObject),
}

impl From<SchemaObject> for Schema {
    fn from(o: SchemaObject) -> Self {
        Schema::Object(o)
    }
}

impl From<bool> for Schema {
    fn from(b: bool) -> Self {
        Schema::Bool(b)
    }
}

impl From<Ref> for Schema {
    fn from(r: Ref) -> Self {
        Schema::Ref(r)
    }
}

impl Schema {
    pub fn flatten(self, other: Self) -> Result {
        fn extend<A, E: Extend<A>>(mut a: E, b: impl IntoIterator<Item = A>) -> E {
            a.extend(b);
            a
        }

        let s1 = self.ensure_flattenable()?;
        let s2 = other.ensure_flattenable()?;
        Ok(Schema::Object(SchemaObject {
            schema: s1.schema.or(s2.schema),
            id: s1.id.or(s2.id),
            title: s1.title.or(s2.title),
            description: s1.description.or(s2.description),
            items: s1.items.or(s2.items),
            properties: extend(s1.properties, s2.properties),
            required: extend(s1.required, s2.required),
            definitions: extend(s1.definitions, s2.definitions),
            extensions: extend(s1.extensions, s2.extensions),
            // TODO do the following make sense?
            instance_type: s1.instance_type.or(s2.instance_type),
            enum_values: s1.enum_values.or(s2.enum_values),
            all_of: s1.all_of.or(s2.all_of),
            any_of: s1.any_of.or(s2.any_of),
            one_of: s1.one_of.or(s2.one_of),
            not: s1.not.or(s2.not),
        }))
    }

    fn ensure_flattenable(self) -> Result<SchemaObject> {
        let s = match self {
            Schema::Object(s) => s,
            s => {
                return Err(JsonSchemaError::new(
                    "Only schemas with type `object` can be flattened.",
                    s,
                ))
            }
        };
        match s.instance_type {
            Some(SingleOrVec::Single(ref t)) if **t != InstanceType::Object => {
                Err(JsonSchemaError::new(
                    "Only schemas with type `object` can be flattened.",
                    s.into(),
                ))
            }
            Some(SingleOrVec::Vec(ref t)) if !t.contains(&InstanceType::Object) => {
                Err(JsonSchemaError::new(
                    "Only schemas with type `object` can be flattened.",
                    s.into(),
                ))
            }
            _ => Ok(s),
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]
pub struct Ref {
    #[serde(rename = "$ref")]
    pub reference: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
#[serde(rename_all = "camelCase", default)]
pub struct SchemaObject {
    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,
    #[serde(rename = "$id", skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub instance_type: Option<SingleOrVec<InstanceType>>,
    #[serde(rename = "enum", skip_serializing_if = "Option::is_none")]
    pub enum_values: Option<Vec<Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub items: Option<SingleOrVec<Schema>>,
    #[serde(skip_serializing_if = "Map::is_empty")]
    pub properties: Map<String, Schema>,
    #[serde(skip_serializing_if = "Set::is_empty")]
    pub required: Set<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub all_of: Option<Vec<Schema>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub any_of: Option<Vec<Schema>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub one_of: Option<Vec<Schema>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub not: Option<Box<Schema>>,
    #[serde(skip_serializing_if = "Map::is_empty")]
    pub definitions: Map<String, Schema>,
    #[serde(flatten)]
    pub extensions: Map<String, Value>,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum InstanceType {
    Null,
    Boolean,
    Object,
    Array,
    Number,
    String,
    Integer,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, JsonSchema)]
#[serde(untagged)]
pub enum SingleOrVec<T> {
    Single(Box<T>),
    Vec(Vec<T>),
}

impl<T> From<T> for SingleOrVec<T> {
    fn from(single: T) -> Self {
        SingleOrVec::Single(Box::new(single))
    }
}

impl<T> From<Vec<T>> for SingleOrVec<T> {
    fn from(vec: Vec<T>) -> Self {
        SingleOrVec::Vec(vec)
    }
}