Debian Codegraph @

src/features/schemars.rs

raw
1 #![cfg_attr(docsrs, doc(cfg(feature = "schemars")))]
2
3 use alloc::borrow::Cow;
4 use alloc::string::String;
5
6 use schemars::{JsonSchema, Schema, SchemaGenerator};
7
8 use crate::CompactString;
9
10 // A `CompactString` serializes exactly like a `std::string::String`, so its JSON
11 // schema should be identical. We delegate every method to `String`'s impl to keep
12 // the two perfectly in sync (name, id, inlining behavior, and the schema itself).
13 impl JsonSchema for CompactString {
14 fn inline_schema() -> bool {
15 <String as JsonSchema>::inline_schema()
16 }
17
18 fn schema_name() -> Cow<'static, str> {
19 <String as JsonSchema>::schema_name()
20 }
21
22 fn schema_id() -> Cow<'static, str> {
23 <String as JsonSchema>::schema_id()
24 }
25
26 fn json_schema(generator: &mut SchemaGenerator) -> Schema {
27 <String as JsonSchema>::json_schema(generator)
28 }
29 }
30
31 #[cfg(test)]
32 mod tests {
33 use alloc::string::String;
34
35 use schemars::{JsonSchema, SchemaGenerator};
36
37 use crate::CompactString;
38
39 #[test]
40 fn test_metadata_matches_string() {
41 assert_eq!(CompactString::schema_name(), String::schema_name());
42 assert_eq!(CompactString::schema_id(), String::schema_id());
43 assert_eq!(
44 CompactString::inline_schema(),
45 String::inline_schema(),
46 "inlining behavior must match String so nested schemas are identical",
47 );
48 }
49
50 #[test]
51 fn test_json_schema_matches_string() {
52 let mut compact_gen = SchemaGenerator::default();
53 let compact_schema = CompactString::json_schema(&mut compact_gen);
54
55 let mut string_gen = SchemaGenerator::default();
56 let string_schema = String::json_schema(&mut string_gen);
57
58 assert_eq!(compact_schema, string_schema);
59 }
60
61 #[test]
62 fn test_schema_describes_a_string() {
63 let mut generator = SchemaGenerator::default();
64 let schema = CompactString::json_schema(&mut generator);
65 let value = serde_json::to_value(&schema).unwrap();
66
67 assert_eq!(value.get("type").and_then(|t| t.as_str()), Some("string"));
68 }
69
70 // Even when generated as part of a larger document (which exercises the
71 // reference/definition machinery via `subschema_for`), the output for a
72 // `CompactString` field must be byte-for-byte identical to a `String` field.
73 #[test]
74 fn test_subschema_matches_string() {
75 let mut compact_gen = SchemaGenerator::default();
76 let compact_sub = compact_gen.subschema_for::<CompactString>();
77 let compact_defs = compact_gen.into_root_schema_for::<CompactString>();
78
79 let mut string_gen = SchemaGenerator::default();
80 let string_sub = string_gen.subschema_for::<String>();
81 let string_defs = string_gen.into_root_schema_for::<String>();
82
83 assert_eq!(
84 serde_json::to_value(&compact_sub).unwrap(),
85 serde_json::to_value(&string_sub).unwrap(),
86 );
87 assert_eq!(
88 serde_json::to_value(&compact_defs).unwrap(),
89 serde_json::to_value(&string_defs).unwrap(),
90 );
91 }
92 }