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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
/*!
JSON Schema generator and settings.

This module is useful if you want more control over how the schema generated than the [`schema_for!`] macro gives you.
There are two main types in this module:
* [`SchemaSettings`], which defines what JSON Schema features should be used when generating schemas (for example, how `Option`s should be represented).
* [`SchemaGenerator`], which manages the generation of a schema document.
*/

use crate::Schema;
use crate::_alloc_prelude::*;
use crate::{transform::*, JsonSchema};
use alloc::collections::{BTreeMap, BTreeSet};
use core::{any::Any, fmt::Debug};
use dyn_clone::DynClone;
use serde::Serialize;
use serde_json::{Map as JsonMap, Value};

type CowStr = alloc::borrow::Cow<'static, str>;

/// Settings to customize how Schemas are generated.
///
/// The default settings currently conform to [JSON Schema 2020-12](https://json-schema.org/specification-links#2020-12), but this is liable to change in a future version of Schemars if support for other JSON Schema versions is added.
/// If you rely on generated schemas conforming to draft 2020-12, consider using the
/// [`SchemaSettings::draft2020_12()`] method.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SchemaSettings {
    /// If `true`, schemas for [`Option<T>`] will include a `nullable` property.
    ///
    /// This is not part of the JSON Schema spec, but is used in Swagger/OpenAPI schemas.
    ///
    /// Defaults to `false`.
    pub option_nullable: bool,
    /// If `true`, schemas for [`Option<T>`] will have `null` added to their `type` property.
    ///
    /// Defaults to `true`.
    pub option_add_null_type: bool,
    /// A JSON pointer to the expected location of referenceable subschemas within the resulting
    /// root schema.
    ///
    /// A single leading `#` and/or single trailing `/` are ignored.
    ///
    /// Defaults to `"/$defs"`.
    pub definitions_path: String,
    /// The URI of the meta-schema describing the structure of the generated schemas.
    ///
    /// Defaults to `"https://json-schema.org/draft/2020-12/schema"`.
    pub meta_schema: Option<String>,
    /// A list of [`Transform`]s that get applied to generated root schemas.
    pub transforms: Vec<Box<dyn GenTransform>>,
    /// Inline all subschemas instead of using references.
    ///
    /// Some references may still be generated in schemas for recursive types.
    ///
    /// Defaults to `false`.
    pub inline_subschemas: bool,
    /// Whether the generated schemas should describe how types are serialized or *de*serialized.
    ///
    /// Defaults to `Contract::Deserialize`.
    pub contract: Contract,
}

impl Default for SchemaSettings {
    /// The default settings currently conform to [JSON Schema 2020-12](https://json-schema.org/specification-links#2020-12), but this is liable to change in a future version of Schemars if support for other JSON Schema versions is added.
    /// If you rely on generated schemas conforming to draft 2020-12, consider using the
    /// [`SchemaSettings::draft2020_12()`] method.
    fn default() -> SchemaSettings {
        SchemaSettings::draft2020_12()
    }
}

impl SchemaSettings {
    /// Creates `SchemaSettings` that conform to [JSON Schema Draft 7](https://json-schema.org/specification-links#draft-7).
    pub fn draft07() -> SchemaSettings {
        SchemaSettings {
            option_nullable: false,
            option_add_null_type: true,
            definitions_path: "/definitions".to_owned(),
            meta_schema: Some("http://json-schema.org/draft-07/schema#".to_owned()),
            transforms: vec![
                Box::new(ReplaceUnevaluatedProperties),
                Box::new(RemoveRefSiblings),
                Box::new(ReplacePrefixItems),
            ],
            inline_subschemas: false,
            contract: Contract::Deserialize,
        }
    }

