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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
use std::borrow::Cow;
use std::fmt;
use bytes::Bytes;

/// A raw header value.
#[derive(Clone, Debug)]
pub struct Raw(Lines);

impl Raw {
    /// Returns the amount of lines.
    #[inline]
    pub fn len(&self) -> usize {
        match self.0 {
            Lines::Empty => 0,
            Lines::One(..) => 1,
            Lines::Many(ref lines) => lines.len()
        }
    }

    /// Returns the line if there is only 1.
    #[inline]
    pub fn one(&self) -> Option<&[u8]> {
        match self.0 {
            Lines::One(ref line) => Some(line.as_ref()),
            Lines::Many(ref lines) if lines.len() == 1 => Some(lines[0].as_ref()),
            _ => None
        }
    }

    /// Iterate the lines of raw bytes.
    #[inline]
    pub fn iter(&self) -> RawLines {
        RawLines {
            inner: &self.0,
            pos: 0,
        }
    }

    /// Append a line to this `Raw` header value.
    pub fn push<V: Into<Raw>>(&mut self, val: V) {
        let raw = val.into();
        match raw.0 {
            Lines::Empty => (),
            Lines::One(one) => self.push_line(one),
            Lines::Many(lines) => {
                for line in lines {
                    self.push_line(line);
                }
            }
        }
    }

    fn push_line(&mut self, line: Bytes) {
        let lines = ::std::mem::replace(&mut self.0, Lines::Empty);
        match lines {
            Lines::Empty => {
                self.0 = Lines::One(line);
            }
            Lines::One(one) => {
                self.0 = Lines::Many(vec![one, line]);
            }
            Lines::Many(mut lines) => {
                lines.push(line);
                self.0 = Lines::Many(lines);
            }
        }
    }
}

#[derive(Clone)]
enum Lines {
    Empty,
    One(Bytes),
    Many(Vec<Bytes>),
}

fn eq_many<A: AsRef<[u8]>, B: AsRef<[u8]>>(a: &[A], b: &[B]) -> bool {
    if a.len() != b.len() {
        false
    } else {
        for (a, b) in a.iter().zip(b.iter()) {
            if a.as_ref() != b.as_ref() {
                return false
            }
        }
        true
    }
}

fn eq<B: AsRef<[u8]>>(raw: &Raw, b: &[B]) -> bool {
    match raw.0 {
        Lines::Empty => b.is_empty(),
        Lines::One(ref line) => eq_many(&[line], b),
        Lines::Many(ref lines) => eq_many(lines, b)
    }
}

impl PartialEq for Raw {
    fn eq(&self, other: &Raw) -> bool {
        match other.0 {
            Lines::Empty => eq(self, &[] as &[Bytes]),
            Lines::One(ref line) => eq(self, &[line]),
            Lines::Many(ref lines) => eq(self, lines),
        }
    }
}

impl Eq for Raw {}

impl PartialEq<[Vec<u8>]> for Raw {
    fn eq(&self, bytes: &[Vec<u8>]) -> bool {
        eq(self, bytes)
    }
}

impl<'a> PartialEq<[&'a [u8]]> for Raw {
    fn eq(&self, bytes: &[&[u8]]) -> bool {
        eq(self, bytes)
    }
}

impl PartialEq<[String]> for Raw {
    fn eq(&self, bytes: &[String]) -> bool {
        eq(self, bytes)
    }
}

