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
use std::borrow::Cow;
use std::fmt::{self, Debug, Display};
use std::str::FromStr;
use crate::Error;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct HeaderName(Cow<'static, str>);
impl HeaderName {
pub fn from_ascii(mut bytes: Vec<u8>) -> Result<Self, Error> {
crate::ensure!(bytes.is_ascii(), "Bytes should be valid ASCII");
bytes.make_ascii_lowercase();
let string = unsafe { String::from_utf8_unchecked(bytes.to_vec()) };
Ok(HeaderName(Cow::Owned(string)))
}
pub fn as_str(&self) -> &'_ str {
&self.0
}
pub unsafe fn from_ascii_unchecked(mut bytes: Vec<u8>) -> Self {
bytes.make_ascii_lowercase();
let string = String::from_utf8_unchecked(bytes);
HeaderName(Cow::Owned(string))
}
pub(crate) const fn from_lowercase_str(str: &'static str) -> Self {
HeaderName(Cow::Borrowed(str))
}
}
impl Display for HeaderName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl FromStr for HeaderName {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
crate::ensure!(s.is_ascii(), "String slice should be valid ASCII");
Ok(HeaderName(Cow::Owned(s.to_ascii_lowercase())))
}
}
impl<'a> std::convert::TryFrom<&'a str> for HeaderName {
type Error = Error;
fn try_from(value: &'a str) -> Result<Self, Self::Error> {
Self::from_str(value)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_header_name_static_non_static() {
let static_header = HeaderName::from_lowercase_str("hello");
let non_static_header = HeaderName::from_str("hello").unwrap();
assert_eq!(&static_header, &non_static_header);
assert_eq!(&static_header, &static_header);
assert_eq!(&non_static_header, &non_static_header);
assert_eq!(static_header, non_static_header);
assert_eq!(static_header, static_header);
assert_eq!(non_static_header, non_static_header);
}
}