    /// Creates `SchemaSettings` that conform to [JSON Schema 2019-09](https://json-schema.org/specification-links#draft-2019-09-(formerly-known-as-draft-8)).
    pub fn draft2019_09() -> SchemaSettings {
        SchemaSettings {
            option_nullable: false,
            option_add_null_type: true,
            definitions_path: "/$defs".to_owned(),
            meta_schema: Some("https://json-schema.org/draft/2019-09/schema".to_owned()),
            transforms: vec![Box::new(ReplacePrefixItems)],
            inline_subschemas: false,
            contract: Contract::Deserialize,
        }
    }

    /// Creates `SchemaSettings` that conform to [JSON Schema 2020-12](https://json-schema.org/specification-links#2020-12).
    pub fn draft2020_12() -> SchemaSettings {
        SchemaSettings {
            option_nullable: false,
            option_add_null_type: true,
            definitions_path: "/$defs".to_owned(),
            meta_schema: Some("https://json-schema.org/draft/2020-12/schema".to_owned()),
            transforms: Vec::new(),
            inline_subschemas: false,
            contract: Contract::Deserialize,
        }
    }

    /// Creates `SchemaSettings` that conform to [OpenAPI 3.0](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#schema).
    pub fn openapi3() -> SchemaSettings {
        SchemaSettings {
            option_nullable: true,
            option_add_null_type: false,
            definitions_path: "/components/schemas".to_owned(),
            meta_schema: Some(
                "https://spec.openapis.org/oas/3.0/schema/2021-09-28#/definitions/Schema"
                    .to_owned(),
            ),
            transforms: vec![
                Box::new(ReplaceUnevaluatedProperties),
                Box::new(RemoveRefSiblings),
                Box::new(ReplaceBoolSchemas {
                    skip_additional_properties: true,
                }),
                Box::new(SetSingleExample),
                Box::new(ReplaceConstValue),
                Box::new(ReplacePrefixItems),
            ],
            inline_subschemas: false,
            contract: Contract::Deserialize,
        }
    }

    /// Modifies the `SchemaSettings` by calling the given function.
    ///
    /// # Example
    /// ```
    /// use schemars::generate::{SchemaGenerator, SchemaSettings};
    ///
    /// let settings = SchemaSettings::default().with(|s| {
    ///     s.option_nullable = true;
    ///     s.option_add_null_type = false;
    /// });
    /// let generator = settings.into_generator();
    /// ```
    pub fn with(mut self, configure_fn: impl FnOnce(&mut Self)) -> Self {
        configure_fn(&mut self);
        self
    }

    /// Appends the given transform to the list of [transforms](SchemaSettings::transforms) for
    /// these `SchemaSettings`.
    pub fn with_transform(mut self, transform: impl Transform + Clone + 'static + Send) -> Self {
        self.transforms.push(Box::new(transform));
        self
    }

    /// Creates a new [`SchemaGenerator`] using these settings.
    pub fn into_generator(self) -> SchemaGenerator {
        SchemaGenerator::new(self)
    }

    /// Updates the settings to generate schemas describing how types are **deserialized**.
    pub fn for_deserialize(mut self) -> Self {
        self.contract = Contract::Deserialize;
        self
    }

    /// Updates the settings to generate schemas describing how types are **serialized**.
    pub fn for_serialize(mut self) -> Self {
        self.contract = Contract::Serialize;
        self
    }
}

/// A setting to specify whether generated schemas should describe how types are serialized or
/// *de*serialized.
///
/// This enum is marked as `#[non_exhaustive]` to reserve space to introduce further variants
/// in future.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[allow(missing_docs)]
#[non_exhaustive]
pub enum Contract {
    Deserialize,
    Serialize,
}

impl Contract {
    /// Returns true if `self` is the `Deserialize` contract.
    pub fn is_deserialize(&self) -> bool {
        self == &Contract::Deserialize
    }

