poem_openapi/types/
string_types.rs1use std::{
2 borrow::Cow,
3 ops::{Deref, DerefMut},
4};
5
6use serde_json::Value;
7
8use crate::{
9 registry::{MetaSchema, MetaSchemaRef},
10 types::{ParseError, ParseFromJSON, ParseFromParameter, ParseResult, ToJSON, Type},
11};
12
13macro_rules! impl_string_types {
14 ($(#[$docs:meta])* $ty:ident, $type_name:literal, $format:literal) => {
15 impl_string_types!($(#[$docs])* $ty, $type_name, $format, |_| true);
16 };
17
18 ($(#[$docs:meta])* $ty:ident, $type_name:literal, $format:literal, $validator:expr) => {
19 $(#[$docs])*
20 #[derive(Debug, Clone, Eq, PartialEq, Hash)]
21 pub struct $ty(pub String);
22
23 impl Deref for $ty {
24 type Target = String;
25
26 fn deref(&self) -> &Self::Target {
27 &self.0
28 }
29 }
30
31 impl DerefMut for $ty {
32 fn deref_mut(&mut self) -> &mut Self::Target {
33 &mut self.0
34 }
35 }
36
37 impl AsRef<str> for $ty {
38 fn as_ref(&self) -> &str {
39 &self.0
40 }
41 }
42
43 impl Type for $ty {
44 const IS_REQUIRED: bool = true;
45
46 type RawValueType = Self;
47
48 type RawElementValueType = Self;
49
50 fn name() -> Cow<'static, str> {
51 concat!($type_name, "_", $format).into()
52 }
53
54 fn schema_ref() -> MetaSchemaRef {
55 MetaSchemaRef::Inline(Box::new(MetaSchema::new_with_format($type_name, $format)))
56 }
57
58 fn as_raw_value(&self) -> Option<&Self::RawValueType> {
59 Some(self)
60 }
61
62 fn raw_element_iter<'a>(
63 &'a self,
64 ) -> Box<dyn Iterator<Item = &'a Self::RawElementValueType> + 'a> {
65 Box::new(self.as_raw_value().into_iter())
66 }
67
68 #[inline]
69 fn is_empty(&self) -> bool {
70 self.0.is_empty()
71 }
72 }
73
74 impl ParseFromJSON for $ty {
75 fn parse_from_json(value: Option<Value>) -> ParseResult<Self> {
76 let value = value.unwrap_or_default();
77 if let Value::String(value) = value {
78 let validator = $validator;
79 if !validator(&value) {
80 return Err(concat!("invalid ", $format).into());
81 }
82 Ok(Self(value))
83 } else {
84 Err(ParseError::expected_type(value))
85 }
86 }
87 }
88
89 impl ParseFromParameter for $ty {
90 fn parse_from_parameter(value: &str) -> ParseResult<Self> {
91 let validator = $validator;
92 if !validator(value) {
93 return Err(concat!("invalid ", $format).into());
94 }
95 Ok(Self(value.to_string()))
96 }
97 }
98
99 impl ToJSON for $ty {
100 fn to_json(&self) -> Option<Value> {
101 Some(Value::String(self.0.clone()))
102 }
103 }
104 };
105}
106
107impl_string_types!(
108 Password,
113 "string",
114 "password"
115);
116
117#[cfg(feature = "email")]
118impl_string_types!(
119 #[cfg_attr(docsrs, doc(cfg(feature = "email")))]
121 Email,
122 "string",
123 "email",
124 email_address::EmailAddress::is_valid
125);
126
127#[cfg(feature = "hostname")]
128impl_string_types!(
129 #[cfg_attr(docsrs, doc(cfg(feature = "hostname")))]
131 Hostname,
132 "string",
133 "hostname",
134 hostname_validator::is_valid
135);