Skip to main content

vld/primitives/
adapter.rs

1//! Adapters for existing Rust types: [`ZFromSerde`], [`ZFromStr`], [`ZEnumOf`].
2
3use serde_json::Value;
4use std::fmt::Display;
5use std::marker::PhantomData;
6use std::str::FromStr;
7
8use crate::error::{FormatKind, IssueCode, VldError};
9use crate::schema::VldSchema;
10
11/// Schema that deserializes the JSON value into any `T: DeserializeOwned`.
12/// Created via [`vld::from_serde()`](crate::from_serde).
13///
14/// A serde error becomes one `parse_error` issue whose message is the serde
15/// message. JSON Schema is `{}` (any) unless set with [`schema`](Self::schema).
16///
17/// # Example
18/// ```
19/// use vld::prelude::*;
20///
21/// #[derive(Debug, PartialEq, serde::Deserialize)]
22/// #[serde(rename_all = "lowercase")]
23/// enum Role { Admin, User }
24///
25/// let role = vld::from_serde::<Role>();
26/// assert_eq!(role.parse(r#""admin""#).unwrap(), Role::Admin);
27/// let err = role.parse(r#""root""#).unwrap_err();
28/// assert!(err.issues[0].message.contains("unknown variant"));
29/// ```
30pub struct ZFromSerde<T> {
31    schema: Value,
32    _type: PhantomData<fn() -> T>,
33}
34
35impl<T> ZFromSerde<T> {
36    /// Create the schema (the same as its `vld::` constructor function).
37    pub fn new() -> Self {
38        Self {
39            schema: serde_json::json!({}),
40            _type: PhantomData,
41        }
42    }
43
44    /// JSON Schema to report for this type (default `{}`).
45    pub fn schema(mut self, schema: Value) -> Self {
46        self.schema = schema;
47        self
48    }
49}
50
51impl<T> Default for ZFromSerde<T> {
52    fn default() -> Self {
53        Self::new()
54    }
55}
56
57impl<T> Clone for ZFromSerde<T> {
58    fn clone(&self) -> Self {
59        Self {
60            schema: self.schema.clone(),
61            _type: PhantomData,
62        }
63    }
64}
65
66impl<T: serde::de::DeserializeOwned> VldSchema for ZFromSerde<T> {
67    type Output = T;
68
69    fn parse_value(&self, value: &Value) -> Result<T, VldError> {
70        T::deserialize(value)
71            .map_err(|e| VldError::single_with_value(IssueCode::ParseError, e.to_string(), value))
72    }
73}
74
75#[cfg(feature = "openapi")]
76impl<T> crate::openapi::JsonSchema for ZFromSerde<T> {
77    fn json_schema(&self) -> Value {
78        self.schema.clone()
79    }
80}
81
82#[cfg(feature = "openapi")]
83impl<T> crate::openapi::CollectNestedSchemas for ZFromSerde<T> {}
84
85/// Schema that parses a JSON string with `T: FromStr`.
86/// Created via [`vld::from_str()`](crate::from_str).
87///
88/// Non-string input fails with `invalid_type`; a parse error becomes one
89/// `invalid_format` (`from_str`) issue whose message is the error's `Display`.
90/// JSON Schema is `{"type": "string"}` unless set with [`schema`](Self::schema).
91///
92/// # Example
93/// ```
94/// use vld::prelude::*;
95/// use std::net::IpAddr;
96///
97/// let ip = vld::from_str::<IpAddr>();
98/// assert_eq!(ip.parse(r#""10.0.0.1""#).unwrap(), "10.0.0.1".parse::<IpAddr>().unwrap());
99/// assert!(ip.parse(r#""10.0.0.256""#).is_err());
100/// assert!(ip.parse("42").is_err());
101/// ```
102pub struct ZFromStr<T> {
103    schema: Value,
104    custom_type_error: Option<String>,
105    _type: PhantomData<fn() -> T>,
106}
107
108impl<T> ZFromStr<T> {
109    /// Create the schema (the same as its `vld::` constructor function).
110    pub fn new() -> Self {
111        Self {
112            schema: serde_json::json!({"type": "string"}),
113            custom_type_error: None,
114            _type: PhantomData,
115        }
116    }
117
118    /// JSON Schema to report for this type (default `{"type": "string"}`).
119    pub fn schema(mut self, schema: Value) -> Self {
120        self.schema = schema;
121        self
122    }
123
124    /// Set a custom error message for type mismatch (non-string input).
125    pub fn type_error(mut self, msg: impl Into<String>) -> Self {
126        self.custom_type_error = Some(msg.into());
127        self
128    }
129}
130
131impl<T> Default for ZFromStr<T> {
132    fn default() -> Self {
133        Self::new()
134    }
135}
136
137impl<T> Clone for ZFromStr<T> {
138    fn clone(&self) -> Self {
139        Self {
140            schema: self.schema.clone(),
141            custom_type_error: self.custom_type_error.clone(),
142            _type: PhantomData,
143        }
144    }
145}
146
147impl<T> VldSchema for ZFromStr<T>
148where
149    T: FromStr,
150    T::Err: Display,
151{
152    type Output = T;
153
154    fn parse_value(&self, value: &Value) -> Result<T, VldError> {
155        let s = value.as_str().ok_or_else(|| {
156            crate::primitives::type_error(&self.custom_type_error, "string", value)
157        })?;
158        s.parse::<T>().map_err(|e| {
159            VldError::single_with_value(
160                IssueCode::InvalidFormat {
161                    format: FormatKind::FromStr,
162                },
163                e.to_string(),
164                value,
165            )
166        })
167    }
168}
169
170#[cfg(feature = "openapi")]
171impl<T> crate::openapi::JsonSchema for ZFromStr<T> {
172    fn json_schema(&self) -> Value {
173        self.schema.clone()
174    }
175}
176
177#[cfg(feature = "openapi")]
178impl<T> crate::openapi::CollectNestedSchemas for ZFromStr<T> {}
179
180/// Schema mapping fixed strings to values of `T`.
181/// Created via [`vld::enum_of()`](crate::enum_of).
182///
183/// Unknown strings fail with `invalid_enum_value` listing the options.
184/// JSON Schema: `{"type": "string", "enum": [...]}`.
185///
186/// # Example
187/// ```
188/// use vld::prelude::*;
189///
190/// #[derive(Debug, Clone, PartialEq)]
191/// enum Role { Admin, User }
192///
193/// let role = vld::enum_of(&[("admin", Role::Admin), ("user", Role::User)]);
194/// assert_eq!(role.parse(r#""user""#).unwrap(), Role::User);
195/// assert!(role.parse(r#""root""#).is_err());
196/// ```
197#[derive(Clone)]
198pub struct ZEnumOf<T> {
199    variants: Vec<(String, T)>,
200    custom_type_error: Option<String>,
201}
202
203impl<T: Clone> ZEnumOf<T> {
204    /// Create the schema (the same as its `vld::` constructor function).
205    pub fn new(variants: &[(&str, T)]) -> Self {
206        Self {
207            variants: variants
208                .iter()
209                .map(|(k, v)| (k.to_string(), v.clone()))
210                .collect(),
211            custom_type_error: None,
212        }
213    }
214
215    /// Set a custom error message for type mismatch (non-string input).
216    pub fn type_error(mut self, msg: impl Into<String>) -> Self {
217        self.custom_type_error = Some(msg.into());
218        self
219    }
220
221    fn names(&self) -> Vec<String> {
222        self.variants.iter().map(|(k, _)| k.clone()).collect()
223    }
224}
225
226impl<T: Clone> VldSchema for ZEnumOf<T> {
227    type Output = T;
228
229    fn parse_value(&self, value: &Value) -> Result<T, VldError> {
230        let s = value.as_str().ok_or_else(|| {
231            crate::primitives::type_error(&self.custom_type_error, "string", value)
232        })?;
233        self.variants
234            .iter()
235            .find(|(k, _)| k == s)
236            .map(|(_, v)| v.clone())
237            .ok_or_else(|| {
238                VldError::from_code_with_value(
239                    IssueCode::InvalidEnumValue {
240                        options: self.names(),
241                    },
242                    value,
243                )
244            })
245    }
246}
247
248#[cfg(feature = "openapi")]
249impl<T: Clone> crate::openapi::JsonSchema for ZEnumOf<T> {
250    fn json_schema(&self) -> Value {
251        serde_json::json!({"type": "string", "enum": self.names()})
252    }
253}
254
255#[cfg(feature = "openapi")]
256impl<T> crate::openapi::CollectNestedSchemas for ZEnumOf<T> {}