    /// Returns true if `self` is the `Serialize` contract.
    pub fn is_serialize(&self) -> bool {
        self == &Contract::Serialize
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct SchemaUid(CowStr, Contract);

/// The main type used to generate JSON Schemas.
///
/// # Example
/// ```
/// use schemars::{JsonSchema, SchemaGenerator};
///
/// #[derive(JsonSchema)]
/// struct MyStruct {
///     foo: i32,
/// }
///
/// let generator = SchemaGenerator::default();
/// let schema = generator.into_root_schema_for::<MyStruct>();
/// ```
#[derive(Debug, Default)]
pub struct SchemaGenerator {
    settings: SchemaSettings,
    definitions: JsonMap<String, Value>,
    pending_schema_ids: BTreeSet<SchemaUid>,
    schema_id_to_name: BTreeMap<SchemaUid, CowStr>,
    used_schema_names: BTreeSet<CowStr>,
}

impl Clone for SchemaGenerator {
    fn clone(&self) -> Self {
        Self {
            settings: self.settings.clone(),
            definitions: self.definitions.clone(),
            pending_schema_ids: BTreeSet::new(),
            schema_id_to_name: BTreeMap::new(),
            used_schema_names: BTreeSet::new(),
        }
    }
}

impl From<SchemaSettings> for SchemaGenerator {
    fn from(settings: SchemaSettings) -> Self {
        settings.into_generator()
    }
}

impl SchemaGenerator {
    /// Creates a new `SchemaGenerator` using the given settings.
    pub fn new(settings: SchemaSettings) -> SchemaGenerator {
        SchemaGenerator {
            settings,
            ..Default::default()
        }
    }

    /// Borrows the [`SchemaSettings`] being used by this `SchemaGenerator`.
    ///
    /// # Example
    /// ```
    /// use schemars::SchemaGenerator;
    ///
    /// let generator = SchemaGenerator::default();
    /// let settings = generator.settings();
    ///
    /// assert_eq!(settings.option_add_null_type, true);
    /// ```
    pub fn settings(&self) -> &SchemaSettings {
        &self.settings
    }

    /// Generates a JSON Schema for the type `T`, and returns either the schema itself or a `$ref`
    /// schema referencing `T`'s schema.
    ///
    /// If `T` is not [inlined](JsonSchema::always_inline_schema), this will add `T`'s schema to
    /// this generator's definitions, and return a `$ref` schema referencing that schema.
    /// Otherwise, this method behaves identically to [`JsonSchema::json_schema`].
    ///
    /// If `T`'s schema depends on any [non-inlined](JsonSchema::always_inline_schema) schemas, then
    /// this method will add them to the `SchemaGenerator`'s schema definitions.
    pub fn subschema_for<T: ?Sized + JsonSchema>(&mut self) -> Schema {
        let uid = self.schema_uid::<T>();
        let return_ref = !T::always_inline_schema()
            && (!self.settings.inline_subschemas || self.pending_schema_ids.contains(&uid));

        if return_ref {
            let name = match self.schema_id_to_name.get(&uid).cloned() {
                Some(n) => n,
                None => {
                    let base_name = T::schema_name();
                    let mut name = CowStr::Borrowed("");

                    if self.used_schema_names.contains(base_name.as_ref()) {
                        for i in 2.. {
                            name = format!("{base_name}{i}").into();
                            if !self.used_schema_names.contains(&name) {
                                break;
                            }
                        }
                    } else {
                        name = base_name;
                    }

                    self.used_schema_names.insert(name.clone());
                    self.schema_id_to_name.insert(uid.clone(), name.clone());
                    name
                }
            };

            let reference = format!("#{}/{}", self.definitions_path_stripped(), name);
            if !self.definitions.contains_key(name.as_ref()) {
                self.insert_new_subschema_for::<T>(name, uid);
            }
            Schema::new_ref(reference)
        } else {
            self.json_schema_internal::<T>(uid)
        }
    }

    fn insert_new_subschema_for<T: ?Sized + JsonSchema>(&mut self, name: CowStr, uid: SchemaUid) {
        // TODO: If we've already added a schema for T with the "opposite" contract, then check
        // whether the new schema is identical. If so, re-use the original for both contracts.

        let dummy = false.into();
        // insert into definitions BEFORE calling json_schema to avoid infinite recursion
        self.definitions.insert(name.clone().into(), dummy);

        let schema = self.json_schema_internal::<T>(uid);

        self.definitions.insert(name.into(), schema.to_value());
    }

    /// Borrows the collection of all [non-inlined](JsonSchema::always_inline_schema) schemas that
    /// have been generated.
    ///
    /// The keys of the returned `Map` are the [schema names](JsonSchema::schema_name), and the
    /// values are the schemas themselves.
    pub fn definitions(&self) -> &JsonMap<String, Value> {
        &self.definitions
    }

    /// Mutably borrows the collection of all [non-inlined](JsonSchema::always_inline_schema)
    /// schemas that have been generated.
    ///
    /// The keys of the returned `Map` are the [schema names](JsonSchema::schema_name), and the
    /// values are the schemas themselves.
    pub fn definitions_mut(&mut self) -> &mut JsonMap<String, Value> {
        &mut self.definitions
    }

    /// Returns the collection of all [non-inlined](JsonSchema::always_inline_schema) schemas that
    /// have been generated, leaving an empty `Map` in its place.
    ///
    /// The keys of the returned `Map` are the [schema names](JsonSchema::schema_name), and the
    /// values are the schemas themselves.
    pub fn take_definitions(&mut self) -> JsonMap<String, Value> {
        core::mem::take(&mut self.definitions)
    }

    /// Returns an iterator over the [transforms](SchemaSettings::transforms) being used by this
    /// `SchemaGenerator`.
    pub fn transforms_mut(&mut self) -> impl Iterator<Item = &mut dyn GenTransform> {
        self.settings.transforms.iter_mut().map(Box::as_mut)
    }

    /// Generates a JSON Schema for the type `T`.
    ///
    /// If `T`'s schema depends on any [non-inlined](JsonSchema::always_inline_schema) schemas, then
    /// this method will include them in the returned `Schema` at the [definitions
    /// path](SchemaSettings::definitions_path) (by default `"$defs"`).
    pub fn root_schema_for<T: ?Sized + JsonSchema>(&mut self) -> Schema {
        let mut schema = self.json_schema_internal::<T>(self.schema_uid::<T>());

        let object = schema.ensure_object();

        object
            .entry("title")
            .or_insert_with(|| T::schema_name().into());

        if let Some(meta_schema) = self.settings.meta_schema.as_deref() {
            object.insert("$schema".into(), meta_schema.into());
        }

        self.add_definitions(object, self.definitions.clone());
        self.apply_transforms(&mut schema);

        schema
    }

    /// Consumes `self` and generates a JSON Schema for the type `T`.
    ///
    /// If `T`'s schema depends on any [non-inlined](JsonSchema::always_inline_schema) schemas, then
    /// this method will include them in the returned `Schema` at the [definitions
    /// path](SchemaSettings::definitions_path) (by default `"$defs"`).
    pub fn into_root_schema_for<T: ?Sized + JsonSchema>(mut self) -> Schema {
        let mut schema = self.json_schema_internal::<T>(self.schema_uid::<T>());

        let object = schema.ensure_object();

        object
            .entry("title")
            .or_insert_with(|| T::schema_name().into());

        if let Some(meta_schema) = core::mem::take(&mut self.settings.meta_schema) {
            object.insert("$schema".into(), meta_schema.into());
        }

        let definitions = self.take_definitions();
        self.add_definitions(object, definitions);
        self.apply_transforms(&mut schema);

        schema
    }

    /// Generates a JSON Schema for the given example value.
    ///
    /// If the value implements [`JsonSchema`], then prefer using the
    /// [`root_schema_for()`](Self::root_schema_for()) function which will generally produce a
    /// more precise schema, particularly when the value contains any enums.
    ///
    /// If the `Serialize` implementation of the value decides to fail, this will return an [`Err`].
    pub fn root_schema_for_value<T: ?Sized + Serialize>(
        &mut self,
        value: &T,
    ) -> Result<Schema, serde_json::Error> {
        let mut schema = value.serialize(crate::ser::Serializer {
            generator: self,
            include_title: true,
        })?;

        let object = schema.ensure_object();

        if let Ok(example) = serde_json::to_value(value) {
            object.insert("examples".into(), vec![example].into());
        }

        if let Some(meta_schema) = self.settings.meta_schema.as_deref() {
            object.insert("$schema".into(), meta_schema.into());
        }

        self.add_definitions(object, self.definitions.clone());
        self.apply_transforms(&mut schema);

        Ok(schema)
    }

    /// Consumes `self` and generates a JSON Schema for the given example value.
    ///
    /// If the value  implements [`JsonSchema`], then prefer using the
    /// [`into_root_schema_for()!`](Self::into_root_schema_for()) function which will generally
    /// produce a more precise schema, particularly when the value contains any enums.
    ///
    /// If the `Serialize` implementation of the value decides to fail, this will return an [`Err`].
    pub fn into_root_schema_for_value<T: ?Sized + Serialize>(
        mut self,
        value: &T,
    ) -> Result<Schema, serde_json::Error> {
        let mut schema = value.serialize(crate::ser::Serializer {
            generator: &mut self,
            include_title: true,
        })?;

        let object = schema.ensure_object();

        if let Ok(example) = serde_json::to_value(value) {
            object.insert("examples".into(), vec![example].into());
        }

        if let Some(meta_schema) = core::mem::take(&mut self.settings.meta_schema) {
            object.insert("$schema".into(), meta_schema.into());
        }

        let definitions = self.take_definitions();
        self.add_definitions(object, definitions);
        self.apply_transforms(&mut schema);

        Ok(schema)
    }

    /// Returns a reference to the [contract](SchemaSettings::contract) for the settings on this
    /// `SchemaGenerator`.
    ///
    /// This specifies whether generated schemas describe serialize or *de*serialize behaviour.
    pub fn contract(&self) -> &Contract {
        &self.settings.contract
    }

    fn json_schema_internal<T: ?Sized + JsonSchema>(&mut self, uid: SchemaUid) -> Schema {
        struct PendingSchemaState<'a> {
            generator: &'a mut SchemaGenerator,
            uid: SchemaUid,
            did_add: bool,
        }

        impl<'a> PendingSchemaState<'a> {
            fn new(generator: &'a mut SchemaGenerator, uid: SchemaUid) -> Self {
                let did_add = generator.pending_schema_ids.insert(uid.clone());
                Self {
                    generator,
                    uid,
                    did_add,
                }
            }
        }

        impl Drop for PendingSchemaState<'_> {
            fn drop(&mut self) {
                if self.did_add {
                    self.generator.pending_schema_ids.remove(&self.uid);
                }
            }
        }

        let pss = PendingSchemaState::new(self, uid);
        T::json_schema(pss.generator)
    }

