1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
use crate::validation::{
    is_sub_delimiter, is_unreserved, validate_percent_encoding, InvalidByte, InvalidComponent,
};
use boar_::BoasStr;
use std::{borrow::Borrow, convert::TryFrom, error::Error, fmt};

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Path<'a>(BoasStr<'a>);

impl<'a> Path<'a> {
    pub fn new() -> Self {
        Self(BoasStr::Static(""))
    }

    fn internal_try_from(string: BoasStr<'a>) -> Result<Self, InvalidPath> {
        validate(string.as_bytes())?;
        Ok(Self(string))
    }

    pub fn as_str(&self) -> &str {
        &*self.0
    }

    pub fn into_static(self) -> Path<'static> {
        Path(self.0.into_static())
    }

    pub fn to_borrowed(&self) -> Path {
        Path(self.0.to_borrowed())
    }
}

impl Path<'static> {
    #[inline]
    pub fn ensure_static(&mut self) {
        self.0.ensure_static()
    }

    #[inline]
    pub fn into_ensured_static(mut self) -> Self {
        self.ensure_static();
        self
    }

    pub fn try_from_static(string: &'static str) -> Result<Self, InvalidPath> {
        Self::internal_try_from(BoasStr::Static(string))
    }

    #[track_caller]
    pub const fn from_static(string: &'static str) -> Self {
        match validate(string.as_bytes()) {
            Ok(()) => Self(BoasStr::Static(string)),
            Err(_e) => panic!("Failed to validate static InvalidPath."),
        }
    }
}

impl<'a> TryFrom<&'a str> for Path<'a> {
    type Error = InvalidPath;

    fn try_from(string: &'a str) -> Result<Self, InvalidPath> {
        Self::internal_try_from(BoasStr::Borrowed(string))
    }
}

impl<'a> TryFrom<String> for Path<'a> {
    type Error = InvalidPath;

    fn try_from(string: String) -> Result<Self, InvalidPath> {
        Self::internal_try_from(BoasStr::Owned(string))
    }
}

#[cfg(feature = "boar")]
impl<'a> TryFrom<BoasStr<'a>> for Path<'a> {
    type Error = InvalidPath;

    fn try_from(string: BoasStr<'a>) -> Result<Self, InvalidPath> {
        Self::internal_try_from(string)
    }
}

impl Default for Path<'_> {
    fn default() -> Self {
        Self::new()
    }
}

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

impl Borrow<str> for Path<'_> {
    fn borrow(&self) -> &str {
        self.0.borrow()
    }
}

impl PartialEq<str> for Path<'_> {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}

impl PartialEq<&'_ str> for Path<'_> {
    fn eq(&self, &other: &&str) -> bool {
        self == other
    }
}

#[derive(Debug, Clone)]
pub struct InvalidPath(InvalidComponent);

impl fmt::Display for InvalidPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "invalid path: {}", self.0)
    }
}

impl Error for InvalidPath {}

const fn validate(bytes: &[u8]) -> Result<(), InvalidPath> {
    match inner_validate(bytes) {
        Ok(x) => Ok(x),
        Err(e) => Err(InvalidPath(e)),
    }
}

const fn inner_validate(bytes: &[u8]) -> Result<(), InvalidComponent> {
    let mut index = 0;
    while index < bytes.len() {
        let byte = bytes[index];
        if byte == b'%' {
            match validate_percent_encoding(index, bytes) {
                Err(e) => return Err(InvalidComponent::PercentEncoded(e)),
                Ok(next_index) => index = next_index,
            }
        } else {
            if !is_normal_path_char(byte) {
                return Err(InvalidComponent::Byte(InvalidByte { index, byte }));
            }
            index += 1;
        }
    }
    Ok(())
}

const fn is_normal_path_char(b: u8) -> bool {
    is_unreserved(b) || is_sub_delimiter(b) || matches!(b, b':' | b'@' | b'/')
}

#[cfg(test)]
mod tests {
    use super::*;
    use assert_matches::assert_matches;

    #[test]
    fn asterisk() {
        let string = "*";
        assert_matches!(Path::try_from(string), Ok(info) => assert_eq!(info, string));
    }
}