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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
use crate::{
    header::{HeaderKey, HeaderValue},
    Header,
};

/// A collection of Headers
#[derive(Debug, PartialEq, Clone)]
pub struct Headers<'a> {
    headers: Vec<Header<'a>>,
    max_value_length: usize,
}

impl<'a> Headers<'a> {
    /// Creates a new Headers-Instance, for performance reasons
    /// it is recommended to use the `with_capacity` method
    /// as that would avoid frequent reallocations
    pub fn new() -> Self {
        Self {
            headers: Vec::new(),
            max_value_length: 0,
        }
    }

    /// Creates the Headers-Object with the given Capacity
    /// prereserved for future Headers.
    /// This should be used when you already kind of know
    /// how many Headers this will hold, as it will avoid
    /// extra allocations in the future
    pub fn with_capacity(cap: usize) -> Self {
        Self {
            headers: Vec::with_capacity(cap),
            max_value_length: 0,
        }
    }

    /// Sets the Value of the of the Header for the given Key to
    /// the given Value
    ///
    /// ## Behaviour
    /// Checks if the Key is already present in the Collection and
    /// removes it if that is the case.
    /// Then adds the new Header to the End of the Collection
    pub fn set<'b, K, V>(&mut self, key: K, value: V)
    where
        'b: 'a,
        K: Into<HeaderKey<'a>>,
        V: Into<HeaderValue<'a>>,
    {
        let final_key = key.into();
        if let Some(index) = self.find(&final_key) {
            self.headers.remove(index);
        }

        let n_value: HeaderValue = value.into();
        let n_value_length = n_value.length();
        if n_value_length > self.max_value_length {
            self.max_value_length = n_value_length;
        }

        self.headers.push(Header {
            key: final_key,
            value: n_value,
        });
    }

    /// Appends the given Key-Value Pair to the end of the
    /// Collection, without checking if the Key is already
    /// present in the Collection
    pub fn append<K, V>(&mut self, key: K, value: V)
    where
        K: Into<HeaderKey<'a>>,
        V: Into<HeaderValue<'a>>,
    {
        let n_value: HeaderValue = value.into();
        let n_value_length = n_value.length();
        if n_value_length > self.max_value_length {
            self.max_value_length = n_value_length;
        }

        self.headers.push(Header {
            key: key.into(),
            value: n_value,
        })
    }

    fn find(&self, key: &HeaderKey<'a>) -> Option<usize> {
        for (index, pair) in self.headers.iter().enumerate() {
            if &pair.key == key {
                return Some(index);
            }
        }
        None
    }

    /// Removes the first Header, that matches the given
    /// Key, from the Collection
    pub fn remove<K>(&mut self, key: K)
    where
        K: Into<HeaderKey<'a>>,
    {
        if let Some(index) = self.find(&key.into()) {
            self.headers.remove(index);
        }
    }

    /// Searches the Collection for a Header that matches
    /// the given Key
    ///
    /// Returns:
    /// * None: if no Header matches the Key
    /// * A Reference to the underlying Header-Value that
    /// belongs to the Key
    pub fn get<K>(&self, key: K) -> Option<&HeaderValue<'a>>
    where
        K: Into<HeaderKey<'a>>,
    {
        self.find(&key.into())
            .map(|index| &self.headers.get(index).unwrap().value)
    }

    /// Serializes the Collection of Headers into the
    /// given Buffer by append to it
    pub fn serialize(&self, buf: &mut Vec<u8>) {
        for pair in self.headers.iter() {
            pair.serialize(buf);
        }
    }

    /// Returns the Size in bytes of the biggest Value as text.
    ///
    /// This means that all the Header-Values in this collection
    /// can fit in a buffer of this size.
    pub fn get_max_value_size(&self) -> usize {
        self.max_value_length
    }

    /// Returns the Number of Headers in this collection
    pub fn get_header_count(&self) -> usize {
        self.headers.len()
    }
}

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

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

    #[test]
    fn headers_add_new() {
        let mut headers = Headers::new();
        headers.set("test-key", "test-value");

        assert_eq!(
            vec![Header {
                key: HeaderKey::StrRef("test-key"),
                value: HeaderValue::StrRef("test-value")
            }],
            headers.headers
        );
    }
    #[test]
    fn headers_add_already_exists() {
        let mut headers = Headers::new();
        headers.set("test-key", "test-value");

        assert_eq!(
            vec![Header {
                key: HeaderKey::StrRef("test-key"),
                value: HeaderValue::StrRef("test-value")
            }],
            headers.headers
        );

        headers.set("test-key", "other value");
        assert_eq!(
            vec![Header {
                key: HeaderKey::StrRef("test-key"),
                value: HeaderValue::StrRef("other value")
            }],
            headers.headers
        );
    }

    #[test]
    fn headers_remove_existing() {
        let mut headers = Headers::new();
        headers.set("test-key", "test-value");

        assert_eq!(
            vec![Header {
                key: HeaderKey::StrRef("test-key"),
                value: HeaderValue::StrRef("test-value")
            }],
            headers.headers
        );

        headers.remove("test-key");
        assert_eq!(Vec::<Header>::new(), headers.headers);
    }
    #[test]
    fn headers_remove_non_existing() {
        let mut headers = Headers::new();
        headers.set("test-key", "test-value");

        assert_eq!(
            vec![Header {
                key: HeaderKey::StrRef("test-key"),
                value: HeaderValue::StrRef("test-value")
            }],
            headers.headers
        );

        headers.remove("other-key");
        assert_eq!(
            vec![Header {
                key: HeaderKey::StrRef("test-key"),
                value: HeaderValue::StrRef("test-value")
            }],
            headers.headers
        );
    }

    #[test]
    fn headers_get_existing() {
        let mut headers = Headers::new();
        headers.set("test-key", "test-value");

        assert_eq!(
            vec![Header {
                key: HeaderKey::StrRef("test-key"),
                value: HeaderValue::StrRef("test-value")
            }],
            headers.headers
        );

        assert_eq!(
            Some(&HeaderValue::StrRef("test-value")),
            headers.get("test-key")
        );
    }
    #[test]
    fn headers_get_not_existing() {
        let mut headers = Headers::new();
        headers.set("test-key", "test-value");

        assert_eq!(
            vec![Header {
                key: HeaderKey::StrRef("test-key"),
                value: HeaderValue::StrRef("test-value")
            }],
            headers.headers
        );

        assert_eq!(None, headers.get("other-key"));
    }

    #[test]
    fn headers_serialize() {
        let mut headers = Headers::new();
        headers.set("test-key", "test-value");

        assert_eq!(
            vec![Header {
                key: HeaderKey::StrRef("test-key"),
                value: HeaderValue::StrRef("test-value")
            }],
            headers.headers
        );

        let result = "test-key: test-value\r\n".as_bytes();
        let mut tmp: Vec<u8> = Vec::new();
        headers.serialize(&mut tmp);
        assert_eq!(result, &tmp);
    }
}