    fn add_definitions(
        &mut self,
        schema_object: &mut JsonMap<String, Value>,
        mut definitions: JsonMap<String, Value>,
    ) {
        if definitions.is_empty() {
            return;
        }

        let pointer = self.definitions_path_stripped();
        let Some(target) = json_pointer_mut(schema_object, pointer, true) else {
            return;
        };

        target.append(&mut definitions);
    }

    fn apply_transforms(&mut self, schema: &mut Schema) {
        for transform in self.transforms_mut() {
            transform.transform(schema);
        }
    }

    /// Returns `self.settings.definitions_path` as a plain JSON pointer to the definitions object,
    /// i.e. without a leading '#' or trailing '/'
    fn definitions_path_stripped(&self) -> &str {
        let path = &self.settings.definitions_path;
        let path = path.strip_prefix('#').unwrap_or(path);
        path.strip_suffix('/').unwrap_or(path)
    }

    fn schema_uid<T: ?Sized + JsonSchema>(&self) -> SchemaUid {
        SchemaUid(T::schema_id(), self.settings.contract.clone())
    }
}

fn json_pointer_mut<'a>(
    mut object: &'a mut JsonMap<String, Value>,
    pointer: &str,
    create_if_missing: bool,
) -> Option<&'a mut JsonMap<String, Value>> {
    use serde_json::map::Entry;

    let pointer = pointer.strip_prefix('/')?;
    if pointer.is_empty() {
        return Some(object);
    }

    for mut segment in pointer.split('/') {
        let replaced: String;
        if segment.contains('~') {
            replaced = segment.replace("~1", "/").replace("~0", "~");
            segment = &replaced;
        }

        let next_value = match object.entry(segment) {
            Entry::Occupied(o) => o.into_mut(),
            Entry::Vacant(v) if create_if_missing => v.insert(Value::Object(JsonMap::default())),
            Entry::Vacant(_) => return None,
        };

        object = next_value.as_object_mut()?;
    }

    Some(object)
}

