use std::{
borrow::Cow,
cell::{Ref, RefMut},
error::Error,
fmt,
rc::Rc,
sync::Arc,
};
use constant_string::constant_string;
use url::{ParseError, Url};
constant_string!(UrlErrorCode, URL_ERROR_CODE, "url");
#[derive(Debug, Eq, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
serde(
tag = "subcode",
rename_all = "camelCase",
rename_all_fields = "camelCase"
)
)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum UrlError {
EmptyHost {
#[cfg_attr(feature = "serde", serde(default))]
#[cfg_attr(feature = "utoipa", schema(inline, required))]
code: UrlErrorCode,
#[cfg(feature = "message")]
message: String,
},
IdnaError {
#[cfg_attr(feature = "serde", serde(default))]
#[cfg_attr(feature = "utoipa", schema(inline, required))]
code: UrlErrorCode,
#[cfg(feature = "message")]
message: String,
},
InvalidPort {
#[cfg_attr(feature = "serde", serde(default))]
#[cfg_attr(feature = "utoipa", schema(inline, required))]
code: UrlErrorCode,
#[cfg(feature = "message")]
message: String,
},
InvalidIpv4Address {
#[cfg_attr(feature = "serde", serde(default))]
#[cfg_attr(feature = "utoipa", schema(inline, required))]
code: UrlErrorCode,
#[cfg(feature = "message")]
message: String,
},
InvalidIpv6Address {
#[cfg_attr(feature = "serde", serde(default))]
#[cfg_attr(feature = "utoipa", schema(inline, required))]
code: UrlErrorCode,
#[cfg(feature = "message")]
message: String,
},
InvalidDomainCharacter {
#[cfg_attr(feature = "serde", serde(default))]
#[cfg_attr(feature = "utoipa", schema(inline, required))]
code: UrlErrorCode,
#[cfg(feature = "message")]
message: String,
},
RelativeUrlWithoutBase {
#[cfg_attr(feature = "serde", serde(default))]
#[cfg_attr(feature = "utoipa", schema(inline, required))]
code: UrlErrorCode,
#[cfg(feature = "message")]
message: String,
},
RelativeUrlWithCannotBeABaseBase {
#[cfg_attr(feature = "serde", serde(default))]
#[cfg_attr(feature = "utoipa", schema(inline, required))]
code: UrlErrorCode,
#[cfg(feature = "message")]
message: String,
},
SetHostOnCannotBeABaseUrl {
#[cfg_attr(feature = "serde", serde(default))]
#[cfg_attr(feature = "utoipa", schema(inline, required))]
code: UrlErrorCode,
#[cfg(feature = "message")]
message: String,
},
Overflow {
#[cfg_attr(feature = "serde", serde(default))]
#[cfg_attr(feature = "utoipa", schema(inline, required))]
code: UrlErrorCode,
#[cfg(feature = "message")]
message: String,
},
Unknown {
#[cfg_attr(feature = "serde", serde(default))]
#[cfg_attr(feature = "utoipa", schema(inline, required))]
code: UrlErrorCode,
#[cfg(feature = "message")]
message: String,
},
}
impl fmt::Display for UrlError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:#?}")
}
}
impl Error for UrlError {}
impl From<ParseError> for UrlError {
fn from(value: ParseError) -> Self {
let code = UrlErrorCode;
match value {
ParseError::EmptyHost => UrlError::EmptyHost {
code,
#[cfg(feature = "message")]
message: value.to_string(),
},
ParseError::IdnaError => UrlError::IdnaError {
code,
#[cfg(feature = "message")]
message: value.to_string(),
},
ParseError::InvalidPort => UrlError::InvalidPort {
code,
#[cfg(feature = "message")]
message: value.to_string(),
},
ParseError::InvalidIpv4Address => UrlError::InvalidIpv4Address {
code,
#[cfg(feature = "message")]
message: value.to_string(),
},
ParseError::InvalidIpv6Address => UrlError::InvalidIpv6Address {
code,
#[cfg(feature = "message")]
message: value.to_string(),
},
ParseError::InvalidDomainCharacter => UrlError::InvalidDomainCharacter {
code,
#[cfg(feature = "message")]
message: value.to_string(),
},
ParseError::RelativeUrlWithoutBase => UrlError::RelativeUrlWithoutBase {
code,
#[cfg(feature = "message")]
message: value.to_string(),
},
ParseError::RelativeUrlWithCannotBeABaseBase => {
UrlError::RelativeUrlWithCannotBeABaseBase {
code,
#[cfg(feature = "message")]
message: value.to_string(),
}
}
ParseError::SetHostOnCannotBeABaseUrl => UrlError::SetHostOnCannotBeABaseUrl {
code,
#[cfg(feature = "message")]
message: value.to_string(),
},
ParseError::Overflow => UrlError::Overflow {
code,
#[cfg(feature = "message")]
message: value.to_string(),
},
#[cfg_attr(not(feature = "message"), allow(unused_variables))]
value => UrlError::Overflow {
code,
#[cfg(feature = "message")]
message: value.to_string(),
},
}
}
}
pub trait ValidateUrl {
fn url(&self) -> Option<Cow<'_, str>>;
fn validate_url(&self) -> Result<(), UrlError> {
let Some(url) = self.url() else {
return Ok(());
};
Url::parse(&url).map_err(UrlError::from)?;
Ok(())
}
}
impl ValidateUrl for str {
fn url(&self) -> Option<Cow<'_, str>> {
Some(self.into())
}
}
impl ValidateUrl for &str {
fn url(&self) -> Option<Cow<'_, str>> {
Some((*self).into())
}
}
impl ValidateUrl for String {
fn url(&self) -> Option<Cow<'_, str>> {
Some(self.into())
}
}
impl ValidateUrl for Cow<'_, str> {
fn url(&self) -> Option<Cow<'_, str>> {
Some(self.clone())
}
}
impl ValidateUrl for Url {
fn url(&self) -> Option<Cow<'_, str>> {
Some(self.as_str().into())
}
fn validate_url(&self) -> Result<(), UrlError> {
Ok(())
}
}
impl<T> ValidateUrl for Option<T>
where
T: ValidateUrl,
{
fn url(&self) -> Option<Cow<'_, str>> {
if let Some(url) = self {
T::url(url)
} else {
None
}
}
}
macro_rules! validate_with_deref {
($type:ty) => {
impl<T> ValidateUrl for $type
where
T: ValidateUrl,
{
fn url(&self) -> Option<Cow<'_, str>> {
T::url(self)
}
}
};
}
validate_with_deref!(&T);
validate_with_deref!(Arc<T>);
validate_with_deref!(Box<T>);
validate_with_deref!(Rc<T>);
validate_with_deref!(Ref<'_, T>);
validate_with_deref!(RefMut<'_, T>);
#[cfg(test)]
mod tests {
use std::{borrow::Cow, cell::RefCell, rc::Rc, sync::Arc};
use url::{ParseError, Url};
use crate::UrlErrorCode;
use super::{UrlError, ValidateUrl};
#[test]
fn ok() {
assert_eq!((*"http://localhost").validate_url(), Ok(()));
assert_eq!("http://localhost".validate_url(), Ok(()));
assert_eq!("http://localhost".to_owned().validate_url(), Ok(()));
assert_eq!(
Cow::<str>::Borrowed("http://localhost").validate_url(),
Ok(())
);
assert_eq!(
Cow::<str>::Owned("http://localhost".to_owned()).validate_url(),
Ok(())
);
assert_eq!(
Url::parse("http://localhost")
.expect("valid URL")
.validate_url(),
Ok(())
);
assert_eq!(None::<&str>.validate_url(), Ok(()));
assert_eq!(Some("http://localhost").validate_url(), Ok(()));
assert_eq!((&"http://localhost").validate_url(), Ok(()));
assert_eq!(Box::new("http://localhost").validate_url(), Ok(()));
assert_eq!(Arc::new("http://localhost").validate_url(), Ok(()));
assert_eq!(Rc::new("http://localhost").validate_url(), Ok(()));
let cell = RefCell::new("http://localhost");
assert_eq!(cell.borrow().validate_url(), Ok(()));
assert_eq!(cell.borrow_mut().validate_url(), Ok(()));
}
#[test]
fn parse_error() {
assert_eq!(
(*"http://").validate_url(),
Err(UrlError::from(ParseError::EmptyHost))
);
assert_eq!(
"http://".validate_url(),
Err(UrlError::from(ParseError::EmptyHost))
);
assert_eq!(
"http://".to_owned().validate_url(),
Err(UrlError::from(ParseError::EmptyHost))
);
assert_eq!(
Cow::<str>::Borrowed("http://").validate_url(),
Err(UrlError::from(ParseError::EmptyHost))
);
assert_eq!(
Cow::<str>::Owned("http://".to_owned()).validate_url(),
Err(UrlError::from(ParseError::EmptyHost))
);
assert_eq!(
Some("http://").validate_url(),
Err(UrlError::from(ParseError::EmptyHost))
);
assert_eq!(
(&"http://").validate_url(),
Err(UrlError::from(ParseError::EmptyHost))
);
assert_eq!(
Box::new("http://").validate_url(),
Err(UrlError::EmptyHost {
code: UrlErrorCode,
#[cfg(feature = "message")]
message: "empty host".to_owned(),
})
);
assert_eq!(
Arc::new("http://").validate_url(),
Err(UrlError::from(ParseError::EmptyHost))
);
assert_eq!(
Rc::new("http://").validate_url(),
Err(UrlError::from(ParseError::EmptyHost))
);
let cell = RefCell::new("http://");
assert_eq!(
cell.borrow().validate_url(),
Err(UrlError::from(ParseError::EmptyHost))
);
assert_eq!(
cell.borrow_mut().validate_url(),
Err(UrlError::from(ParseError::EmptyHost))
);
}
}