cog_schemars/json_schema_impls/
primitives.rs1use crate::SchemaGenerator;
2use crate::_alloc_prelude::*;
3use crate::{json_schema, JsonSchema, Schema};
4use alloc::borrow::Cow;
5
6macro_rules! simple_impl {
7 ($type:ty => $instance_type:literal) => {
8 impl JsonSchema for $type {
9 always_inline!();
10
11 fn schema_name() -> Cow<'static, str> {
12 $instance_type.into()
13 }
14
15 fn json_schema(_: &mut SchemaGenerator) -> Schema {
16 json_schema!({
17 "type": $instance_type
18 })
19 }
20 }
21 };
22 ($type:ty => $instance_type:literal, $format:literal) => {
23 impl JsonSchema for $type {
24 always_inline!();
25
26 fn schema_name() -> Cow<'static, str> {
27 $format.into()
28 }
29
30 fn json_schema(_: &mut SchemaGenerator) -> Schema {
31 json_schema!({
32 "type": $instance_type,
33 "format": $format
34 })
35 }
36 }
37 };
38}
39
40simple_impl!(str => "string");
41simple_impl!(String => "string");
42simple_impl!(bool => "boolean");
43simple_impl!(f32 => "number", "float");
44simple_impl!(f64 => "number", "double");
45simple_impl!(i8 => "integer", "int8");
46simple_impl!(i16 => "integer", "int16");
47simple_impl!(i32 => "integer", "int32");
48simple_impl!(i64 => "integer", "int64");
49simple_impl!(i128 => "integer", "int128");
50simple_impl!(isize => "integer", "int");
51simple_impl!(() => "null");
52
53#[cfg(feature = "std")]
54mod std_types {
55 use super::*;
56 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
57 use std::path::{Path, PathBuf};
58
59 simple_impl!(Path => "string");
60 simple_impl!(PathBuf => "string");
61
62 simple_impl!(Ipv4Addr => "string", "ipv4");
63 simple_impl!(Ipv6Addr => "string", "ipv6");
64 simple_impl!(IpAddr => "string", "ip");
65
66 simple_impl!(SocketAddr => "string");
67 simple_impl!(SocketAddrV4 => "string");
68 simple_impl!(SocketAddrV6 => "string");
69}
70
71macro_rules! unsigned_impl {
72 ($type:ty => $instance_type:literal, $format:literal) => {
73 impl JsonSchema for $type {
74 always_inline!();
75
76 fn schema_name() -> Cow<'static, str> {
77 $format.into()
78 }
79
80 fn json_schema(_: &mut SchemaGenerator) -> Schema {
81 json_schema!({
82 "type": $instance_type,
83 "format": $format,
84 "minimum": 0
85 })
86 }
87 }
88 };
89}
90
91unsigned_impl!(u8 => "integer", "uint8");
92unsigned_impl!(u16 => "integer", "uint16");
93unsigned_impl!(u32 => "integer", "uint32");
94unsigned_impl!(u64 => "integer", "uint64");
95unsigned_impl!(u128 => "integer", "uint128");
96unsigned_impl!(usize => "integer", "uint");
97
98impl JsonSchema for char {
99 always_inline!();
100
101 fn schema_name() -> Cow<'static, str> {
102 "Character".into()
103 }
104
105 fn schema_id() -> Cow<'static, str> {
106 "char".into()
107 }
108
109 fn json_schema(_: &mut SchemaGenerator) -> Schema {
110 json_schema!({
111 "type": "string",
112 "minLength": 1,
113 "maxLength": 1,
114 })
115 }
116}