Debian Codegraph @

third_party/rust/serde_with/src/schemars_0_8.rs

raw
1 //! Integration with [schemars v0.8](schemars_0_8).
2 //!
3 //! This module is only available if using the `schemars_0_8` feature of the crate.
4 //!
5 //! If you would like to add support for schemars to your own `serde_with` helpers
6 //! see [`JsonSchemaAs`].
7
8 use crate::{
9 formats::{Flexible, Format, PreferMany, PreferOne, Separator, Strict},
10 prelude::{Schema as WrapSchema, *},
11 };
12 use ::schemars_0_8::{
13 gen::SchemaGenerator,
14 schema::{
15 ArrayValidation, InstanceType, Metadata, NumberValidation, ObjectValidation, Schema,
16 SchemaObject, SingleOrVec, SubschemaValidation,
17 },
18 JsonSchema,
19 };
20 use core::{
21 mem::ManuallyDrop,
22 ops::{Deref, DerefMut},
23 };
24
25 //===================================================================
26 // Trait Definition
27
28 /// A type which can be described as a JSON schema document.
29 ///
30 /// This trait is as [`SerializeAs`] is to [`Serialize`] but for [`JsonSchema`].
31 /// You can use it to make your custom [`SerializeAs`] and [`DeserializeAs`]
32 /// types also support being described via JSON schemas.
33 ///
34 /// It is used by the [`Schema`][1] type in order to implement [`JsonSchema`]
35 /// for the relevant types. [`Schema`][1] is used implicitly by the [`serde_as`]
36 /// macro to instruct `schemars` on how to generate JSON schemas for fields
37 /// annotated with `#[serde_as(as = "...")]` attributes.
38 ///
39 /// # Examples
40 /// Suppose we have our very own `PositiveInt` type. Then we could add support
41 /// for generating a schema from it like this
42 ///
43 /// ```
44 /// # extern crate schemars_0_8 as schemars;
45 /// # use serde::{Serialize, Serializer, Deserialize, Deserializer};
46 /// # use serde_with::{SerializeAs, DeserializeAs};
47 /// use serde_with::schemars_0_8::JsonSchemaAs;
48 /// use schemars::gen::SchemaGenerator;
49 /// use schemars::schema::Schema;
50 /// use schemars::JsonSchema;
51 ///
52 /// # #[allow(dead_code)]
53 /// struct PositiveInt;
54 ///
55 /// impl SerializeAs<i32> for PositiveInt {
56 /// // ...
57 /// # fn serialize_as<S>(&value: &i32, ser: S) -> Result<S::Ok, S::Error>
58 /// # where
59 /// # S: Serializer
60 /// # {
61 /// # if value < 0 {
62 /// # return Err(serde::ser::Error::custom(
63 /// # "expected a positive integer value, got a negative one"
64 /// # ));
65 /// # }
66 /// #
67 /// # value.serialize(ser)
68 /// # }
69 /// }
70 ///
71 /// impl<'de> DeserializeAs<'de, i32> for PositiveInt {
72 /// // ...
73 /// # fn deserialize_as<D>(de: D) -> Result<i32, D::Error>
74 /// # where
75 /// # D: Deserializer<'de>,
76 /// # {
77 /// # match i32::deserialize(de) {
78 /// # Ok(value) if value < 0 => Err(serde::de::Error::custom(
79 /// # "expected a positive integer value, got a negative one"
80 /// # )),
81 /// # value => value
82 /// # }
83 /// # }
84 /// }
85 ///
86 /// impl JsonSchemaAs<i32> for PositiveInt {
87 /// fn schema_name() -> String {
88 /// "PositiveInt".into()
89 /// }
90 ///
91 /// fn json_schema(gen: &mut SchemaGenerator) -> Schema {
92 /// let mut schema = <i32 as JsonSchema>::json_schema(gen).into_object();
93 /// schema.number().minimum = Some(0.0);
94 /// schema.into()
95 /// }
96 /// }
97 /// ```
98 ///
99 /// [0]: crate::serde_as
100 /// [1]: crate::Schema
101 pub trait JsonSchemaAs<T: ?Sized> {
102 /// Whether JSON Schemas generated for this type should be re-used where possible using the `$ref` keyword.
103 ///
104 /// For trivial types (such as primitives), this should return `false`. For more complex types, it should return `true`.
105 /// For recursive types, this **must** return `true` to prevent infinite cycles when generating schemas.
106 ///
107 /// By default, this returns `true`.
108 fn is_referenceable() -> bool {
109 true
110 }
111
112 /// The name of the generated JSON Schema.
113 ///
114 /// This is used as the title for root schemas, and the key within the root's `definitions` property for sub-schemas.
115 ///
116 /// As the schema name is used as as part of `$ref` it has to be a valid URI path segment according to
117 /// [RFC 3986 Section-3](https://datatracker.ietf.org/doc/html/rfc3986#section-3).
118 fn schema_name() -> String;
119
120 /// Returns a string that uniquely identifies the schema produced by this type.
121 ///
122 /// This does not have to be a human-readable string, and the value will not itself be included in generated schemas.
123 /// If two types produce different schemas, then they **must** have different `schema_id()`s,
124 /// but two types that produce identical schemas should *ideally* have the same `schema_id()`.
125 ///
126 /// The default implementation returns the same value as `schema_name()`.
127 fn schema_id() -> Cow<'static, str> {
128 Cow::Owned(Self::schema_name())
129 }
130
131 /// Generates a JSON Schema for this type.
132 ///
133 /// If the returned schema depends on any [referenceable](JsonSchema::is_referenceable) schemas, then this method will
134 /// add them to the [`SchemaGenerator`]'s schema definitions.
135 ///
136 /// This should not return a `$ref` schema.
137 fn json_schema(gen: &mut SchemaGenerator) -> Schema;
138 }
139
140 impl<T, TA> JsonSchema for WrapSchema<T, TA>
141 where
142 T: ?Sized,
143 TA: JsonSchemaAs<T>,
144 {
145 fn schema_name() -> String {
146 TA::schema_name()
147 }
148
149 fn schema_id() -> Cow<'static, str> {
150 TA::schema_id()
151 }
152
153 fn json_schema(gen: &mut SchemaGenerator) -> Schema {
154 TA::json_schema(gen)
155 }
156
157 fn is_referenceable() -> bool {
158 TA::is_referenceable()
159 }
160 }
161
162 //===================================================================
163 // Macro helpers
164
165 macro_rules! forward_schema {
166 ($fwd:ty) => {
167 fn schema_name() -> String {
168 <$fwd as JsonSchema>::schema_name()
169 }
170
171 fn schema_id() -> Cow<'static, str> {
172 <$fwd as JsonSchema>::schema_id()
173 }
174
175 fn json_schema(gen: &mut SchemaGenerator) -> Schema {
176 <$fwd as JsonSchema>::json_schema(gen)
177 }
178
179 fn is_referenceable() -> bool {
180 <$fwd as JsonSchema>::is_referenceable()
181 }
182 };
183 }
184
185 //===================================================================
186 // Common definitions for various std types
187
188 impl<'a, T: 'a, TA: 'a> JsonSchemaAs<&'a T> for &'a TA
189 where
190 T: ?Sized,
191 TA: JsonSchemaAs<T>,
192 {
193 forward_schema!(&'a WrapSchema<T, TA>);
194 }
195
196 impl<'a, T: 'a, TA: 'a> JsonSchemaAs<&'a mut T> for &'a mut TA
197 where
198 T: ?Sized,
199 TA: JsonSchemaAs<T>,
200 {
201 forward_schema!(&'a mut WrapSchema<T, TA>);
202 }
203
204 impl<T, TA> JsonSchemaAs<Option<T>> for Option<TA>
205 where
206 TA: JsonSchemaAs<T>,
207 {
208 forward_schema!(Option<WrapSchema<T, TA>>);
209 }
210
211 impl<T, TA> JsonSchemaAs<Box<T>> for Box<TA>
212 where
213 T: ?Sized,
214 TA: JsonSchemaAs<T>,
215 {
216 forward_schema!(Box<WrapSchema<T, TA>>);
217 }
218
219 impl<T, TA> JsonSchemaAs<Rc<T>> for Rc<TA>
220 where
221 T: ?Sized,
222 TA: JsonSchemaAs<T>,
223 {
224 forward_schema!(Rc<WrapSchema<T, TA>>);
225 }
226
227 impl<T, TA> JsonSchemaAs<Arc<T>> for Arc<TA>
228 where
229 T: ?Sized,
230 TA: JsonSchemaAs<T>,
231 {
232 forward_schema!(Arc<WrapSchema<T, TA>>);
233 }
234
235 impl<T, TA> JsonSchemaAs<Vec<T>> for Vec<TA>
236 where
237 TA: JsonSchemaAs<T>,
238 {
239 forward_schema!(Vec<WrapSchema<T, TA>>);
240 }
241
242 impl<T, TA> JsonSchemaAs<VecDeque<T>> for VecDeque<TA>
243 where
244 TA: JsonSchemaAs<T>,
245 {
246 forward_schema!(VecDeque<WrapSchema<T, TA>>);
247 }
248
249 // schemars only requires that V implement JsonSchema for BTreeMap<K, V>
250 impl<K, V, KA, VA> JsonSchemaAs<BTreeMap<K, V>> for BTreeMap<KA, VA>
251 where
252 VA: JsonSchemaAs<V>,
253 {
254 forward_schema!(BTreeMap<WrapSchema<K, KA>, WrapSchema<V, VA>>);
255 }
256
257 // schemars only requires that V implement JsonSchema for HashMap<K, V>
258 impl<K, V, S, KA, VA> JsonSchemaAs<HashMap<K, V, S>> for HashMap<KA, VA, S>
259 where
260 VA: JsonSchemaAs<V>,
261 {
262 forward_schema!(HashMap<WrapSchema<K, KA>, WrapSchema<V, VA>, S>);
263 }
264
265 impl<T, TA> JsonSchemaAs<BTreeSet<T>> for BTreeSet<TA>
266 where
267 TA: JsonSchemaAs<T>,
268 {
269 forward_schema!(BTreeSet<WrapSchema<T, TA>>);
270 }
271
272 impl<T, TA, S> JsonSchemaAs<T> for HashSet<TA, S>
273 where
274 TA: JsonSchemaAs<T>,
275 {
276 forward_schema!(HashSet<WrapSchema<T, TA>, S>);
277 }
278
279 impl<T, TA, const N: usize> JsonSchemaAs<[T; N]> for [TA; N]
280 where
281 TA: JsonSchemaAs<T>,
282 {
283 fn schema_name() -> String {
284 std::format!("[{}; {}]", <WrapSchema<T, TA>>::schema_name(), N)
285 }
286
287 fn schema_id() -> Cow<'static, str> {
288 std::format!("[{}; {}]", <WrapSchema<T, TA>>::schema_id(), N).into()
289 }
290
291 fn json_schema(gen: &mut SchemaGenerator) -> Schema {
292 let (max, min) = match N.try_into() {
293 Ok(len) => (Some(len), Some(len)),
294 Err(_) => (None, Some(u32::MAX)),
295 };
296
297 SchemaObject {
298 instance_type: Some(InstanceType::Array.into()),
299 array: Some(Box::new(ArrayValidation {
300 items: Some(gen.subschema_for::<WrapSchema<T, TA>>().into()),
301 max_items: max,
302 min_items: min,
303 ..Default::default()
304 })),
305 ..Default::default()
306 }
307 .into()
308 }
309
310 fn is_referenceable() -> bool {
311 false
312 }
313 }
314
315 macro_rules! schema_for_tuple {
316 (
317 ( $( $ts:ident )+ )
318 ( $( $as:ident )+ )
319 ) => {
320 impl<$($ts,)+ $($as,)+> JsonSchemaAs<($($ts,)+)> for ($($as,)+)
321 where
322 $( $as: JsonSchemaAs<$ts>, )+
323 {
324 forward_schema!(( $( WrapSchema<$ts, $as>, )+ ));
325 }
326 }
327 }
328
329 impl JsonSchemaAs<()> for () {
330 forward_schema!(());
331 }
332
333 // schemars only implements JsonSchema for tuples up to 15 elements so we do
334 // the same here.
335 schema_for_tuple!((T0)(A0));
336 schema_for_tuple!((T0 T1) (A0 A1));
337 schema_for_tuple!((T0 T1 T2) (A0 A1 A2));
338 schema_for_tuple!((T0 T1 T2 T3) (A0 A1 A2 A3));
339 schema_for_tuple!((T0 T1 T2 T3 T4) (A0 A1 A2 A3 A4));
340 schema_for_tuple!((T0 T1 T2 T3 T4 T5) (A0 A1 A2 A3 A4 A5));
341 schema_for_tuple!((T0 T1 T2 T3 T4 T5 T6) (A0 A1 A2 A3 A4 A5 A6));
342 schema_for_tuple!((T0 T1 T2 T3 T4 T5 T6 T7) (A0 A1 A2 A3 A4 A5 A6 A7));
343 schema_for_tuple!((T0 T1 T2 T3 T4 T5 T6 T7 T8) (A0 A1 A2 A3 A4 A5 A6 A7 A8));
344 schema_for_tuple!((T0 T1 T2 T3 T4 T5 T6 T7 T8 T9) (A0 A1 A2 A3 A4 A5 A6 A7 A8 A9));
345 schema_for_tuple!((T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10) (A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10));
346 schema_for_tuple!((T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11) (A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11));
347 schema_for_tuple!(
348 (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12)
349 (A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12)
350 );
351 schema_for_tuple!(
352 (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13)
353 (A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13)
354 );
355 schema_for_tuple!(
356 (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14)
357 (A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14)
358 );
359 schema_for_tuple!(
360 (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14 T15)
361 (A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15)
362 );
363
364 //===================================================================
365 // Impls for serde_with types.
366
367 impl<T: JsonSchema> JsonSchemaAs<T> for Same {
368 forward_schema!(T);
369 }
370
371 impl<T> JsonSchemaAs<T> for DisplayFromStr {
372 forward_schema!(String);
373 }
374
375 impl JsonSchemaAs<bool> for BoolFromInt<Strict> {
376 fn schema_name() -> String {
377 "BoolFromInt<Strict>".into()
378 }
379
380 fn schema_id() -> Cow<'static, str> {
381 "serde_with::BoolFromInt<Strict>".into()
382 }
383
384 fn json_schema(_: &mut SchemaGenerator) -> Schema {
385 SchemaObject {
386 instance_type: Some(InstanceType::Integer.into()),
387 number: Some(Box::new(NumberValidation {
388 minimum: Some(0.0),
389 maximum: Some(1.0),
390 ..Default::default()
391 })),
392 ..Default::default()
393 }
394 .into()
395 }
396
397 fn is_referenceable() -> bool {
398 false
399 }
400 }
401
402 impl JsonSchemaAs<bool> for BoolFromInt<Flexible> {
403 fn schema_name() -> String {
404 "BoolFromInt<Flexible>".into()
405 }
406
407 fn schema_id() -> Cow<'static, str> {
408 "serde_with::BoolFromInt<Flexible>".into()
409 }
410
411 fn json_schema(_: &mut SchemaGenerator) -> Schema {
412 SchemaObject {
413 instance_type: Some(InstanceType::Integer.into()),
414 ..Default::default()
415 }
416 .into()
417 }
418
419 fn is_referenceable() -> bool {
420 false
421 }
422 }
423
424 impl<'a, T: 'a> JsonSchemaAs<Cow<'a, T>> for BorrowCow
425 where
426 T: ?Sized + ToOwned,
427 Cow<'a, T>: JsonSchema,
428 {
429 forward_schema!(Cow<'a, T>);
430 }
431
432 impl<T> JsonSchemaAs<T> for Bytes {
433 forward_schema!(Vec<u8>);
434 }
435
436 impl JsonSchemaAs<Vec<u8>> for BytesOrString {
437 fn schema_name() -> String {
438 "BytesOrString".into()
439 }
440
441 fn schema_id() -> Cow<'static, str> {
442 "serde_with::BytesOrString".into()
443 }
444
445 fn json_schema(gen: &mut SchemaGenerator) -> Schema {
446 SchemaObject {
447 subschemas: Some(Box::new(SubschemaValidation {
448 any_of: Some(std::vec![
449 gen.subschema_for::<Vec<u8>>(),
450 SchemaObject {
451 instance_type: Some(InstanceType::String.into()),
452 metadata: Some(Box::new(Metadata {
453 write_only: true,
454 ..Default::default()
455 })),
456 ..Default::default()
457 }
458 .into()
459 ]),
460 ..Default::default()
461 })),
462 ..Default::default()
463 }
464 .into()
465 }
466
467 fn is_referenceable() -> bool {
468 false
469 }
470 }
471
472 impl<T, TA> JsonSchemaAs<T> for DefaultOnError<TA>
473 where
474 TA: JsonSchemaAs<T>,
475 {
476 forward_schema!(WrapSchema<T, TA>);
477 }
478
479 impl<T, TA> JsonSchemaAs<T> for DefaultOnNull<TA>
480 where
481 TA: JsonSchemaAs<T>,
482 {
483 forward_schema!(Option<WrapSchema<T, TA>>);
484 }
485
486 impl<O, T: JsonSchema> JsonSchemaAs<O> for FromInto<T> {
487 forward_schema!(T);
488 }
489
490 impl<O, T: JsonSchema> JsonSchemaAs<O> for FromIntoRef<T> {
491 forward_schema!(T);
492 }
493
494 impl<T, U: JsonSchema> JsonSchemaAs<T> for TryFromInto<U> {
495 forward_schema!(U);
496 }
497
498 impl<T, U: JsonSchema> JsonSchemaAs<T> for TryFromIntoRef<U> {
499 forward_schema!(U);
500 }
501
502 impl<T, TA, FA> JsonSchemaAs<T> for IfIsHumanReadable<TA, FA>
503 where
504 TA: JsonSchemaAs<T>,
505 {
506 // serde_json always has `is_human_readable` set to true so we just use the
507 // schema for the human readable variant.
508 forward_schema!(WrapSchema<T, TA>);
509 }
510
511 macro_rules! schema_for_map {
512 ($type:ty) => {
513 impl<K, V, KA, VA> JsonSchemaAs<$type> for Map<KA, VA>
514 where
515 VA: JsonSchemaAs<V>,
516 {
517 forward_schema!(WrapSchema<BTreeMap<K, V>, BTreeMap<KA, VA>>);
518 }
519 };
520 }
521
522 schema_for_map!([(K, V)]);
523 schema_for_map!(BTreeSet<(K, V)>);
524 schema_for_map!(BinaryHeap<(K, V)>);
525 schema_for_map!(Box<[(K, V)]>);
526 schema_for_map!(LinkedList<(K, V)>);
527 schema_for_map!(Vec<(K, V)>);
528 schema_for_map!(VecDeque<(K, V)>);
529
530 impl<K, V, S, KA, VA> JsonSchemaAs<HashSet<(K, V), S>> for Map<KA, VA>
531 where
532 VA: JsonSchemaAs<V>,
533 {
534 forward_schema!(WrapSchema<BTreeMap<K, V>, BTreeMap<KA, VA>>);
535 }
536
537 impl<T> JsonSchemaAs<Vec<T>> for EnumMap
538 where
539 T: JsonSchema,
540 {
541 fn schema_name() -> String {
542 std::format!("EnumMap({})", T::schema_name())
543 }
544
545 fn schema_id() -> Cow<'static, str> {
546 std::format!("serde_with::EnumMap({})", T::schema_id()).into()
547 }
548
549 // We generate the schema here by going through all the variants of the
550 // enum (the oneOf property) and sticking all their properties onto an
551 // object.
552 //
553 // This will be wrong if the object is not an externally tagged enum but in
554 // that case serialization and deserialization will fail so it is probably
555 // OK.
556 fn json_schema(gen: &mut SchemaGenerator) -> Schema {
557 let mut object = SchemaObject {
558 instance_type: Some(InstanceType::Object.into()),
559 ..Default::default()
560 };
561 let inner = T::json_schema(gen).into_object();
562
563 let one_of = match inner.subschemas {
564 Some(subschemas) => match subschemas.one_of {
565 Some(one_of) => one_of,
566 None => return object.into(),
567 },
568 None => return object.into(),
569 };
570
571 let properties = &mut object.object().properties;
572 for schema in one_of {
573 if let Some(object) = schema.into_object().object {
574 properties.extend(object.properties.into_iter());
575 }
576 }
577
578 object.object().additional_properties = Some(Box::new(Schema::Bool(false)));
579 object.into()
580 }
581
582 fn is_referenceable() -> bool {
583 true
584 }
585 }
586
587 impl<T, TA> WrapSchema<Vec<T>, KeyValueMap<TA>>
588 where
589 TA: JsonSchemaAs<T>,
590 {
591 /// Transform a schema from the entry type of a `KeyValueMap<T>` to the
592 /// resulting field type.
593 ///
594 /// This usually means doing one of two things:
595 /// 1. removing the `$key$` property from an object, or,
596 /// 2. removing the first item from an array.
597 ///
598 /// We also need to adjust any fields that control the number of items or
599 /// properties allowed such as `(max|min)_properties` or `(max|min)_items`.
600 ///
601 /// This is mostly straightforward. Where things get hairy is when dealing
602 /// with subschemas. JSON schemas allow you to build the schema for an
603 /// object by combining multiple subschemas:
604 /// - You can match exactly one of a set of subschemas (`one_of`).
605 /// - You can match any of a set of subschemas (`any_of`).
606 /// - You can match all of a set of subschemas (`all_of`).
607 ///
608 /// Unfortunately for us, we need to handle all of these options by recursing
609 /// into the subschemas and applying the same transformations as above.
610 fn kvmap_transform_schema(gen: &mut SchemaGenerator, schema: &mut Schema) {
611 let mut parents = Vec::new();
612
613 Self::kvmap_transform_schema_impl(gen, schema, &mut parents, 0);
614 }
615
616 fn kvmap_transform_schema_impl(
617 gen: &mut SchemaGenerator,
618 schema: &mut Schema,
619 parents: &mut Vec<String>,
620 depth: u32,
621 ) {
622 if depth > 8 {
623 return;
624 }
625
626 let mut done = false;
627 let schema = match schema {
628 Schema::Object(schema) => schema,
629 _ => return,
630 };
631
632 // The schema is a reference to a schema defined elsewhere.
633 //
634 // If possible we replace it with its definition but if that is not
635 // available then we give up and leave it as-is.
636 let mut parents = if let Some(reference) = &schema.reference {
637 let name = match reference.strip_prefix(&gen.settings().definitions_path) {
638 Some(name) => name,
639 // Reference is defined elsewhere, nothing we can do.
640 None => return,
641 };
642
643 // We are in a recursive reference loop. No point in continuing.
644 if parents.iter().any(|parent| parent == name) {
645 return;
646 }
647
648 let name = name.to_owned();
649 *schema = match gen.definitions().get(&name) {
650 Some(Schema::Object(schema)) => schema.clone(),
651 _ => return,
652 };
653
654 parents.push(name);
655 DropGuard::new(parents, |parents| drop(parents.pop()))
656 } else {
657 DropGuard::unguarded(parents)
658 };
659
660 if let Some(object) = &mut schema.object {
661 // For objects KeyValueMap uses the $key$ property so we need to remove it from
662 // the inner schema.
663
664 done |= object.properties.remove("$key$").is_some();
665 done |= object.required.remove("$key$");
666
667 if let Some(max) = &mut object.max_properties {
668 *max = max.saturating_sub(1);
669 }
670
671 if let Some(min) = &mut object.max_properties {
672 *min = min.saturating_sub(1);
673 }
674 }
675
676 if let Some(array) = &mut schema.array {
677 // For arrays KeyValueMap uses the first array element so we need to remove it
678 // from the inner schema.
679
680 if let Some(SingleOrVec::Vec(items)) = &mut array.items {
681 // If the array is empty then the leading element may be following the
682 // additionalItem schema. In that case we do nothing.
683 if !items.is_empty() {
684 items.remove(0);
685 done = true;
686 }
687 }
688
689 if let Some(max) = &mut array.max_items {
690 *max = max.saturating_sub(1);
691 }
692
693 if let Some(min) = &mut array.min_items {
694 *min = min.saturating_sub(1);
695 }
696 }
697
698 // We've already modified the schema so there's no need to do more work.
699 if done {
700 return;
701 }
702
703 let subschemas = match &mut schema.subschemas {
704 Some(subschemas) => subschemas,
705 None => return,
706 };
707
708 if let Some(one_of) = &mut subschemas.one_of {
709 for subschema in one_of {
710 Self::kvmap_transform_schema_impl(gen, subschema, &mut parents, depth + 1);
711 }
712 }
713
714 if let Some(any_of) = &mut subschemas.any_of {
715 for subschema in any_of {
716 Self::kvmap_transform_schema_impl(gen, subschema, &mut parents, depth + 1);
717 }
718 }
719
720 if let Some(all_of) = &mut subschemas.all_of {
721 for subschema in all_of {
722 Self::kvmap_transform_schema_impl(gen, subschema, &mut parents, depth + 1);
723 }
724 }
725 }
726 }
727
728 impl<T, TA> JsonSchemaAs<Vec<T>> for KeyValueMap<TA>
729 where
730 TA: JsonSchemaAs<T>,
731 {
732 fn schema_name() -> String {
733 std::format!("KeyValueMap({})", <WrapSchema<T, TA>>::schema_name())
734 }
735
736 fn schema_id() -> Cow<'static, str> {
737 std::format!(
738 "serde_with::KeyValueMap({})",
739 <WrapSchema<T, TA>>::schema_id()
740 )
741 .into()
742 }
743
744 fn json_schema(gen: &mut SchemaGenerator) -> Schema {
745 let mut value = <WrapSchema<T, TA>>::json_schema(gen);
746 <WrapSchema<Vec<T>, KeyValueMap<TA>>>::kvmap_transform_schema(gen, &mut value);
747
748 SchemaObject {
749 instance_type: Some(InstanceType::Object.into()),
750 object: Some(Box::new(ObjectValidation {
751 additional_properties: Some(Box::new(value)),
752 ..Default::default()
753 })),
754 ..Default::default()
755 }
756 .into()
757 }
758
759 fn is_referenceable() -> bool {
760 true
761 }
762 }
763
764 impl<K, V, KA, VA, const N: usize> JsonSchemaAs<[(K, V); N]> for Map<KA, VA>
765 where
766 VA: JsonSchemaAs<V>,
767 {
768 forward_schema!(WrapSchema<BTreeMap<K, V>, BTreeMap<KA, VA>>);
769 }
770
771 macro_rules! map_first_last_wins_schema {
772 ($(=> $extra:ident)? $type:ty) => {
773 impl<K, V, $($extra,)? KA, VA> JsonSchemaAs<$type> for MapFirstKeyWins<KA, VA>
774 where
775 VA: JsonSchemaAs<V>,
776 {
777 forward_schema!(BTreeMap<WrapSchema<K, KA>, WrapSchema<V, VA>>);
778 }
779
780 impl<K, V, $($extra,)? KA, VA> JsonSchemaAs<$type> for MapPreventDuplicates<KA, VA>
781 where
782 VA: JsonSchemaAs<V>,
783 {
784 forward_schema!(BTreeMap<WrapSchema<K, KA>, WrapSchema<V, VA>>);
785 }
786 }
787 }
788
789 map_first_last_wins_schema!(BTreeMap<K, V>);
790 map_first_last_wins_schema!(=> S HashMap<K, V, S>);
791 #[cfg(feature = "hashbrown_0_14")]
792 map_first_last_wins_schema!(=> S hashbrown_0_14::HashMap<K, V, S>);
793 #[cfg(feature = "hashbrown_0_15")]
794 map_first_last_wins_schema!(=> S hashbrown_0_15::HashMap<K, V, S>);
795 #[cfg(feature = "indexmap_1")]
796 map_first_last_wins_schema!(=> S indexmap_1::IndexMap<K, V, S>);
797 #[cfg(feature = "indexmap_2")]
798 map_first_last_wins_schema!(=> S indexmap_2::IndexMap<K, V, S>);
799
800 impl<T, TA> JsonSchemaAs<Vec<T>> for OneOrMany<TA, PreferOne>
801 where
802 TA: JsonSchemaAs<T>,
803 {
804 fn schema_name() -> String {
805 std::format!(
806 "OneOrMany({},PreferOne)",
807 <WrapSchema<T, TA>>::schema_name()
808 )
809 }
810
811 fn schema_id() -> Cow<'static, str> {
812 std::format!(
813 "serde_with::OneOrMany({},PreferOne)",
814 <WrapSchema<T, TA>>::schema_id()
815 )
816 .into()
817 }
818
819 fn json_schema(gen: &mut SchemaGenerator) -> Schema {
820 let single = gen.subschema_for::<WrapSchema<T, TA>>();
821 let array = SchemaObject {
822 instance_type: Some(InstanceType::Array.into()),
823 array: Some(Box::new(ArrayValidation {
824 items: Some(single.clone().into()),
825 ..Default::default()
826 })),
827 ..Default::default()
828 };
829
830 SchemaObject {
831 subschemas: Some(Box::new(SubschemaValidation {
832 any_of: Some(std::vec![single, array.into()]),
833 ..Default::default()
834 })),
835 ..Default::default()
836 }
837 .into()
838 }
839 }
840
841 impl<T, TA> JsonSchemaAs<Vec<T>> for OneOrMany<TA, PreferMany>
842 where
843 TA: JsonSchemaAs<T>,
844 {
845 fn schema_name() -> String {
846 std::format!(
847 "OneOrMany<{}, PreferMany>",
848 <WrapSchema<T, TA>>::schema_name()
849 )
850 }
851
852 fn schema_id() -> Cow<'static, str> {
853 std::format!(
854 "serde_with::OneOrMany<{}, PreferMany>",
855 <WrapSchema<T, TA>>::schema_id()
856 )
857 .into()
858 }
859
860 fn json_schema(gen: &mut SchemaGenerator) -> Schema {
861 let inner = gen.subschema_for::<WrapSchema<T, TA>>();
862 let single = SchemaObject {
863 metadata: Some(Box::new(Metadata {
864 write_only: true,
865 ..Default::default()
866 })),
867 subschemas: Some(Box::new(SubschemaValidation {
868 all_of: Some(std::vec![inner.clone()]),
869 ..Default::default()
870 })),
871 ..Default::default()
872 };
873 let array = SchemaObject {
874 instance_type: Some(InstanceType::Array.into()),
875 array: Some(Box::new(ArrayValidation {
876 items: Some(Schema::from(single.clone()).into()),
877 ..Default::default()
878 })),
879 ..Default::default()
880 };
881
882 SchemaObject {
883 subschemas: Some(Box::new(SubschemaValidation {
884 any_of: Some(std::vec![single.into(), array.into()]),
885 ..Default::default()
886 })),
887 ..Default::default()
888 }
889 .into()
890 }
891 }
892
893 macro_rules! schema_for_pickfirst {
894 ($( $param:ident )+) => {
895 impl<T, $($param,)+> JsonSchemaAs<T> for PickFirst<($( $param, )+)>
896 where
897 $( $param: JsonSchemaAs<T>, )+
898 {
899 fn schema_name() -> String {
900 std::format!(
901 concat!(
902 "PickFirst(",
903 $( "{", stringify!($param), "}", )+
904 ")"
905 ),
906 $( $param = <WrapSchema<T, $param>>::schema_name(), )+
907 )
908 }
909
910 fn schema_id() -> Cow<'static, str> {
911 std::format!(
912 concat!(
913 "serde_with::PickFirst(",
914 $( "{", stringify!($param), "}", )+
915 ")"
916 ),
917 $( $param = <WrapSchema<T, $param>>::schema_id(), )+
918 )
919 .into()
920 }
921
922 fn json_schema(gen: &mut SchemaGenerator) -> Schema {
923 let mut first = true;
924 let subschemas = std::vec![$(
925 {
926 let is_first = std::mem::replace(&mut first, false);
927 let schema = gen.subschema_for::<WrapSchema<T, $param>>();
928
929 if !is_first {
930 SchemaObject {
931 metadata: Some(Box::new(Metadata {
932 write_only: true,
933 ..Default::default()
934 })),
935 subschemas: Some(Box::new(SubschemaValidation {
936 all_of: Some(std::vec![schema]),
937 ..Default::default()
938 })),
939 ..Default::default()
940 }
941 .into()
942 } else {
943 schema
944 }
945 }
946 ),+];
947
948 SchemaObject {
949 subschemas: Some(Box::new(SubschemaValidation {
950 any_of: Some(subschemas),
951 ..Default::default()
952 })),
953 ..Default::default()
954 }
955 .into()
956 }
957 }
958 }
959 }
960
961 schema_for_pickfirst!(A);
962 schema_for_pickfirst!(A B);
963 schema_for_pickfirst!(A B C);
964 schema_for_pickfirst!(A B C D);
965
966 impl<T, TA> JsonSchemaAs<T> for SetLastValueWins<TA>
967 where
968 TA: JsonSchemaAs<T>,
969 {
970 fn schema_id() -> Cow<'static, str> {
971 std::format!(
972 "serde_with::SetLastValueWins<{}>",
973 <WrapSchema<T, TA> as JsonSchema>::schema_id()
974 )
975 .into()
976 }
977
978 fn schema_name() -> String {
979 std::format!(
980 "SetLastValueWins<{}>",
981 <WrapSchema<T, TA> as JsonSchema>::schema_name()
982 )
983 }
984
985 fn json_schema(gen: &mut SchemaGenerator) -> Schema {
986 let schema = <WrapSchema<T, TA> as JsonSchema>::json_schema(gen);
987 let mut schema = schema.into_object();
988
989 // We explicitly allow duplicate items since the whole point of
990 // SetLastValueWins is to take the duplicate value.
991 if let Some(array) = &mut schema.array {
992 array.unique_items = None;
993 }
994
995 schema.into()
996 }
997
998 fn is_referenceable() -> bool {
999 false
1000 }
1001 }
1002
1003 impl<T, TA> JsonSchemaAs<T> for SetPreventDuplicates<TA>
1004 where
1005 TA: JsonSchemaAs<T>,
1006 {
1007 forward_schema!(WrapSchema<T, TA>);
1008 }
1009
1010 impl<SEP, T, TA> JsonSchemaAs<T> for StringWithSeparator<SEP, TA>
1011 where
1012 SEP: Separator,
1013 {
1014 forward_schema!(String);
1015 }
1016
1017 impl<T, TA> JsonSchemaAs<Vec<T>> for VecSkipError<TA>
1018 where
1019 TA: JsonSchemaAs<T>,
1020 {
1021 forward_schema!(Vec<WrapSchema<T, TA>>);
1022 }
1023
1024 mod timespan {
1025 use super::*;
1026
1027 // #[non_exhaustive] is not actually necessary here but it should
1028 // help avoid warnings about semver breakage if this ever changes.
1029 #[non_exhaustive]
1030 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1031 pub enum TimespanTargetType {
1032 String,
1033 F64,
1034 U64,
1035 I64,
1036 }
1037
1038 impl TimespanTargetType {
1039 pub const fn is_signed(self) -> bool {
1040 !matches!(self, Self::U64)
1041 }
1042 }
1043
1044 /// Internal helper trait used to constrain which types we implement
1045 /// `JsonSchemaAs<T>` for.
1046 pub trait TimespanSchemaTarget<F> {
1047 /// The underlying type.
1048 ///
1049 /// This is mainly used to decide which variant of the resulting schema
1050 /// should be marked as `write_only: true`.
1051 const TYPE: TimespanTargetType;
1052
1053 /// Whether the target type is signed.
1054 ///
1055 /// This is only true for `std::time::Duration`.
1056 const SIGNED: bool = true;
1057 }
1058
1059 macro_rules! timespan_type_of {
1060 (String) => {
1061 TimespanTargetType::String
1062 };
1063 (f64) => {
1064 TimespanTargetType::F64
1065 };
1066 (i64) => {
1067 TimespanTargetType::I64
1068 };
1069 (u64) => {
1070 TimespanTargetType::U64
1071 };
1072 }
1073
1074 macro_rules! declare_timespan_target {
1075 ( $target:ty { $($format:ident),* $(,)? } ) => {
1076 $(
1077 impl TimespanSchemaTarget<$format> for $target {
1078 const TYPE: TimespanTargetType = timespan_type_of!($format);
1079 }
1080 )*
1081 }
1082 }
1083
1084 impl TimespanSchemaTarget<u64> for Duration {
1085 const TYPE: TimespanTargetType = TimespanTargetType::U64;
1086 const SIGNED: bool = false;
1087 }
1088
1089 impl TimespanSchemaTarget<f64> for Duration {
1090 const TYPE: TimespanTargetType = TimespanTargetType::F64;
1091 const SIGNED: bool = false;
1092 }
1093
1094 impl TimespanSchemaTarget<String> for Duration {
1095 const TYPE: TimespanTargetType = TimespanTargetType::String;
1096 const SIGNED: bool = false;
1097 }
1098
1099 declare_timespan_target!(SystemTime { i64, f64, String });
1100
1101 #[cfg(feature = "chrono_0_4")]
1102 declare_timespan_target!(::chrono_0_4::Duration { i64, f64, String });
1103 #[cfg(feature = "chrono_0_4")]
1104 declare_timespan_target!(::chrono_0_4::DateTime<::chrono_0_4::Utc> { i64, f64, String });
1105 #[cfg(feature = "chrono_0_4")]
1106 declare_timespan_target!(::chrono_0_4::DateTime<::chrono_0_4::Local> { i64, f64, String });
1107 #[cfg(feature = "chrono_0_4")]
1108 declare_timespan_target!(::chrono_0_4::NaiveDateTime { i64, f64, String });
1109
1110 #[cfg(feature = "time_0_3")]
1111 declare_timespan_target!(::time_0_3::Duration { i64, f64, String });
1112 #[cfg(feature = "time_0_3")]
1113 declare_timespan_target!(::time_0_3::OffsetDateTime { i64, f64, String });
1114 #[cfg(feature = "time_0_3")]
1115 declare_timespan_target!(::time_0_3::PrimitiveDateTime { i64, f64, String });
1116 }
1117
1118 use self::timespan::{TimespanSchemaTarget, TimespanTargetType};
1119
1120 /// Internal type used for the base impls on `DurationXXX` and `TimestampYYY` types.
1121 ///
1122 /// This allows the `JsonSchema` impls that are Strict to be generic without
1123 /// committing to it as part of the public API.
1124 struct Timespan<Format, Strictness>(PhantomData<(Format, Strictness)>);
1125
1126 impl<T, F> JsonSchemaAs<T> for Timespan<F, Strict>
1127 where
1128 T: TimespanSchemaTarget<F>,
1129 F: Format + JsonSchema,
1130 {
1131 forward_schema!(F);
1132 }
1133
1134 impl TimespanTargetType {
1135 pub(crate) fn to_flexible_schema(self, signed: bool) -> Schema {
1136 use ::schemars_0_8::schema::StringValidation;
1137
1138 let mut number = SchemaObject {
1139 instance_type: Some(InstanceType::Number.into()),
1140 number: (!signed).then(|| {
1141 Box::new(NumberValidation {
1142 minimum: Some(0.0),
1143 ..Default::default()
1144 })
1145 }),
1146 ..Default::default()
1147 };
1148
1149 // This is a more lenient version of the regex used to determine
1150 // whether JSON numbers are valid. Specifically, it allows multiple
1151 // leading zeroes whereas that is illegal in JSON.
1152 let regex = r#"[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?"#;
1153 let mut string = SchemaObject {
1154 instance_type: Some(InstanceType::String.into()),
1155 string: Some(Box::new(StringValidation {
1156 pattern: Some(match signed {
1157 true => std::format!("^-?{regex}$"),
1158 false => std::format!("^{regex}$"),
1159 }),
1160 ..Default::default()
1161 })),
1162 ..Default::default()
1163 };
1164
1165 if self == Self::String {
1166 number.metadata().write_only = true;
1167 } else {
1168 string.metadata().write_only = true;
1169 }
1170
1171 SchemaObject {
1172 subschemas: Some(Box::new(SubschemaValidation {
1173 one_of: Some(std::vec![number.into(), string.into()]),
1174 ..Default::default()
1175 })),
1176 ..Default::default()
1177 }
1178 .into()
1179 }
1180
1181 pub(crate) fn schema_id(self) -> &'static str {
1182 match self {
1183 Self::String => "serde_with::FlexibleStringTimespan",
1184 Self::F64 => "serde_with::FlexibleF64Timespan",
1185 Self::U64 => "serde_with::FlexibleU64Timespan",
1186 Self::I64 => "serde_with::FlexibleI64Timespan",
1187 }
1188 }
1189 }
1190
1191 impl<T, F> JsonSchemaAs<T> for Timespan<F, Flexible>
1192 where
1193 T: TimespanSchemaTarget<F>,
1194 F: Format + JsonSchema,
1195 {
1196 fn schema_name() -> String {
1197 <T as TimespanSchemaTarget<F>>::TYPE
1198 .schema_id()
1199 .strip_prefix("serde_with::")
1200 .expect("schema id did not start with `serde_with::` - this is a bug")
1201 .into()
1202 }
1203
1204 fn schema_id() -> Cow<'static, str> {
1205 <T as TimespanSchemaTarget<F>>::TYPE.schema_id().into()
1206 }
1207
1208 fn json_schema(_: &mut SchemaGenerator) -> Schema {
1209 <T as TimespanSchemaTarget<F>>::TYPE
1210 .to_flexible_schema(<T as TimespanSchemaTarget<F>>::SIGNED)
1211 }
1212
1213 fn is_referenceable() -> bool {
1214 false
1215 }
1216 }
1217
1218 macro_rules! forward_duration_schema {
1219 ($ty:ident) => {
1220 impl<T, F> JsonSchemaAs<T> for $ty<F, Strict>
1221 where
1222 T: TimespanSchemaTarget<F>,
1223 F: Format + JsonSchema
1224 {
1225 forward_schema!(WrapSchema<T, Timespan<F, Strict>>);
1226 }
1227
1228 impl<T, F> JsonSchemaAs<T> for $ty<F, Flexible>
1229 where
1230 T: TimespanSchemaTarget<F>,
1231 F: Format + JsonSchema
1232 {
1233 forward_schema!(WrapSchema<T, Timespan<F, Flexible>>);
1234 }
1235 };
1236 }
1237
1238 forward_duration_schema!(DurationSeconds);
1239 forward_duration_schema!(DurationMilliSeconds);
1240 forward_duration_schema!(DurationMicroSeconds);
1241 forward_duration_schema!(DurationNanoSeconds);
1242
1243 forward_duration_schema!(DurationSecondsWithFrac);
1244 forward_duration_schema!(DurationMilliSecondsWithFrac);
1245 forward_duration_schema!(DurationMicroSecondsWithFrac);
1246 forward_duration_schema!(DurationNanoSecondsWithFrac);
1247
1248 forward_duration_schema!(TimestampSeconds);
1249 forward_duration_schema!(TimestampMilliSeconds);
1250 forward_duration_schema!(TimestampMicroSeconds);
1251 forward_duration_schema!(TimestampNanoSeconds);
1252
1253 forward_duration_schema!(TimestampSecondsWithFrac);
1254 forward_duration_schema!(TimestampMilliSecondsWithFrac);
1255 forward_duration_schema!(TimestampMicroSecondsWithFrac);
1256 forward_duration_schema!(TimestampNanoSecondsWithFrac);
1257
1258 //===================================================================
1259 // Extra internal helper structs
1260
1261 struct DropGuard<T, F: FnOnce(T)> {
1262 value: ManuallyDrop<T>,
1263 guard: Option<F>,
1264 }
1265
1266 impl<T, F: FnOnce(T)> DropGuard<T, F> {
1267 pub fn new(value: T, guard: F) -> Self {
1268 Self {
1269 value: ManuallyDrop::new(value),
1270 guard: Some(guard),
1271 }
1272 }
1273
1274 pub fn unguarded(value: T) -> Self {
1275 Self {
1276 value: ManuallyDrop::new(value),
1277 guard: None,
1278 }
1279 }
1280 }
1281
1282 impl<T, F: FnOnce(T)> Deref for DropGuard<T, F> {
1283 type Target = T;
1284
1285 fn deref(&self) -> &Self::Target {
1286 &self.value
1287 }
1288 }
1289
1290 impl<T, F: FnOnce(T)> DerefMut for DropGuard<T, F> {
1291 fn deref_mut(&mut self) -> &mut Self::Target {
1292 &mut self.value
1293 }
1294 }
1295
1296 impl<T, F: FnOnce(T)> Drop for DropGuard<T, F> {
1297 fn drop(&mut self) {
1298 // SAFETY: value is known to be initialized since we only ever remove it here.
1299 let value = unsafe { ManuallyDrop::take(&mut self.value) };
1300
1301 if let Some(guard) = self.guard.take() {
1302 guard(value);
1303 }
1304 }
1305 }