Skip to main content

apollo_configuration/types/
regex.rs

1//! Support for regular expressions in configuration.
2
3use std::borrow::Cow;
4
5use derive_more::{Deref, Display, From, FromStr};
6use schemars::JsonSchema;
7use serde::de::Deserializer;
8use serde::{Deserialize, Serialize};
9
10use crate::Validate;
11
12/// A regular expression parsed from configuration.
13#[derive(Debug, Clone, Deref, From, FromStr, Display)]
14pub struct Regex(regex::Regex);
15
16impl<'de> Deserialize<'de> for Regex {
17    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
18    where
19        D: Deserializer<'de>,
20    {
21        let s = String::deserialize(deserializer)?;
22        regex::Regex::new(&s)
23            .map(Self)
24            .map_err(serde::de::Error::custom)
25    }
26}
27
28impl Serialize for Regex {
29    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
30    where
31        S: serde::Serializer,
32    {
33        self.0.as_str().serialize(serializer)
34    }
35}
36
37impl JsonSchema for Regex {
38    fn schema_name() -> Cow<'static, str> {
39        Cow::Borrowed("Regex")
40    }
41
42    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
43        String::json_schema(generator)
44    }
45}
46
47impl Validate for Regex {}