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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
use crate::validation::{
    is_sub_delimiter, is_unreserved, validate_percent_encoding, InvalidByte, InvalidComponent,
};
use boar_::BoasStr;
use std::{
    convert::TryFrom,
    error::Error,
    fmt,
    hash::{Hash, Hasher},
};

#[derive(Debug, Clone)]
pub struct HostName<'a>(BoasStr<'a>);

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

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

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

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

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

impl HostName<'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, InvalidHostName> {
        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!("invalid static HostName"),
        }
    }
}

impl<'a> TryFrom<&'a str> for HostName<'a> {
    type Error = InvalidHostName;

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

impl<'a> TryFrom<String> for HostName<'a> {
    type Error = InvalidHostName;

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

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

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

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

impl<'a> Eq for HostName<'a> {}

impl<'a> Hash for HostName<'a> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        for byte in self.0.bytes() {
            state.write_u8(byte.to_ascii_lowercase())
        }
    }
}

impl<'a> PartialEq for HostName<'a> {
    fn eq(&self, other: &Self) -> bool {
        self.0.eq_ignore_ascii_case(&other.0)
    }
}

impl<'a> PartialEq<str> for HostName<'a> {
    fn eq(&self, other: &str) -> bool {
        self.0.eq_ignore_ascii_case(other)
    }
}

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

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

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

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

impl Error for InvalidHostName {}

const fn validate(bytes: &[u8]) -> Result<(), InvalidHostName> {
    match inner_validate(bytes) {
        Ok(x) => Ok(x),
        Err(e) => Err(InvalidHostName(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_host_name_char(byte) {
                return Err(InvalidComponent::Byte(InvalidByte { index, byte }));
            }
            index += 1;
        }
    }
    Ok(())
}

const fn is_normal_host_name_char(b: u8) -> bool {
    is_unreserved(b) || is_sub_delimiter(b)
}

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

    #[test]
    fn default_is_valid() {
        assert_matches!(validate(HostName::default().as_str().as_bytes()), Ok(_));
    }
}