impl<'a> PartialEq<[&'a str]> for Raw {
    fn eq(&self, bytes: &[&'a str]) -> bool {
        eq(self, bytes)
    }
}

impl PartialEq<[u8]> for Raw {
    fn eq(&self, bytes: &[u8]) -> bool {
        match self.0 {
            Lines::Empty => bytes.is_empty(),
            Lines::One(ref line) => line.as_ref() == bytes,
            Lines::Many(..) => false
        }
    }
}

impl PartialEq<str> for Raw {
    fn eq(&self, s: &str) -> bool {
        self == s.as_bytes()
    }
}

impl From<Vec<Vec<u8>>> for Raw {
    #[inline]
    fn from(val: Vec<Vec<u8>>) -> Raw {
        Raw(Lines::Many(
            val.into_iter()
                .map(|vec| maybe_literal(vec.into()))
                .collect()
        ))
    }
}

impl From<String> for Raw {
    #[inline]
    fn from(val: String) -> Raw {
        Raw::from(val.into_bytes())
    }
}

impl From<Vec<u8>> for Raw {
    #[inline]
    fn from(val: Vec<u8>) -> Raw {
        Raw(Lines::One(maybe_literal(val.into())))
    }
}

impl<'a> From<&'a str> for Raw {
    fn from(val: &'a str) -> Raw {
        Raw::from(val.as_bytes())
    }
}

impl<'a> From<&'a [u8]> for Raw {
    fn from(val: &'a [u8]) -> Raw {
        Raw(Lines::One(maybe_literal(val.into())))
    }
}

impl From<Bytes> for Raw {
    #[inline]
    fn from(val: Bytes) -> Raw {
        Raw(Lines::One(val))
    }
}

pub fn parsed(val: Bytes) -> Raw {
    Raw(Lines::One(From::from(val)))
}

pub fn push(raw: &mut Raw, val: Bytes) {
    raw.push_line(val);
}

pub fn new() -> Raw {
    Raw(Lines::Empty)
}

impl fmt::Debug for Lines {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Lines::Empty => f.pad("[]"),
            Lines::One(ref line) => fmt::Debug::fmt(&[line], f),
            Lines::Many(ref lines) => fmt::Debug::fmt(lines, f)
        }
    }
}

impl ::std::ops::Index<usize> for Raw {
    type Output = [u8];

    fn index(&self, idx: usize) -> &[u8] {
        match self.0 {
            Lines::Empty => panic!("index of out of bounds: {}", idx),
            Lines::One(ref line) => if idx == 0 {
                line.as_ref()
            } else {
                panic!("index out of bounds: {}", idx)
            },
            Lines::Many(ref lines) => lines[idx].as_ref()
        }
    }
}

macro_rules! literals {
    ($($len:expr => $($value:expr),+;)+) => (
        fn maybe_literal(s: Cow<[u8]>) -> Bytes {
            match s.len() {
                $($len => {
                    $(
                    if s.as_ref() == $value {
                        return Bytes::from_static($value);
                    }
                    )+
                })+

                _ => ()
            }

            Bytes::from(s.into_owned())
        }

        #[test]
        fn test_literal_lens() {
            $(
            $({
                let s = $value;
                assert!(s.len() == $len, "{:?} has len of {}, listed as {}", s, s.len(), $len);
            })+
            )+
        }
    );
}

literals! {
    1  => b"*", b"0";
    3  => b"*/*";
    4  => b"gzip";
    5  => b"close";
    7  => b"chunked";
    10 => b"keep-alive";
}

impl<'a> IntoIterator for &'a Raw {
    type IntoIter = RawLines<'a>;
    type Item = &'a [u8];

    fn into_iter(self) -> RawLines<'a> {
        self.iter()
    }
}

pub struct RawLines<'a> {
    inner: &'a Lines,
    pos: usize,
}

impl<'a> fmt::Debug for RawLines<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("RawLines")
            .field(&self.inner)
            .finish()
    }
}

impl<'a> Iterator for RawLines<'a> {
    type Item = &'a [u8];

    #[inline]
    fn next(&mut self) -> Option<&'a [u8]> {
        let current_pos = self.pos;
        self.pos += 1;
        match *self.inner {
            Lines::Empty => None,
            Lines::One(ref line) => {
                if current_pos == 0 {
                    Some(line.as_ref())
                } else {
                    None
                }
            }
            Lines::Many(ref lines) => lines.get(current_pos).map(|l| l.as_ref()),
        }
    }
}