apollo-configuration 0.4.0

A typed, friendly configuration system for Apollo products.
Documentation
//! Support for regular expressions in configuration.

use std::borrow::Cow;

use derive_more::{Deref, Display, From, FromStr};
use schemars::JsonSchema;
use serde::de::Deserializer;
use serde::{Deserialize, Serialize};

use crate::Validate;

/// A regular expression parsed from configuration.
#[derive(Debug, Clone, Deref, From, FromStr, Display)]
pub struct Regex(regex::Regex);

impl<'de> Deserialize<'de> for Regex {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        regex::Regex::new(&s)
            .map(Self)
            .map_err(serde::de::Error::custom)
    }
}

impl Serialize for Regex {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.0.as_str().serialize(serializer)
    }
}

impl JsonSchema for Regex {
    fn schema_name() -> Cow<'static, str> {
        Cow::Borrowed("Regex")
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        String::json_schema(generator)
    }
}

impl Validate for Regex {}