ckb_schemars/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4/// The map type used by schemars types.
5///
6/// Currently a `BTreeMap` or `IndexMap` can be used, but this may change to a different implementation
7/// with a similar interface in a future version of schemars.
8/// The `IndexMap` will be used when the `preserve_order` feature flag is set.
9#[cfg(not(feature = "preserve_order"))]
10pub type Map<K, V> = std::collections::BTreeMap<K, V>;
11#[cfg(feature = "preserve_order")]
12pub type Map<K, V> = indexmap::IndexMap<K, V>;
13/// The set type used by schemars types.
14///
15/// Currently a `BTreeSet`, but this may change to a different implementation
16/// with a similar interface in a future version of schemars.
17pub type Set<T> = std::collections::BTreeSet<T>;
18
19/// A view into a single entry in a map, which may either be vacant or occupied.
20//
21/// This is constructed from the `entry` method on `BTreeMap` or `IndexMap`,
22/// depending on whether the `preserve_order` feature flag is set.
23#[cfg(not(feature = "preserve_order"))]
24pub type MapEntry<'a, K, V> = std::collections::btree_map::Entry<'a, K, V>;
25#[cfg(feature = "preserve_order")]
26pub type MapEntry<'a, K, V> = indexmap::map::Entry<'a, K, V>;
27
28mod flatten;
29mod json_schema_impls;
30mod ser;
31#[macro_use]
32mod macros;
33
34/// This module is only public for use by `schemars_derive`. It should not need to be used by code
35/// outside of `schemars`, and should not be considered part of the public API.
36#[doc(hidden)]
37pub mod _private;
38
39pub mod r#gen;
40pub mod schema;
41pub mod visit;
42
43pub use r#gen::SchemaGenerator;
44
45#[cfg(feature = "schemars_derive")]
46extern crate schemars_derive;
47use std::borrow::Cow;
48
49#[cfg(feature = "schemars_derive")]
50pub use schemars_derive::*;
51
52// Export serde_json so schemars_derive can use it
53#[doc(hidden)]
54pub use serde_json as _serde_json;
55
56use schema::Schema;
57
58/// A type which can be described as a JSON Schema document.
59///
60/// This is implemented for many Rust primitive and standard library types.
61///
62/// This can also be automatically derived on most custom types with `#[derive(JsonSchema)]`.
63///
64/// # Examples
65/// Deriving an implementation:
66/// ```
67/// use schemars::{schema_for, JsonSchema};
68///
69/// #[derive(JsonSchema)]
70/// struct MyStruct {
71///     foo: i32,
72/// }
73///
74/// let my_schema = schema_for!(MyStruct);
75/// ```
76///
77/// When manually implementing `JsonSchema`, as well as determining an appropriate schema,
78/// you will need to determine an appropriate name and ID for the type.
79/// For non-generic types, the type name/path are suitable for this:
80/// ```
81/// use schemars::{r#gen::SchemaGenerator, schema::Schema, JsonSchema};
82/// use std::borrow::Cow;
83///
84/// struct NonGenericType;
85///
86/// impl JsonSchema for NonGenericType {
87///     fn schema_name() -> String {
88///         // Exclude the module path to make the name in generated schemas clearer.
89///         "NonGenericType".to_owned()
90///     }
91///
92///     fn schema_id() -> Cow<'static, str> {
93///         // Include the module, in case a type with the same name is in another module/crate
94///         Cow::Borrowed(concat!(module_path!(), "::NonGenericType"))
95///     }
96///
97///     fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
98///         todo!()
99///     }
100/// }
101///
102/// assert_eq!(NonGenericType::schema_id(), <&mut NonGenericType>::schema_id());
103/// ```
104///
105/// But generic type parameters which may affect the generated schema should typically be included in the name/ID:
106/// ```
107/// use schemars::{r#gen::SchemaGenerator, schema::Schema, JsonSchema};
108/// use std::{borrow::Cow, marker::PhantomData};
109///
110/// struct GenericType<T>(PhantomData<T>);
111///
112/// impl<T: JsonSchema> JsonSchema for GenericType<T> {
113///     fn schema_name() -> String {
114///         format!("GenericType_{}", T::schema_name())
115///     }
116///
117///     fn schema_id() -> Cow<'static, str> {
118///         Cow::Owned(format!(
119///             "{}::GenericType<{}>",
120///             module_path!(),
121///             T::schema_id()
122///         ))
123///     }
124///
125///     fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
126///         todo!()
127///     }
128/// }
129///
130/// assert_eq!(<GenericType<i32>>::schema_id(), <&mut GenericType<&i32>>::schema_id());
131/// ```
132///
133pub trait JsonSchema {
134    /// Whether JSON Schemas generated for this type should be re-used where possible using the `$ref` keyword.
135    ///
136    /// For trivial types (such as primitives), this should return `false`. For more complex types, it should return `true`.
137    /// For recursive types, this **must** return `true` to prevent infinite cycles when generating schemas.
138    ///
139    /// By default, this returns `true`.
140    fn is_referenceable() -> bool {
141        true
142    }
143
144    /// The name of the generated JSON Schema.
145    ///
146    /// This is used as the title for root schemas, and the key within the root's `definitions` property for subschemas.
147    fn schema_name() -> String;
148
149    /// Returns a string that uniquely identifies the schema produced by this type.
150    ///
151    /// This does not have to be a human-readable string, and the value will not itself be included in generated schemas.
152    /// If two types produce different schemas, then they **must** have different `schema_id()`s,
153    /// but two types that produce identical schemas should *ideally* have the same `schema_id()`.
154    ///
155    /// The default implementation returns the same value as `schema_name()`.
156    fn schema_id() -> Cow<'static, str> {
157        Cow::Owned(Self::schema_name())
158    }
159
160    /// Generates a JSON Schema for this type.
161    ///
162    /// If the returned schema depends on any [referenceable](JsonSchema::is_referenceable) schemas, then this method will
163    /// add them to the [`SchemaGenerator`](r#gen::SchemaGenerator)'s schema definitions.
164    ///
165    /// This should not return a `$ref` schema.
166    fn json_schema(generator: &mut r#gen::SchemaGenerator) -> Schema;
167
168    // TODO document and bring into public API?
169    #[doc(hidden)]
170    fn _schemars_private_non_optional_json_schema(generator: &mut r#gen::SchemaGenerator) -> Schema {
171        Self::json_schema(generator)
172    }
173
174    // TODO document and bring into public API?
175    #[doc(hidden)]
176    fn _schemars_private_is_option() -> bool {
177        false
178    }
179}
180
181#[cfg(test)]
182pub mod tests {
183    use super::*;
184
185    pub fn schema_object_for<T: JsonSchema>() -> schema::SchemaObject {
186        schema_object(schema_for::<T>())
187    }
188
189    pub fn schema_for<T: JsonSchema>() -> schema::Schema {
190        let mut generator = r#gen::SchemaGenerator::default();
191        T::json_schema(&mut generator)
192    }
193
194    pub fn schema_object(schema: schema::Schema) -> schema::SchemaObject {
195        match schema {
196            schema::Schema::Object(o) => o,
197            s => panic!("Schema was not an object: {:?}", s),
198        }
199    }
200}