use super::{validate_static, validate_with_normalized_percent_encoding, InvalidPath};
use shared_bytes::SharedStr;
use std::{hash::Hash, sync::Arc};
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct Path(SharedStr);
impl Path {
#[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 Path"),
}
}
#[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 Path {
#[inline]
pub const fn new() -> Self {
Self::from_static("")
}
}
impl Default for Path {
#[inline]
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
#[test]
fn default_is_valid() {
let default_str = Path::default().into_shared_str();
Path::try_from(default_str).unwrap();
}
impl PartialEq<str> for Path {
fn eq(&self, other: &str) -> bool {
self.as_str() == other
}
}
impl PartialEq<String> for Path {
fn eq(&self, other: &String) -> bool {
self.as_str() == other
}
}
impl AsRef<str> for Path {
#[inline]
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl Eq for Path {}
impl From<Path> for SharedStr {
fn from(x: Path) -> Self {
x.into_shared_str()
}
}
impl From<Path> for String {
fn from(x: Path) -> Self {
x.into_shared_str().into_string()
}
}
impl<T> PartialEq<&'_ T> for Path
where
Self: PartialEq<T>,
T: ?Sized,
{
fn eq(&self, other: &&T) -> bool {
self.eq(*other)
}
}
impl TryFrom<&'static str> for Path {
type Error = InvalidPath;
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 Path {
type Error = InvalidPath;
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 Path {
type Error = InvalidPath;
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 Path {
type Error = InvalidPath;
fn try_from(value: SharedStr) -> Result<Self, Self::Error> {
let inner = validate_with_normalized_percent_encoding(&value)?.unwrap_or(value);
Ok(Self(inner))
}
}