/// A [`Transform`] which implements additional traits required to be included in a
/// [`SchemaSettings`].
///
/// You will rarely need to use this trait directly as it is automatically implemented for any type
/// which implements all of:
/// - [`Transform`]
/// - [`std::any::Any`] (implemented for all `'static` types)
/// - [`std::clone::Clone`]
/// - [`std::marker::Send`]
///
/// # Example
/// ```
/// use schemars::transform::Transform;
/// use schemars::generate::GenTransform;
///
/// #[derive(Debug, Clone)]
/// struct MyTransform;
///
/// impl Transform for MyTransform {
///   fn transform(&mut self, schema: &mut schemars::Schema) {
///     todo!()
///   }
/// }
///
/// let v: &dyn GenTransform = &MyTransform;
/// assert!(v.as_any().is::<MyTransform>());
/// ```
pub trait GenTransform: Transform + DynClone + Any + Send {
    /// Upcasts this transform into an [`Any`], which can be used to inspect and manipulate it as
    /// its concrete type.
    ///
    /// # Example
    /// To remove a specific transform from an instance of `SchemaSettings`:
    /// ```
    /// use schemars::generate::SchemaSettings;
    /// use schemars::transform::ReplaceBoolSchemas;
    ///
    /// let mut settings = SchemaSettings::openapi3();
    /// let original_len = settings.transforms.len();
    ///
    /// settings
    ///     .transforms
    ///     .retain(|t| !t.as_any().is::<ReplaceBoolSchemas>());
    ///
    /// assert_eq!(settings.transforms.len(), original_len - 1);
    /// ```
    fn as_any(&self) -> &dyn Any;

    /// Mutably upcasts this transform into an [`Any`], which can be used to inspect and manipulate
    /// it as its concrete type.
    ///
    /// # Example
    /// To modify a specific transform in an instance of `SchemaSettings`:
    /// ```
    /// use schemars::generate::SchemaSettings;
    /// use schemars::transform::ReplaceBoolSchemas;
    ///
    /// let mut settings = SchemaSettings::openapi3();
    /// for t in &mut settings.transforms {
    ///     if let Some(replace_bool_schemas) = t.as_any_mut().downcast_mut::<ReplaceBoolSchemas>() {
    ///         replace_bool_schemas.skip_additional_properties = false;
    ///     }
    /// }
    /// ```
    fn as_any_mut(&mut self) -> &mut dyn Any;
}

dyn_clone::clone_trait_object!(GenTransform);

impl<T> GenTransform for T
where
    T: Transform + Clone + Any + Send,
{
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

impl Debug for Box<dyn GenTransform> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self._debug_type_name(f)
    }
}

fn _assert_send() {
    fn _assert<T: Send>() {}

    _assert::<SchemaSettings>();
    _assert::<SchemaGenerator>();
}