use super::{validate_static, validate_with_normalized_percent_encoding, InvalidScheme};
use shared_bytes::SharedStr;
use std::{hash::Hash, sync::Arc};
#[derive(Debug, Clone)]
pub struct Scheme(SharedStr);
impl Scheme {
#[track_caller]
#[inline]
pub const fn from_static(string: &'static str) -> Self {
match validate_static(string.as_bytes()) {
Ok(()) => Self(SharedStr::from_static(string)),
Err(_e) => panic!("invalid static Scheme"),
}
}
#[inline]
pub fn as_shared_str(&self) -> &SharedStr {
&self.0
}
#[inline]
pub fn into_shared_str(self) -> SharedStr {
self.0
}
#[inline]
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl Scheme {
#[inline]
pub const fn new() -> Self {
Self::from_static("https")
}
}
impl Default for Scheme {
#[inline]
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
#[test]
fn default_is_valid() {
let default_str = Scheme::default().into_shared_str();
Scheme::try_from(default_str).unwrap();
}
use std::hash::Hasher;
impl Hash for Scheme {
fn hash<H: Hasher>(&self, state: &mut H) {
for byte in self.0.bytes() {
state.write_u8(byte.to_ascii_lowercase())
}
}
}
impl PartialEq for Scheme {
fn eq(&self, other: &Self) -> bool {
self.0.eq_ignore_ascii_case(&other.0)
}
}
impl PartialEq<str> for Scheme {
fn eq(&self, other: &str) -> bool {
self.0.eq_ignore_ascii_case(other)
}
}
impl PartialEq<String> for Scheme {
fn eq(&self, other: &String) -> bool {
self.0.eq_ignore_ascii_case(other)
}
}
impl AsRef<str> for Scheme {
#[inline]
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl Eq for Scheme {}
impl From<Scheme> for SharedStr {
fn from(x: Scheme) -> Self {
x.into_shared_str()
}
}
impl From<Scheme> for String {
fn from(x: Scheme) -> Self {
x.into_shared_str().into_string()
}
}
impl<T> PartialEq<&'_ T> for Scheme
where
Self: PartialEq<T>,
T: ?Sized,
{
fn eq(&self, other: &&T) -> bool {
self.eq(*other)
}
}
impl TryFrom<&'static str> for Scheme {
type Error = InvalidScheme;
fn try_from(value: &'static str) -> Result<Self, Self::Error> {
let inner = validate_with_normalized_percent_encoding(value)?
.unwrap_or_else(|| SharedStr::from(value));
Ok(Self(inner))
}
}
impl TryFrom<String> for Scheme {
type Error = InvalidScheme;
fn try_from(value: String) -> Result<Self, Self::Error> {
let inner = validate_with_normalized_percent_encoding(&value)?
.unwrap_or_else(|| SharedStr::from(value));
Ok(Self(inner))
}
}
impl TryFrom<Arc<String>> for Scheme {
type Error = InvalidScheme;
fn try_from(value: Arc<String>) -> Result<Self, Self::Error> {
let inner = validate_with_normalized_percent_encoding(&value)?
.unwrap_or_else(|| SharedStr::from(value));
Ok(Self(inner))
}
}
impl TryFrom<SharedStr> for Scheme {
type Error = InvalidScheme;
fn try_from(value: SharedStr) -> Result<Self, Self::Error> {
let inner = validate_with_normalized_percent_encoding(&value)?.unwrap_or(value);
Ok(Self(inner))
}
}