summaryrefslogtreecommitdiff
path: root/src/header.rs
blob: 74786e679f44505a05b1222d639460f0bf5b3893 (plain)
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
use std::{string::ToString, cmp::{PartialEq, Eq}, hash::{Hash, Hasher}};
use multimap::{MultiMap, IterAll};
use crate::{error::HTTPError, parse::{TryParse, Parse}};

#[derive(Debug, Clone, Eq)]
pub struct HeaderName {
    inner: String
}

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

impl TryParse for HeaderName {
    fn try_parse(s: impl Into<String>) -> Result<Self, HTTPError> {
        let name = s.into();
        if name.len() < 1 {
            return Err(HTTPError::InvalidHeaderName(name))
        } else {
            Ok(Self { inner: name })
        }
    }
    
}

impl ToString for HeaderName {
    fn to_string(&self) -> String {
        self.inner.clone()
    }
}

impl PartialEq for HeaderName {
    fn eq(&self, other: &Self) -> bool {
        self.inner.eq_ignore_ascii_case(&other.inner)
    }
}

impl Hash for HeaderName {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let mut hash: i32 = 0;
        for char in self.inner.chars() {
            let byte = char.to_ascii_lowercase() as u8;
            hash = hash ^ ((byte as i32) << 0);
            hash = hash ^ ((byte as i32) << 8); 
            hash = hash ^ ((byte as i32) << 16);
            hash = hash ^ ((byte as i32) << 24);
            hash = hash % 16777213;
        }
        state.write_i32(hash);
    }
}

#[derive(Debug, Clone)]
pub struct HeaderValue {
    inner: String
}

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

impl Parse for HeaderValue {
    fn parse(value: impl Into<String>) -> Self {
        Self { inner: value.into() }
    }

}

impl ToString for HeaderValue {
    fn to_string(&self) -> String {
        self.inner.clone()
    }
}

pub struct Header {
    pub name: HeaderName,
    pub value: HeaderValue
}

impl Header {
    pub fn new(name: impl Into<HeaderName>, value: impl Into<HeaderValue>) -> Self {
        Self { name: name.into(), value: value.into() }
    }
}

impl TryParse for Header {
    fn try_parse(s: impl Into<String>) -> Result<Self, HTTPError> {
        let s = s.into();
        let Some(mid) = s.find(": ") else {
            return Err(HTTPError::InvalidHeader(s.to_string()))
        };
        if mid == 0 || mid >= s.len() - 2 {
            return Err(HTTPError::InvalidHeader(s.to_string()))
        }
        let name = HeaderName::try_parse(&s[0..mid])?;
        let value = HeaderValue::parse(&s[(mid+2)..]);
        Ok(Header::new(name, value))
    }
}

impl ToString for Header {
    fn to_string(&self) -> String {
        let mut s = String::new();
        s.push_str(self.name.as_str());
        s.push_str(": ");
        s.push_str(self.value.as_str());
        s
    }
}

impl<H,V> From<(H, V)> for Header 
where
    H: Into<HeaderName>,
    V: Into<HeaderValue>
{
    fn from(value: (H, V)) -> Self {
        Self { name: value.0.into(), value: value.1.into() }
    }
}

pub struct HeaderMap {
    inner: MultiMap<HeaderName, Header>
}

impl HeaderMap {
    pub fn new() -> Self {
        Self::with_headers(Vec::new())
    }

    pub fn with_headers(headers: Vec<Header>) -> Self {
        let mut inner = MultiMap::with_capacity(headers.len());
        for header in headers {
            inner.insert(header.name.clone(), Header::new(header.name, header.value)); 
        } 

        Self { inner }
    }

    pub fn insert(&mut self, header: impl Into<Header>) {
        let header = header.into();
        self.inner.insert(header.name.clone(), Header::new(header.name, header.value))
    }

    pub fn remove(&mut self, name: &HeaderName) -> Option<Vec<Header>> {
        self.inner.remove(name)
    }

    pub fn get(&mut self, name: &HeaderName) -> Option<&Vec<Header>> {
        self.inner.get_vec(name)
    }

    pub fn iter(&self) -> HeaderMapIter {
        HeaderMapIter { inner: self.inner.iter_all() }
    }
}

pub struct HeaderMapIter<'i> {
    inner: IterAll<'i, HeaderName, Vec<Header>>
}

impl<'i> Iterator for HeaderMapIter<'i> {
    type Item = &'i Vec<Header>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.inner.next() {
            Some(h) => Some(h.1),
            None => None,
        }
    }
}