apollo-configuration 0.4.0

A typed, friendly configuration system for Apollo products.
Documentation
//! Support for URL types in configuration.
//!
//! Provides a [`Url`] newtype with appropriate error handling.

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 URL parsed from configuration.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deref, From, FromStr, Display)]
pub struct Url(url::Url);

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

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

impl AsRef<str> for Url {
    fn as_ref(&self) -> &str {
        self.0.as_ref()
    }
}

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

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

impl Validate for Url {}