1use indexmap::IndexMap;
4use serde::de::Error as _;
5use serde::ser::SerializeMap;
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7use serde_json::{Map, Value};
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
11pub enum Type {
12 Object,
14 String,
16 Integer,
18 Number,
20 Boolean,
22 Array,
24 Null,
26}
27
28impl Type {
29 pub const fn as_str(self) -> &'static str {
31 match self {
32 Self::Object => "object",
33 Self::String => "string",
34 Self::Integer => "integer",
35 Self::Number => "number",
36 Self::Boolean => "boolean",
37 Self::Array => "array",
38 Self::Null => "null",
39 }
40 }
41
42 fn parse(name: &str) -> Option<Self> {
43 Some(match name {
44 "object" => Self::Object,
45 "string" => Self::String,
46 "integer" => Self::Integer,
47 "number" => Self::Number,
48 "boolean" => Self::Boolean,
49 "array" => Self::Array,
50 "null" => Self::Null,
51 _ => return None,
52 })
53 }
54}
55
56#[derive(Clone, Debug, PartialEq, Eq)]
58pub enum SchemaType {
59 One(Type),
61 Many(Vec<Type>),
63}
64
65impl SchemaType {
66 fn to_value(&self) -> Value {
67 match self {
68 Self::One(ty) => Value::from(ty.as_str()),
69 Self::Many(types) => Value::Array(
70 types
71 .iter()
72 .map(|ty| Value::from(ty.as_str()))
73 .collect::<Vec<_>>(),
74 ),
75 }
76 }
77
78 fn from_value(value: &Value) -> Option<Self> {
79 match value {
80 Value::String(name) => Type::parse(name).map(Self::One),
81 Value::Array(names) => names
82 .iter()
83 .map(|name| name.as_str().and_then(Type::parse))
84 .collect::<Option<Vec<_>>>()
85 .map(Self::Many),
86 _ => None,
87 }
88 }
89}
90
91#[derive(Clone, Debug, PartialEq)]
94pub enum Subschema {
95 Bool(bool),
97 Schema(Box<Schema>),
99}
100
101impl Subschema {
102 fn from_value(value: &Value) -> Option<Self> {
103 match value {
104 Value::Bool(allowed) => Some(Self::Bool(*allowed)),
105 Value::Object(_) => Schema::from_value(value.clone())
106 .ok()
107 .map(|schema| Self::Schema(Box::new(schema))),
108 _ => None,
109 }
110 }
111}
112
113impl Serialize for Subschema {
114 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
115 match self {
116 Self::Bool(allowed) => serializer.serialize_bool(*allowed),
117 Self::Schema(schema) => schema.serialize(serializer),
118 }
119 }
120}
121
122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
124pub struct NotASchema;
125
126impl std::fmt::Display for NotASchema {
127 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128 f.write_str("a schema must be a JSON object")
129 }
130}
131
132impl std::error::Error for NotASchema {}
133
134#[doc(hidden)]
138#[derive(Clone, Copy, Debug, Default)]
139pub struct RustType(pub Option<&'static str>);
140
141impl PartialEq for RustType {
142 fn eq(&self, _other: &Self) -> bool {
143 true
144 }
145}
146
147#[derive(Clone, Debug, Default, PartialEq)]
151pub struct Schema {
152 #[doc(hidden)]
153 pub rust_type: RustType,
154 pub reference: Option<String>,
156 pub one_of: Vec<Schema>,
158 pub any_of: Vec<Schema>,
160 pub all_of: Vec<Schema>,
162 pub schema_type: Option<SchemaType>,
164 pub title: Option<String>,
166 pub format: Option<String>,
168 pub items: Option<Subschema>,
170 pub prefix_items: Vec<Schema>,
172 pub description: Option<String>,
174 pub default: Option<Value>,
176 pub enum_values: Vec<Value>,
178 pub const_value: Option<Value>,
180 pub required: Vec<String>,
182 pub properties: IndexMap<String, Schema>,
184 pub additional_properties: Option<Subschema>,
186 pub property_names: Option<Box<Schema>>,
188 pub deprecated: Option<bool>,
190 pub example: Option<Value>,
192 pub examples: Vec<Value>,
194 pub write_only: Option<bool>,
196 pub read_only: Option<bool>,
198 pub maximum: Option<Value>,
200 pub minimum: Option<Value>,
202 pub max_length: Option<u64>,
204 pub min_length: Option<u64>,
206 pub pattern: Option<String>,
208 pub max_items: Option<u64>,
210 pub min_items: Option<u64>,
212 pub unique_items: Option<bool>,
214 pub extra: Map<String, Value>,
216}
217
218impl Schema {
219 pub fn of_type(ty: Type) -> Self {
221 Self {
222 schema_type: Some(SchemaType::One(ty)),
223 ..Self::default()
224 }
225 }
226
227 pub fn object() -> Self {
229 Self::of_type(Type::Object)
230 }
231
232 pub fn string() -> Self {
234 Self::of_type(Type::String)
235 }
236
237 pub fn null() -> Self {
239 Self::of_type(Type::Null)
240 }
241
242 pub fn array(items: Schema) -> Self {
244 Self {
245 items: Some(Subschema::Schema(Box::new(items))),
246 ..Self::of_type(Type::Array)
247 }
248 }
249
250 pub fn map(keys: Schema, values: Schema) -> Self {
252 Self {
253 additional_properties: Some(Subschema::Schema(Box::new(values))),
254 property_names: Some(Box::new(keys)),
255 ..Self::object()
256 }
257 }
258
259 pub fn reference_to(name: &str) -> Self {
261 Self {
262 reference: Some(format!("#/components/schemas/{name}")),
263 ..Self::default()
264 }
265 }
266
267 pub fn one_of(items: Vec<Schema>) -> Self {
269 Self {
270 one_of: items,
271 ..Self::default()
272 }
273 }
274
275 pub fn all_of(items: Vec<Schema>) -> Self {
277 Self {
278 all_of: items,
279 ..Self::default()
280 }
281 }
282
283 pub fn never() -> Self {
285 let mut schema = Self::default();
286 schema
287 .extra
288 .insert("not".to_owned(), Value::Object(Map::new()));
289 schema
290 }
291
292 pub fn string_enum<I, S>(values: I) -> Self
294 where
295 I: IntoIterator<Item = S>,
296 S: Into<String>,
297 {
298 Self {
299 enum_values: values
300 .into_iter()
301 .map(|value| Value::String(value.into()))
302 .collect(),
303 ..Self::string()
304 }
305 }
306
307 #[must_use]
309 pub fn property(mut self, name: &str, schema: Schema, required: bool) -> Self {
310 self.properties.insert(name.to_owned(), schema);
311 if required {
312 self.required.push(name.to_owned());
313 }
314 self
315 }
316
317 #[must_use]
319 pub fn description(mut self, text: impl Into<String>) -> Self {
320 self.description = Some(text.into());
321 self
322 }
323
324 #[must_use]
326 pub fn example(mut self, value: Value) -> Self {
327 self.example = Some(value);
328 self
329 }
330
331 #[must_use]
333 pub fn examples(mut self, values: Vec<Value>) -> Self {
334 self.examples = values;
335 self
336 }
337
338 #[must_use]
340 pub fn read_only(mut self) -> Self {
341 self.read_only = Some(true);
342 self
343 }
344
345 #[must_use]
347 pub fn write_only(mut self) -> Self {
348 self.write_only = Some(true);
349 self
350 }
351
352 #[must_use]
354 pub fn default_value(mut self, value: Value) -> Self {
355 self.default = Some(value);
356 self
357 }
358
359 #[must_use]
361 pub fn title(mut self, text: impl Into<String>) -> Self {
362 self.title = Some(text.into());
363 self
364 }
365
366 #[must_use]
368 pub fn deprecated(mut self) -> Self {
369 self.deprecated = Some(true);
370 self
371 }
372
373 #[must_use]
375 pub fn no_additional_properties(mut self) -> Self {
376 self.additional_properties = Some(Subschema::Bool(false));
377 self
378 }
379
380 #[must_use]
383 pub fn format(self, format: impl Into<String>) -> Self {
384 let format = format.into();
385 self.at_elements(|schema| schema.format = Some(format))
386 }
387
388 #[must_use]
390 pub fn minimum(self, value: Value) -> Self {
391 self.at_elements(|schema| schema.minimum = Some(value))
392 }
393
394 #[must_use]
396 pub fn maximum(self, value: Value) -> Self {
397 self.at_elements(|schema| schema.maximum = Some(value))
398 }
399
400 #[must_use]
404 pub fn nullable(mut self) -> Self {
405 match self.schema_type.take() {
406 Some(SchemaType::One(Type::Null)) => {
407 self.schema_type = Some(SchemaType::One(Type::Null));
408 self
409 }
410 Some(SchemaType::One(ty)) => {
411 self.schema_type = Some(SchemaType::Many(vec![ty, Type::Null]));
412 self
413 }
414 Some(SchemaType::Many(mut types)) => {
415 if !types.contains(&Type::Null) {
416 types.push(Type::Null);
417 }
418 self.schema_type = Some(SchemaType::Many(types));
419 self
420 }
421 None if self.is_nullable_union() || self.allows_anything() => self,
422 None => Self::one_of(vec![self, Self::null()]),
423 }
424 }
425
426 #[must_use]
430 pub fn described(mut self, text: impl Into<String>) -> Self {
431 if self.is_nullable_union()
432 && let Some(first) = self.one_of.first_mut()
433 && first.reference.is_some()
434 {
435 first.description = Some(text.into());
436 return self;
437 }
438 self.description = Some(text.into());
439 self
440 }
441
442 pub fn to_value(&self) -> Value {
444 serde_json::to_value(self).unwrap_or_default()
445 }
446
447 pub fn from_value(value: Value) -> Result<Self, NotASchema> {
455 let Value::Object(object) = value else {
456 return Err(NotASchema);
457 };
458 let mut schema = Self::default();
459 for (keyword, value) in object {
460 if !schema.read_keyword(&keyword, &value) {
461 schema.extra.insert(keyword, value);
462 }
463 }
464 Ok(schema)
465 }
466
467 fn is_nullable_union(&self) -> bool {
469 self.one_of
470 .iter()
471 .any(|item| item.schema_type == Some(SchemaType::One(Type::Null)))
472 }
473
474 fn allows_anything(&self) -> bool {
476 self.reference.is_none()
477 && self.one_of.is_empty()
478 && self.any_of.is_empty()
479 && self.all_of.is_empty()
480 && self.enum_values.is_empty()
481 && self.const_value.is_none()
482 && self.properties.is_empty()
483 && self.items.is_none()
484 }
485
486 fn at_elements(mut self, set: impl FnOnce(&mut Schema)) -> Self {
487 fn apply(schema: &mut Schema, set: impl FnOnce(&mut Schema)) {
488 if let Some(Subschema::Schema(items)) = &mut schema.items {
489 apply(items, set);
490 } else if let Some(Subschema::Schema(values)) = &mut schema.additional_properties {
491 apply(values, set);
492 } else {
493 set(schema);
494 }
495 }
496 apply(&mut self, set);
497 self
498 }
499
500 fn read_keyword(&mut self, keyword: &str, value: &Value) -> bool {
503 fn text(slot: &mut Option<String>, value: &Value) -> bool {
504 value.as_str().is_some_and(|text| {
505 *slot = Some(text.to_owned());
506 true
507 })
508 }
509 fn flag(slot: &mut Option<bool>, value: &Value) -> bool {
510 value.as_bool().is_some_and(|flag| {
511 *slot = Some(flag);
512 true
513 })
514 }
515 fn count(slot: &mut Option<u64>, value: &Value) -> bool {
516 value.as_u64().is_some_and(|count| {
517 *slot = Some(count);
518 true
519 })
520 }
521 fn number(slot: &mut Option<Value>, value: &Value) -> bool {
522 value.is_number() && {
523 *slot = Some(value.clone());
524 true
525 }
526 }
527 fn list(slot: &mut Vec<Schema>, value: &Value) -> bool {
528 let Some(items) = value.as_array().filter(|items| !items.is_empty()) else {
529 return false;
530 };
531 let Some(schemas) = items
532 .iter()
533 .map(|item| Schema::from_value(item.clone()).ok())
534 .collect::<Option<Vec<_>>>()
535 else {
536 return false;
537 };
538 *slot = schemas;
539 true
540 }
541 fn values(slot: &mut Vec<Value>, value: &Value) -> bool {
542 value
543 .as_array()
544 .filter(|values| !values.is_empty())
545 .is_some_and(|values| {
546 slot.clone_from(values);
547 true
548 })
549 }
550 fn sub(slot: &mut Option<Subschema>, value: &Value) -> bool {
551 Subschema::from_value(value).is_some_and(|sub| {
552 *slot = Some(sub);
553 true
554 })
555 }
556
557 match keyword {
558 "$ref" => text(&mut self.reference, value),
559 "oneOf" => list(&mut self.one_of, value),
560 "anyOf" => list(&mut self.any_of, value),
561 "allOf" => list(&mut self.all_of, value),
562 "type" => SchemaType::from_value(value).is_some_and(|ty| {
563 self.schema_type = Some(ty);
564 true
565 }),
566 "title" => text(&mut self.title, value),
567 "format" => text(&mut self.format, value),
568 "items" => sub(&mut self.items, value),
569 "prefixItems" => list(&mut self.prefix_items, value),
570 "description" => text(&mut self.description, value),
571 "default" => {
572 self.default = Some(value.clone());
573 true
574 }
575 "enum" => values(&mut self.enum_values, value),
576 "const" => {
577 self.const_value = Some(value.clone());
578 true
579 }
580 "required" => value
581 .as_array()
582 .filter(|names| !names.is_empty())
583 .and_then(|names| {
584 names
585 .iter()
586 .map(|name| name.as_str().map(str::to_owned))
587 .collect::<Option<Vec<_>>>()
588 })
589 .is_some_and(|names| {
590 self.required = names;
591 true
592 }),
593 "properties" => value
594 .as_object()
595 .filter(|properties| !properties.is_empty())
596 .and_then(|properties| {
597 properties
598 .iter()
599 .map(|(name, schema)| {
600 Schema::from_value(schema.clone())
601 .ok()
602 .map(|schema| (name.clone(), schema))
603 })
604 .collect::<Option<IndexMap<_, _>>>()
605 })
606 .is_some_and(|properties| {
607 self.properties = properties;
608 true
609 }),
610 "additionalProperties" => sub(&mut self.additional_properties, value),
611 "propertyNames" => Schema::from_value(value.clone()).is_ok_and(|schema| {
612 self.property_names = Some(Box::new(schema));
613 true
614 }),
615 "deprecated" => flag(&mut self.deprecated, value),
616 "example" => {
617 self.example = Some(value.clone());
618 true
619 }
620 "examples" => values(&mut self.examples, value),
621 "writeOnly" => flag(&mut self.write_only, value),
622 "readOnly" => flag(&mut self.read_only, value),
623 "maximum" => number(&mut self.maximum, value),
624 "minimum" => number(&mut self.minimum, value),
625 "maxLength" => count(&mut self.max_length, value),
626 "minLength" => count(&mut self.min_length, value),
627 "pattern" => text(&mut self.pattern, value),
628 "maxItems" => count(&mut self.max_items, value),
629 "minItems" => count(&mut self.min_items, value),
630 "uniqueItems" => flag(&mut self.unique_items, value),
631 _ => false,
632 }
633 }
634}
635
636impl Serialize for Schema {
637 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
638 fn some<M: SerializeMap, T: Serialize>(
639 map: &mut M,
640 key: &str,
641 value: Option<&T>,
642 ) -> Result<(), M::Error> {
643 match value {
644 Some(value) => map.serialize_entry(key, value),
645 None => Ok(()),
646 }
647 }
648 fn many<M: SerializeMap, T: Serialize>(
649 map: &mut M,
650 key: &str,
651 values: &[T],
652 ) -> Result<(), M::Error> {
653 if values.is_empty() {
654 Ok(())
655 } else {
656 map.serialize_entry(key, values)
657 }
658 }
659
660 let mut map = serializer.serialize_map(None)?;
661 some(&mut map, "$ref", self.reference.as_ref())?;
662 many(&mut map, "oneOf", &self.one_of)?;
663 many(&mut map, "anyOf", &self.any_of)?;
664 many(&mut map, "allOf", &self.all_of)?;
665 some(
666 &mut map,
667 "type",
668 self.schema_type.as_ref().map(SchemaType::to_value).as_ref(),
669 )?;
670 some(&mut map, "title", self.title.as_ref())?;
671 some(&mut map, "format", self.format.as_ref())?;
672 some(&mut map, "items", self.items.as_ref())?;
673 many(&mut map, "prefixItems", &self.prefix_items)?;
674 some(&mut map, "description", self.description.as_ref())?;
675 some(&mut map, "default", self.default.as_ref())?;
676 many(&mut map, "enum", &self.enum_values)?;
677 some(&mut map, "const", self.const_value.as_ref())?;
678 many(&mut map, "required", &self.required)?;
679 if !self.properties.is_empty() {
680 map.serialize_entry("properties", &self.properties)?;
681 }
682 some(
683 &mut map,
684 "additionalProperties",
685 self.additional_properties.as_ref(),
686 )?;
687 some(&mut map, "propertyNames", self.property_names.as_ref())?;
688 some(&mut map, "deprecated", self.deprecated.as_ref())?;
689 some(&mut map, "example", self.example.as_ref())?;
690 many(&mut map, "examples", &self.examples)?;
691 some(&mut map, "writeOnly", self.write_only.as_ref())?;
692 some(&mut map, "readOnly", self.read_only.as_ref())?;
693 some(&mut map, "maximum", self.maximum.as_ref())?;
694 some(&mut map, "minimum", self.minimum.as_ref())?;
695 some(&mut map, "maxLength", self.max_length.as_ref())?;
696 some(&mut map, "minLength", self.min_length.as_ref())?;
697 some(&mut map, "pattern", self.pattern.as_ref())?;
698 some(&mut map, "maxItems", self.max_items.as_ref())?;
699 some(&mut map, "minItems", self.min_items.as_ref())?;
700 some(&mut map, "uniqueItems", self.unique_items.as_ref())?;
701 for (keyword, value) in &self.extra {
702 map.serialize_entry(keyword, value)?;
703 }
704 map.end()
705 }
706}
707
708impl<'de> Deserialize<'de> for Schema {
709 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
710 Self::from_value(Value::deserialize(deserializer)?).map_err(D::Error::custom)
711 }
712}
713
714#[cfg(test)]
715mod tests {
716 use serde_json::json;
717
718 use super::*;
719
720 #[test]
721 fn nullable_adds_null_to_a_type_or_wraps_a_reference() {
722 assert_eq!(
723 Schema::string().nullable().to_value(),
724 json!({"type": ["string", "null"]})
725 );
726 assert_eq!(
727 Schema::reference_to("Deal").nullable().to_value(),
728 json!({"oneOf": [{"$ref": "#/components/schemas/Deal"}, {"type": "null"}]})
729 );
730 assert_eq!(Schema::default().nullable().to_value(), json!({}));
731 let twice = Schema::reference_to("Deal").nullable().nullable();
732 assert_eq!(twice, Schema::reference_to("Deal").nullable());
733 }
734
735 #[test]
736 fn a_description_goes_on_the_reference_of_a_nullable_reference() {
737 assert_eq!(
738 Schema::reference_to("Deal")
739 .nullable()
740 .described("The deal.")
741 .to_value(),
742 json!({"oneOf": [
743 {"$ref": "#/components/schemas/Deal", "description": "The deal."},
744 {"type": "null"},
745 ]})
746 );
747 }
748
749 #[test]
750 fn format_and_limits_go_on_the_elements() {
751 assert_eq!(
752 Schema::array(Schema::string()).format("uuid").to_value(),
753 json!({"type": "array", "items": {"type": "string", "format": "uuid"}})
754 );
755 }
756
757 #[test]
758 fn every_json_object_is_read_and_written_back() {
759 let value = json!({
760 "type": ["string", 7],
761 "enum": "not a list",
762 "required": [],
763 "oneOf": [],
764 "x-navree-flag": {"name": "beta"},
765 "properties": {"a": "not a schema"},
766 "$ref": 3,
767 });
768 let schema = Schema::from_value(value.clone()).unwrap();
769 assert_eq!(schema.to_value(), value);
770 }
771
772 #[test]
773 fn a_schema_survives_json() {
774 let value = json!({
775 "type": "object",
776 "description": "A deal.",
777 "required": ["id"],
778 "properties": {
779 "id": {"type": "string", "format": "uuid"},
780 "stage": {"oneOf": [{"$ref": "#/components/schemas/Stage"}, {"type": "null"}]},
781 "tags": {"type": "array", "items": {"type": "string"}, "uniqueItems": true},
782 },
783 "additionalProperties": false,
784 });
785 let schema: Schema = serde_json::from_value(value.clone()).unwrap();
786 assert_eq!(serde_json::to_value(&schema).unwrap(), value);
787 }
788
789 #[test]
790 fn only_an_object_is_a_schema() {
791 assert_eq!(Schema::from_value(json!([1])), Err(NotASchema));
792 assert_eq!(Schema::from_value(json!(true)), Err(NotASchema));
793 }
794}