1use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5
6#[derive(Debug, Clone, Serialize, Deserialize)]
8#[serde(untagged)]
9pub enum Schema {
10 Boolean(bool),
12 Ref(RefSchema),
14 Enum(EnumSchema),
16 OneOf(OneOfSchema),
18 AnyOf(AnyOfSchema),
20 #[serde(serialize_with = "serialize_array_schema")]
22 Array(ArraySchema),
23 #[serde(serialize_with = "serialize_primitive_schema")]
25 Primitive(PrimitiveSchema),
26 #[serde(serialize_with = "serialize_object_schema")]
28 Object(ObjectSchema),
29}
30
31#[derive(Serialize)]
32struct TypedSchema<'a, T> {
33 #[serde(rename = "type")]
34 kind: &'static str,
35 #[serde(flatten)]
36 schema: &'a T,
37}
38
39fn serialize_primitive_schema<S: serde::Serializer>(
40 schema: &PrimitiveSchema,
41 serializer: S,
42) -> Result<S::Ok, S::Error> {
43 if schema.nullable {
44 let mut non_null = schema.clone();
45 non_null.nullable = false;
46 Schema::any_of(vec![Schema::Primitive(non_null), <()>::schema()]).serialize(serializer)
47 } else {
48 schema.serialize(serializer)
49 }
50}
51
52fn serialize_object_schema<S: serde::Serializer>(
53 schema: &ObjectSchema,
54 serializer: S,
55) -> Result<S::Ok, S::Error> {
56 TypedSchema {
57 kind: "object",
58 schema,
59 }
60 .serialize(serializer)
61}
62
63fn serialize_array_schema<S: serde::Serializer>(
64 schema: &ArraySchema,
65 serializer: S,
66) -> Result<S::Ok, S::Error> {
67 TypedSchema {
68 kind: "array",
69 schema,
70 }
71 .serialize(serializer)
72}
73
74impl Schema {
75 pub fn string() -> Self {
77 Schema::Primitive(PrimitiveSchema::string())
78 }
79
80 pub fn integer(format: Option<&str>) -> Self {
82 Schema::Primitive(PrimitiveSchema::integer(format))
83 }
84
85 pub fn number(format: Option<&str>) -> Self {
87 Schema::Primitive(PrimitiveSchema::number(format))
88 }
89
90 pub fn boolean() -> Self {
92 Schema::Primitive(PrimitiveSchema::boolean())
93 }
94
95 pub fn reference(name: &str) -> Self {
97 Schema::Ref(RefSchema {
98 reference: format!("#/components/schemas/{name}"),
99 })
100 }
101
102 pub fn array(items: Schema) -> Self {
104 Schema::Array(ArraySchema {
105 items: Box::new(items),
106 min_items: None,
107 max_items: None,
108 })
109 }
110
111 pub fn object(properties: HashMap<String, Schema>, required: Vec<String>) -> Self {
113 Schema::Object(ObjectSchema {
114 title: None,
115 description: None,
116 properties,
117 required,
118 additional_properties: None,
119 })
120 }
121
122 #[must_use]
124 pub fn nullable(mut self) -> Self {
125 if let Schema::Primitive(ref mut p) = self {
126 p.nullable = true;
127 self
128 } else {
129 Self::any_of(vec![self, <()>::schema()])
130 }
131 }
132
133 #[must_use]
135 pub fn with_title(mut self, title: impl Into<String>) -> Self {
136 if let Schema::Object(ref mut o) = self {
137 o.title = Some(title.into());
138 }
139 self
140 }
141
142 #[must_use]
144 pub fn with_description(mut self, description: impl Into<String>) -> Self {
145 if let Schema::Object(ref mut o) = self {
146 o.description = Some(description.into());
147 }
148 self
149 }
150
151 pub fn string_enum(values: Vec<String>) -> Self {
153 Schema::Enum(EnumSchema {
154 schema_type: SchemaType::String,
155 enum_values: values,
156 })
157 }
158
159 pub fn one_of(schemas: Vec<Schema>) -> Self {
161 Schema::OneOf(OneOfSchema { one_of: schemas })
162 }
163
164 pub fn any_of(schemas: Vec<Schema>) -> Self {
166 Schema::AnyOf(AnyOfSchema { any_of: schemas })
167 }
168}
169
170#[derive(Debug, Clone, Serialize, Deserialize)]
172pub struct RefSchema {
173 #[serde(rename = "$ref")]
175 pub reference: String,
176}
177
178#[derive(Debug, Clone, Default, Serialize, Deserialize)]
180pub struct ObjectSchema {
181 #[serde(default, skip_serializing_if = "Option::is_none")]
183 pub title: Option<String>,
184 #[serde(default, skip_serializing_if = "Option::is_none")]
186 pub description: Option<String>,
187 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
189 pub properties: HashMap<String, Schema>,
190 #[serde(default, skip_serializing_if = "Vec::is_empty")]
192 pub required: Vec<String>,
193 #[serde(
195 rename = "additionalProperties",
196 default,
197 skip_serializing_if = "Option::is_none"
198 )]
199 pub additional_properties: Option<Box<Schema>>,
200}
201
202#[derive(Debug, Clone, Serialize, Deserialize)]
204pub struct ArraySchema {
205 pub items: Box<Schema>,
207 #[serde(rename = "minItems", default, skip_serializing_if = "Option::is_none")]
209 pub min_items: Option<usize>,
210 #[serde(rename = "maxItems", default, skip_serializing_if = "Option::is_none")]
212 pub max_items: Option<usize>,
213}
214
215#[derive(Debug, Clone, Serialize, Deserialize)]
217pub struct EnumSchema {
218 #[serde(rename = "type")]
220 pub schema_type: SchemaType,
221 #[serde(rename = "enum")]
223 pub enum_values: Vec<String>,
224}
225
226#[derive(Debug, Clone, Serialize, Deserialize)]
228pub struct OneOfSchema {
229 #[serde(rename = "oneOf")]
231 pub one_of: Vec<Schema>,
232}
233
234#[derive(Debug, Clone, Serialize, Deserialize)]
236pub struct AnyOfSchema {
237 #[serde(rename = "anyOf")]
239 pub any_of: Vec<Schema>,
240}
241
242#[derive(Debug, Clone, Serialize, Deserialize)]
244pub struct PrimitiveSchema {
245 #[serde(rename = "type")]
247 pub schema_type: SchemaType,
248 #[serde(default, skip_serializing_if = "Option::is_none")]
250 pub format: Option<String>,
251 #[serde(default, skip_serializing_if = "is_false")]
253 pub nullable: bool,
254}
255
256impl PrimitiveSchema {
257 pub fn string() -> Self {
259 Self {
260 schema_type: SchemaType::String,
261 format: None,
262 nullable: false,
263 }
264 }
265
266 pub fn integer(format: Option<&str>) -> Self {
268 Self {
269 schema_type: SchemaType::Integer,
270 format: format.map(String::from),
271 nullable: false,
272 }
273 }
274
275 pub fn number(format: Option<&str>) -> Self {
277 Self {
278 schema_type: SchemaType::Number,
279 format: format.map(String::from),
280 nullable: false,
281 }
282 }
283
284 pub fn boolean() -> Self {
286 Self {
287 schema_type: SchemaType::Boolean,
288 format: None,
289 nullable: false,
290 }
291 }
292}
293
294#[allow(clippy::trivially_copy_pass_by_ref)]
295fn is_false(b: &bool) -> bool {
296 !*b
297}
298
299#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
301#[serde(rename_all = "lowercase")]
302pub enum SchemaType {
303 String,
305 Number,
307 Integer,
309 Boolean,
311 Null,
313}
314
315pub trait JsonSchema {
317 fn schema() -> Schema;
319
320 #[must_use]
322 fn schema_name() -> Option<&'static str> {
323 None
324 }
325}
326
327impl JsonSchema for String {
329 fn schema() -> Schema {
330 Schema::Primitive(PrimitiveSchema {
331 schema_type: SchemaType::String,
332 format: None,
333 nullable: false,
334 })
335 }
336}
337
338impl JsonSchema for i64 {
339 fn schema() -> Schema {
340 Schema::Primitive(PrimitiveSchema {
341 schema_type: SchemaType::Integer,
342 format: Some("int64".to_string()),
343 nullable: false,
344 })
345 }
346}
347
348impl JsonSchema for i32 {
349 fn schema() -> Schema {
350 Schema::Primitive(PrimitiveSchema {
351 schema_type: SchemaType::Integer,
352 format: Some("int32".to_string()),
353 nullable: false,
354 })
355 }
356}
357
358impl JsonSchema for f64 {
359 fn schema() -> Schema {
360 Schema::Primitive(PrimitiveSchema {
361 schema_type: SchemaType::Number,
362 format: Some("double".to_string()),
363 nullable: false,
364 })
365 }
366}
367
368impl JsonSchema for bool {
369 fn schema() -> Schema {
370 Schema::Primitive(PrimitiveSchema {
371 schema_type: SchemaType::Boolean,
372 format: None,
373 nullable: false,
374 })
375 }
376}
377
378macro_rules! integer_schema {
379 ($ty:ty, $format:expr) => {
380 impl JsonSchema for $ty {
381 fn schema() -> Schema {
382 Schema::integer($format)
383 }
384 }
385 };
386}
387
388integer_schema!(i8, Some("int8"));
389integer_schema!(i16, Some("int16"));
390integer_schema!(u8, Some("uint8"));
391integer_schema!(u16, Some("uint16"));
392integer_schema!(u32, Some("uint32"));
393integer_schema!(u64, Some("uint64"));
394integer_schema!(isize, Some("int64"));
395integer_schema!(usize, Some("uint64"));
396integer_schema!(i128, None);
397integer_schema!(u128, None);
398
399impl JsonSchema for f32 {
400 fn schema() -> Schema {
401 Schema::number(Some("float"))
402 }
403}
404
405impl JsonSchema for &str {
406 fn schema() -> Schema {
407 Schema::string()
408 }
409}
410
411impl JsonSchema for () {
412 fn schema() -> Schema {
413 Schema::Primitive(PrimitiveSchema {
414 schema_type: SchemaType::Null,
415 format: None,
416 nullable: false,
417 })
418 }
419}
420
421impl JsonSchema for serde_json::Value {
422 fn schema() -> Schema {
423 Schema::Boolean(true)
424 }
425}
426
427impl<T: JsonSchema, S: std::hash::BuildHasher> JsonSchema for HashMap<String, T, S> {
428 fn schema() -> Schema {
429 Schema::Object(ObjectSchema {
430 additional_properties: Some(Box::new(T::schema())),
431 ..ObjectSchema::default()
432 })
433 }
434}
435
436impl<T: JsonSchema> JsonSchema for std::collections::BTreeMap<String, T> {
437 fn schema() -> Schema {
438 <HashMap<String, T>>::schema()
439 }
440}
441
442impl<T: JsonSchema> JsonSchema for Option<T> {
443 fn schema() -> Schema {
444 T::schema().nullable()
445 }
446}
447
448impl<T: JsonSchema> JsonSchema for Vec<T> {
449 fn schema() -> Schema {
450 Schema::Array(ArraySchema {
451 items: Box::new(T::schema()),
452 min_items: None,
453 max_items: None,
454 })
455 }
456}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
461
462 #[test]
463 fn bounded_array_uses_json_schema_keywords_and_round_trips() {
464 let schema = Schema::Array(ArraySchema {
465 items: Box::new(Schema::integer(None)),
466 min_items: Some(2),
467 max_items: Some(4),
468 });
469 let json = serde_json::to_value(schema).unwrap();
470 assert_eq!(json["type"], "array");
471 assert_eq!(json["minItems"], 2);
472 assert_eq!(json["maxItems"], 4);
473 assert!(json["min_items"].is_null());
474 assert!(json["max_items"].is_null());
475 let decoded: Schema = serde_json::from_value(json.clone()).unwrap();
476 assert!(
477 matches!(&decoded, Schema::Array(array) if array.min_items == Some(2) && array.max_items == Some(4))
478 );
479 assert_eq!(serde_json::to_value(decoded).unwrap(), json);
480 }
481
482 #[test]
483 fn optional_array_schema_accepts_real_null_and_retains_item_type() {
484 let json = serde_json::to_value(<Option<Vec<String>>>::schema()).unwrap();
485 assert_eq!(json["anyOf"][0]["type"], "array");
486 assert_eq!(json["anyOf"][0]["items"]["type"], "string");
487 assert_eq!(json["anyOf"][1]["type"], "null");
488 let decoded: Schema = serde_json::from_value(json.clone()).unwrap();
489 assert!(matches!(&decoded, Schema::AnyOf(_)));
490 assert_eq!(serde_json::to_value(decoded).unwrap(), json);
491 }
492
493 #[test]
494 fn nullable_unions_allow_overlapping_null_branches() {
495 let any_json = serde_json::to_value(<Option<serde_json::Value>>::schema()).unwrap();
496 assert_eq!(any_json["anyOf"][0], true);
497 assert_eq!(any_json["anyOf"][1]["type"], "null");
498 assert!(any_json["oneOf"].is_null());
499 let nested = serde_json::to_value(<Option<Option<Vec<String>>>>::schema()).unwrap();
500 assert_eq!(nested["anyOf"][0]["anyOf"][1]["type"], "null");
501 assert_eq!(nested["anyOf"][1]["type"], "null");
502 let null = serde_json::to_value(<Option<()>>::schema()).unwrap();
503 assert_eq!(null["anyOf"][0]["type"], "null");
504 assert_eq!(null["anyOf"][1]["type"], "null");
505 }
506}