use std::convert::Infallible;
use http::{Uri, uri::InvalidUri};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EndpointUrl(Uri);
impl Serialize for EndpointUrl {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0.to_string())
}
}
impl<'de> Deserialize<'de> for EndpointUrl {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
s.into_endpoint_url().map_err(serde::de::Error::custom)
}
}
impl EndpointUrl {
#[must_use]
pub fn as_uri(&self) -> &Uri {
&self.0
}
#[must_use]
pub fn into_uri(self) -> Uri {
self.0
}
}
pub trait IntoEndpointUrl {
type Error: crate::Error;
fn into_endpoint_url(self) -> Result<EndpointUrl, Self::Error>;
}
impl IntoEndpointUrl for EndpointUrl {
type Error = Infallible;
fn into_endpoint_url(self) -> Result<EndpointUrl, Self::Error> {
Ok(self)
}
}
impl IntoEndpointUrl for Uri {
type Error = Infallible;
fn into_endpoint_url(self) -> Result<EndpointUrl, Self::Error> {
Ok(EndpointUrl(self))
}
}
#[cfg(feature = "url")]
impl IntoEndpointUrl for url::Url {
type Error = InvalidUri;
fn into_endpoint_url(self) -> Result<EndpointUrl, Self::Error> {
self.as_str().parse::<Uri>().map(EndpointUrl)
}
}
impl IntoEndpointUrl for &str {
type Error = InvalidUri;
fn into_endpoint_url(self) -> Result<EndpointUrl, Self::Error> {
self.parse::<Uri>().map(EndpointUrl)
}
}
impl IntoEndpointUrl for String {
type Error = InvalidUri;
fn into_endpoint_url(self) -> Result<EndpointUrl, Self::Error> {
self.parse::<Uri>().map(EndpointUrl)
}
}