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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
//! Pieces pertaining to the HTTP message protocol.
use std::borrow::Cow::{self, Borrowed, Owned};
use std::borrow::IntoCow;
use std::cmp::min;
use std::io::{self, Read, Write, Cursor};
use std::num::from_u16;
use std::str;

use url::Url;
use url::ParseError as UrlError;

use method;
use status::StatusCode;
use uri;
use uri::RequestUri::{AbsolutePath, AbsoluteUri, Authority, Star};
use version::HttpVersion;
use version::HttpVersion::{Http09, Http10, Http11};
use HttpError::{HttpHeaderError, HttpMethodError, HttpStatusError,
                HttpUriError, HttpVersionError};
use HttpResult;

use self::HttpReader::{SizedReader, ChunkedReader, EofReader, EmptyReader};
use self::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter};

/// Readers to handle different Transfer-Encodings.
///
/// If a message body does not include a Transfer-Encoding, it *should*
/// include a Content-Length header.
pub enum HttpReader<R> {
    /// A Reader used when a Content-Length header is passed with a positive integer.
    SizedReader(R, u64),
    /// A Reader used when Transfer-Encoding is `chunked`.
    ChunkedReader(R, Option<u64>),
    /// A Reader used for responses that don't indicate a length or chunked.
    ///
    /// Note: This should only used for `Response`s. It is illegal for a
    /// `Request` to be made with both `Content-Length` and
    /// `Transfer-Encoding: chunked` missing, as explained from the spec:
    ///
    /// > If a Transfer-Encoding header field is present in a response and
    /// > the chunked transfer coding is not the final encoding, the
    /// > message body length is determined by reading the connection until
    /// > it is closed by the server.  If a Transfer-Encoding header field
    /// > is present in a request and the chunked transfer coding is not
    /// > the final encoding, the message body length cannot be determined
    /// > reliably; the server MUST respond with the 400 (Bad Request)
    /// > status code and then close the connection.
    EofReader(R),
    /// A Reader used for messages that should never have a body.
    ///
    /// See https://tools.ietf.org/html/rfc7230#section-3.3.3
    EmptyReader(R),
}

impl<R: Read> HttpReader<R> {

    /// Unwraps this HttpReader and returns the underlying Reader.
    pub fn into_inner(self) -> R {
        match self {
            SizedReader(r, _) => r,
            ChunkedReader(r, _) => r,
            EofReader(r) => r,
            EmptyReader(r) => r,
        }
    }
}

impl<R: Read> Read for HttpReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match *self {
            SizedReader(ref mut body, ref mut remaining) => {
                debug!("Sized read, remaining={:?}", remaining);
                if *remaining == 0 {
                    Ok(0)
                } else {
                    let num = try!(body.read(buf)) as u64;
                    if num > *remaining {
                        *remaining = 0;
                    } else {
                        *remaining -= num;
                    }
                    Ok(num as usize)
                }
            },
            ChunkedReader(ref mut body, ref mut opt_remaining) => {
                let mut rem = match *opt_remaining {
                    Some(ref rem) => *rem,
                    // None means we don't know the size of the next chunk
                    None => try!(read_chunk_size(body))
                };
                debug!("Chunked read, remaining={:?}", rem);

                if rem == 0 {
                    *opt_remaining = Some(0);

                    // chunk of size 0 signals the end of the chunked stream
                    // if the 0 digit was missing from the stream, it would
                    // be an InvalidInput error instead.
                    debug!("end of chunked");
                    return Ok(0)
                }

                let to_read = min(rem as usize, buf.len());
                let count = try!(body.read(&mut buf[..to_read])) as u64;

                rem -= count;
                *opt_remaining = if rem > 0 {
                    Some(rem)
                } else {
                    try!(eat(body, LINE_ENDING.as_bytes()));
                    None
                };
                Ok(count as usize)
            },
            EofReader(ref mut body) => {
                body.read(buf)
            },
            EmptyReader(_) => Ok(0)
        }
    }
}

fn eat<R: Read>(rdr: &mut R, bytes: &[u8]) -> io::Result<()> {
    let mut buf = [0];
    for &b in bytes.iter() {
        match try!(rdr.read(&mut buf)) {
            1 if buf[0] == b => (),
            _ => return Err(io::Error::new(io::ErrorKind::InvalidInput,
                                          "Invalid characters found",
                                           None))
        }
    }
    Ok(())
}

/// Chunked chunks start with 1*HEXDIGIT, indicating the size of the chunk.
fn read_chunk_size<R: Read>(rdr: &mut R) -> io::Result<u64> {
    macro_rules! byte (
        ($rdr:ident) => ({
            let mut buf = [0];
            match try!($rdr.read(&mut buf)) {
                1 => buf[0],
                _ => return Err(io::Error::new(io::ErrorKind::InvalidInput,
                                                  "Invalid chunk size line",
                                                   None)),

            }
        })
    );
    let mut size = 0u64;
    let radix = 16;
    let mut in_ext = false;
    let mut in_chunk_size = true;
    loop {
        match byte!(rdr) {
            b@b'0'...b'9' if in_chunk_size => {
                size *= radix;
                size += (b - b'0') as u64;
            },
            b@b'a'...b'f' if in_chunk_size => {
                size *= radix;
                size += (b + 10 - b'a') as u64;
            },
            b@b'A'...b'F' if in_chunk_size => {
                size *= radix;
                size += (b + 10 - b'A') as u64;
            },
            CR => {
                match byte!(rdr) {
                    LF => break,
                    _ => return Err(io::Error::new(io::ErrorKind::InvalidInput,
                                                  "Invalid chunk size line",
                                                   None))

                }
            },
            // If we weren't in the extension yet, the ";" signals its start
            b';' if !in_ext => {
                in_ext = true;
                in_chunk_size = false;
            },
            // "Linear white space" is ignored between the chunk size and the
            // extension separator token (";") due to the "implied *LWS rule".
            b'\t' | b' ' if !in_ext & !in_chunk_size => {},
            // LWS can follow the chunk size, but no more digits can come
            b'\t' | b' ' if in_chunk_size => in_chunk_size = false,
            // We allow any arbitrary octet once we are in the extension, since
            // they all get ignored anyway. According to the HTTP spec, valid
            // extensions would have a more strict syntax:
            //     (token ["=" (token | quoted-string)])
            // but we gain nothing by rejecting an otherwise valid chunk size.
            ext if in_ext => {
                todo!("chunk extension byte={}", ext);
            },
            // Finally, if we aren't in the extension and we're reading any
            // other octet, the chunk size line is invalid!
            _ => {
                return Err(io::Error::new(io::ErrorKind::InvalidInput,
                                         "Invalid chunk size line",
                                         None))
            }
        }
    }
    debug!("chunk size={:?}", size);
    Ok(size)
}

/// Writers to handle different Transfer-Encodings.
pub enum HttpWriter<W: Write> {
    /// A no-op Writer, used initially before Transfer-Encoding is determined.
    ThroughWriter(W),
    /// A Writer for when Transfer-Encoding includes `chunked`.
    ChunkedWriter(W),
    /// A Writer for when Content-Length is set.
    ///
    /// Enforces that the body is not longer than the Content-Length header.
    SizedWriter(W, u64),
    /// A writer that should not write any body.
    EmptyWriter(W),
}

impl<W: Write> HttpWriter<W> {
    /// Unwraps the HttpWriter and returns the underlying Writer.
    #[inline]
    pub fn into_inner(self) -> W {
        match self {
            ThroughWriter(w) => w,
            ChunkedWriter(w) => w,
            SizedWriter(w, _) => w,
            EmptyWriter(w) => w,
        }
    }

    /// Access the inner Writer.
    #[inline]
    pub fn get_ref<'a>(&'a self) -> &'a W {
        match *self {
            ThroughWriter(ref w) => w,
            ChunkedWriter(ref w) => w,
            SizedWriter(ref w, _) => w,
            EmptyWriter(ref w) => w,
        }
    }

    /// Access the inner Writer mutably.
    ///
    /// Warning: You should not write to this directly, as you can corrupt
    /// the state.
    #[inline]
    pub fn get_mut<'a>(&'a mut self) -> &'a mut W {
        match *self {
            ThroughWriter(ref mut w) => w,
            ChunkedWriter(ref mut w) => w,
            SizedWriter(ref mut w, _) => w,
            EmptyWriter(ref mut w) => w,
        }
    }

    /// Ends the HttpWriter, and returns the underlying Writer.
    ///
    /// A final `write_all()` is called with an empty message, and then flushed.
    /// The ChunkedWriter variant will use this to write the 0-sized last-chunk.
    #[inline]
    pub fn end(mut self) -> io::Result<W> {
        try!(self.write(&[]));
        try!(self.flush());
        Ok(self.into_inner())
    }
}

impl<W: Write> Write for HttpWriter<W> {
    #[inline]
    fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
        match *self {
            ThroughWriter(ref mut w) => w.write(msg),
            ChunkedWriter(ref mut w) => {
                let chunk_size = msg.len();
                debug!("chunked write, size = {:?}", chunk_size);
                try!(write!(w, "{:X}{}", chunk_size, LINE_ENDING));
                try!(w.write_all(msg));
                try!(w.write_all(LINE_ENDING.as_bytes()));
                Ok(msg.len())
            },
            SizedWriter(ref mut w, ref mut remaining) => {
                let len = msg.len() as u64;
                if len > *remaining {
                    let len = *remaining;
                    *remaining = 0;
                    try!(w.write_all(&msg[..len as usize]));
                    Ok(len as usize)
                } else {
                    *remaining -= len;
                    try!(w.write_all(msg));
                    Ok(len as usize)
                }
            },
            EmptyWriter(..) => {
                if msg.len() != 0 {
                    error!("Cannot include a body with this kind of message");
                }
                Ok(0)
            }
        }
    }

    #[inline]
    fn flush(&mut self) -> io::Result<()> {
        match *self {
            ThroughWriter(ref mut w) => w.flush(),
            ChunkedWriter(ref mut w) => w.flush(),
            SizedWriter(ref mut w, _) => w.flush(),
            EmptyWriter(ref mut w) => w.flush(),
        }
    }
}

pub const SP: u8 = b' ';
pub const CR: u8 = b'\r';
pub const LF: u8 = b'\n';
pub const STAR: u8 = b'*';
pub const LINE_ENDING: &'static str = "\r\n";

/// Determines if byte is a token char.
///
/// > ```notrust
/// > token          = 1*tchar
/// >
/// > tchar          = "!" / "#" / "$" / "%" / "&" / "'" / "*"
/// >                / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
/// >                / DIGIT / ALPHA
/// >                ; any VCHAR, except delimiters
/// > ```
#[inline]
pub fn is_token(b: u8) -> bool {
    match b {
        b'a'...b'z' |
        b'A'...b'Z' |
        b'0'...b'9' |
        b'!' |
        b'#' |
        b'$' |
        b'%' |
        b'&' |
        b'\''|
        b'*' |
        b'+' |
        b'-' |
        b'.' |
        b'^' |
        b'_' |
        b'`' |
        b'|' |
        b'~' => true,
        _ => false
    }
}

/// Read token bytes from `stream` into `buf` until a space is encountered.
/// Returns `Ok(true)` if we read until a space,
/// `Ok(false)` if we got to the end of `buf` without encountering a space,
/// otherwise returns any error encountered reading the stream.
///
/// The remaining contents of `buf` are left untouched.
fn read_method_token_until_space<R: Read>(stream: &mut R, buf: &mut [u8]) -> HttpResult<bool> {
    macro_rules! byte (
        ($rdr:ident) => ({
            let mut slot = [0];
            match try!($rdr.read(&mut slot)) {
                1 => slot[0],
                _ => return Err(HttpMethodError),
            }
        })
    );

    let mut cursor = Cursor::new(buf);

    loop {
        let b = byte!(stream);

        if b == SP {
            break;
        } else if !is_token(b) {
            return Err(HttpMethodError);
        // Read to end but there's still more
        } else {
            match cursor.write(&[b]) {
                Ok(1) => (),
                _ => return Ok(false)
            }
        }
    }

    if cursor.position() == 0 {
        return Err(HttpMethodError);
    }

    Ok(true)
}

/// Read a `Method` from a raw stream, such as `GET`.
/// ### Note:
/// Extension methods are only parsed to 16 characters.
pub fn read_method<R: Read>(stream: &mut R) -> HttpResult<method::Method> {
    let mut buf = [SP; 16];

    if !try!(read_method_token_until_space(stream, &mut buf)) {
        return Err(HttpMethodError);
    }

    let maybe_method = match &buf[0..7] {
        b"GET    " => Some(method::Method::Get),
        b"PUT    " => Some(method::Method::Put),
        b"POST   " => Some(method::Method::Post),
        b"HEAD   " => Some(method::Method::Head),
        b"PATCH  " => Some(method::Method::Patch),
        b"TRACE  " => Some(method::Method::Trace),
        b"DELETE " => Some(method::Method::Delete),
        b"CONNECT" => Some(method::Method::Connect),
        b"OPTIONS" => Some(method::Method::Options),
        _ => None,
    };

    debug!("maybe_method = {:?}", maybe_method);

    match (maybe_method, &buf[..]) {
        (Some(method), _) => Ok(method),
        (None, ext) => {
            // We already checked that the buffer is ASCII
            Ok(method::Method::Extension(unsafe { str::from_utf8_unchecked(ext) }.trim().to_string()))
        },
    }
}

/// Read a `RequestUri` from a raw stream.
pub fn read_uri<R: Read>(stream: &mut R) -> HttpResult<uri::RequestUri> {
    macro_rules! byte (
        ($rdr:ident) => ({
            let mut buf = [0];
            match try!($rdr.read(&mut buf)) {
                1 => buf[0],
                _ => return Err(HttpUriError(UrlError::InvalidCharacter)),
            }
        })
    );
    let mut b = byte!(stream);
    while b == SP {
        b = byte!(stream);
    }

    let mut s = String::new();
    if b == STAR {
        try!(expect(byte!(stream), SP));
        return Ok(Star)
    } else {
        s.push(b as char);
        loop {
            match byte!(stream) {
                SP => {
                    break;
                },
                CR | LF => {
                    return Err(HttpUriError(UrlError::InvalidCharacter))
                },
                b => s.push(b as char)
            }
        }
    }

    debug!("uri buf = {:?}", s);

    if s.as_slice().starts_with("/") {
        Ok(AbsolutePath(s))
    } else if s.as_slice().contains("/") {
        Ok(AbsoluteUri(try!(Url::parse(s.as_slice()))))
    } else {
        let mut temp = "http://".to_string();
        temp.push_str(s.as_slice());
        try!(Url::parse(temp.as_slice()));
        todo!("compare vs u.authority()");
        Ok(Authority(s))
    }


}


/// Read the `HttpVersion` from a raw stream, such as `HTTP/1.1`.
pub fn read_http_version<R: Read>(stream: &mut R) -> HttpResult<HttpVersion> {
    macro_rules! byte (
        ($rdr:ident) => ({
            let mut buf = [0];
            match try!($rdr.read(&mut buf)) {
                1 => buf[0],
                _ => return Err(HttpVersionError),
            }
        })
    );

    try!(expect(byte!(stream), b'H'));
    try!(expect(byte!(stream), b'T'));
    try!(expect(byte!(stream), b'T'));
    try!(expect(byte!(stream), b'P'));
    try!(expect(byte!(stream), b'/'));

    match byte!(stream) {
        b'0' => {
            try!(expect(byte!(stream), b'.'));
            try!(expect(byte!(stream), b'9'));
            Ok(Http09)
        },
        b'1' => {
            try!(expect(byte!(stream), b'.'));
            match byte!(stream) {
                b'0' => Ok(Http10),
                b'1' => Ok(Http11),
                _ => Err(HttpVersionError)
            }
        },
        _ => Err(HttpVersionError)
    }
}

const MAX_HEADER_NAME_LENGTH: usize = 100;
const MAX_HEADER_FIELD_LENGTH: usize = 4096;

/// The raw bytes when parsing a header line.
///
/// A String and Vec<u8>, divided by COLON (`:`). The String is guaranteed
/// to be all `token`s. See `is_token` source for all valid characters.
pub type RawHeaderLine = (String, Vec<u8>);

/// Read a RawHeaderLine from a Reader.
///
/// From [spec](https://tools.ietf.org/html/http#section-3.2):
///
/// > Each header field consists of a case-insensitive field name followed
/// > by a colon (":"), optional leading whitespace, the field value, and
/// > optional trailing whitespace.
/// >
/// > ```notrust
/// > header-field   = field-name ":" OWS field-value OWS
/// >
/// > field-name     = token
/// > field-value    = *( field-content / obs-fold )
/// > field-content  = field-vchar [ 1*( SP / HTAB ) field-vchar ]
/// > field-vchar    = VCHAR / obs-text
/// >
/// > obs-fold       = CRLF 1*( SP / HTAB )
/// >                ; obsolete line folding
/// >                ; see Section 3.2.4
/// > ```
pub fn read_header<R: Read>(stream: &mut R) -> HttpResult<Option<RawHeaderLine>> {
    macro_rules! byte (
        ($rdr:ident) => ({
            let mut buf = [0];
            match try!($rdr.read(&mut buf)) {
                1 => buf[0],
                _ => return Err(HttpHeaderError),
            }
        })
    );

    let mut name = String::new();
    let mut value = vec![];

    loop {
        match byte!(stream) {
            CR if name.len() == 0 => {
                match byte!(stream) {
                    LF => return Ok(None),
                    _ => return Err(HttpHeaderError)
                }
            },
            b':' => break,
            b if is_token(b) => {
                if name.len() > MAX_HEADER_NAME_LENGTH { return Err(HttpHeaderError); }
                name.push(b as char)
            },
            _nontoken => return Err(HttpHeaderError)
        };
    }

    debug!("header name = {:?}", name);

    let mut ows = true; //optional whitespace

    todo!("handle obs-folding (gross!)");
    loop {
        match byte!(stream) {
            CR => break,
            LF => return Err(HttpHeaderError),
            b' ' if ows => {},
            b => {
                ows = false;
                if value.len() > MAX_HEADER_FIELD_LENGTH { return Err(HttpHeaderError); }
                value.push(b)
            }
        };
    }
    // Remove optional trailing whitespace
    let real_len = value.len() - value.iter().rev().take_while(|&&x| b' ' == x).count();
    value.truncate(real_len);

    match byte!(stream) {
        LF => Ok(Some((name, value))),
        _ => Err(HttpHeaderError)
    }

}

/// `request-line   = method SP request-target SP HTTP-version CRLF`
pub type RequestLine = (method::Method, uri::RequestUri, HttpVersion);

/// Read the `RequestLine`, such as `GET / HTTP/1.1`.
pub fn read_request_line<R: Read>(stream: &mut R) -> HttpResult<RequestLine> {
    macro_rules! byte (
        ($rdr:ident) => ({
            let mut buf = [0];
            match try!($rdr.read(&mut buf)) {
                1 => buf[0],
                _ => return Err(HttpVersionError),
            }
        })
    );

    debug!("read request line");
    let method = try!(read_method(stream));
    debug!("method = {:?}", method);
    let uri = try!(read_uri(stream));
    debug!("uri = {:?}", uri);
    let version = try!(read_http_version(stream));
    debug!("version = {:?}", version);

    if byte!(stream) != CR {
        return Err(HttpVersionError);
    }
    if byte!(stream) != LF {
        return Err(HttpVersionError);
    }

    Ok((method, uri, version))
}

/// `status-line = HTTP-version SP status-code SP reason-phrase CRLF`
///
/// However, reason-phrase is absolutely useless, so its tossed.
pub type StatusLine = (HttpVersion, RawStatus);

/// The raw status code and reason-phrase.
#[derive(PartialEq, Debug)]
pub struct RawStatus(pub u16, pub Cow<'static, str>);

impl Clone for RawStatus {
    fn clone(&self) -> RawStatus {
        RawStatus(self.0, self.1.clone().into_cow())
    }
}

/// Read the StatusLine, such as `HTTP/1.1 200 OK`.
///
/// > The first line of a response message is the status-line, consisting
/// > of the protocol version, a space (SP), the status code, another
/// > space, a possibly empty textual phrase describing the status code,
/// > and ending with CRLF.
/// >
/// >```notrust
/// > status-line = HTTP-version SP status-code SP reason-phrase CRLF
/// > status-code    = 3DIGIT
/// > reason-phrase  = *( HTAB / SP / VCHAR / obs-text )
/// >```
pub fn read_status_line<R: Read>(stream: &mut R) -> HttpResult<StatusLine> {
    macro_rules! byte (
        ($rdr:ident) => ({
            let mut buf = [0];
            match try!($rdr.read(&mut buf)) {
                1 => buf[0],
                _ => return Err(HttpVersionError),
            }
        })
    );

    let version = try!(read_http_version(stream));
    if byte!(stream) != SP {
        return Err(HttpVersionError);
    }
    let code = try!(read_status(stream));

    Ok((version, code))
}

/// Read the StatusCode from a stream.
pub fn read_status<R: Read>(stream: &mut R) -> HttpResult<RawStatus> {
    macro_rules! byte (
        ($rdr:ident) => ({
            let mut buf = [0];
            match try!($rdr.read(&mut buf)) {
                1 => buf[0],
                _ => return Err(HttpStatusError),
            }
        })
    );

    let code = [
        byte!(stream),
        byte!(stream),
        byte!(stream),
    ];

    let code = match str::from_utf8(code.as_slice()).ok().and_then(|x| x.parse().ok()) {
        Some(num) => num,
        None => return Err(HttpStatusError)
    };

    match byte!(stream) {
        b' ' => (),
        _ => return Err(HttpStatusError)
    }

    let mut buf = [SP; 32];
    let mut cursor = Cursor::new(&mut buf[..]);
    {
        'read: loop {
            match byte!(stream) {
                CR => match byte!(stream) {
                    LF => break,
                    _ => return Err(HttpStatusError)
                },
                b => match cursor.write(&[b]) {
                    Ok(0) | Err(_) => {
                        for _ in 0u8..128 {
                            match byte!(stream) {
                                CR => match byte!(stream) {
                                    LF => break 'read,
                                    _ => return Err(HttpStatusError)
                                },
                                _ => { /* ignore */ }
                            }
                        }
                        return Err(HttpStatusError)
                    }
                    Ok(_) => (),
                }
            }
        }
    }

    let reason = match str::from_utf8(cursor.into_inner()) {
        Ok(s) => s.trim(),
        Err(_) => return Err(HttpStatusError)
    };

    let reason = match from_u16::<StatusCode>(code) {
        Some(status) => match status.canonical_reason() {
            Some(phrase) => {
                if phrase == reason {
                    Borrowed(phrase)
                } else {
                    Owned(reason.to_string())
                }
            }
            _ => Owned(reason.to_string())
        },
        None => return Err(HttpStatusError)
    };

    Ok(RawStatus(code, reason))
}

#[inline]
fn expect(actual: u8, expected: u8) -> HttpResult<()> {
    if actual == expected {
        Ok(())
    } else {
        Err(HttpVersionError)
    }
}

#[cfg(test)]
mod tests {
    use std::io::{self, Write};
    use std::borrow::Cow::{Borrowed, Owned};
    use test::Bencher;
    use uri::RequestUri;
    use uri::RequestUri::{Star, AbsoluteUri, AbsolutePath, Authority};
    use method;
    use version::HttpVersion;
    use version::HttpVersion::{Http10, Http11};
    use HttpError::{HttpVersionError, HttpMethodError};
    use HttpResult;
    use url::Url;

    use super::{read_method, read_uri, read_http_version, read_header,
                RawHeaderLine, read_status, RawStatus, read_chunk_size};
    #[test]
    fn test_read_method() {
        fn read(s: &str, result: HttpResult<method::Method>) {
            assert_eq!(read_method(&mut s.as_bytes()), result);
        }

        read("GET /", Ok(method::Method::Get));
        read("POST /", Ok(method::Method::Post));
        read("PUT /", Ok(method::Method::Put));
        read("HEAD /", Ok(method::Method::Head));
        read("OPTIONS /", Ok(method::Method::Options));
        read("CONNECT /", Ok(method::Method::Connect));
        read("TRACE /", Ok(method::Method::Trace));
        read("PATCH /", Ok(method::Method::Patch));
        read("FOO /", Ok(method::Method::Extension("FOO".to_string())));
        read("akemi!~#HOMURA /", Ok(method::Method::Extension("akemi!~#HOMURA".to_string())));
        read(" ", Err(HttpMethodError));
    }

    #[test]
    fn test_read_uri() {
        fn read(s: &str, result: HttpResult<RequestUri>) {
            assert_eq!(read_uri(&mut s.as_bytes()), result);
        }

        read("* ", Ok(Star));
        read("http://hyper.rs/ ", Ok(AbsoluteUri(Url::parse("http://hyper.rs/").unwrap())));
        read("hyper.rs ", Ok(Authority("hyper.rs".to_string())));
        read("/ ", Ok(AbsolutePath("/".to_string())));
    }

    #[test]
    fn test_read_http_version() {
        fn read(s: &str, result: HttpResult<HttpVersion>) {
            assert_eq!(read_http_version(&mut s.as_bytes()), result);
        }

        read("HTTP/1.0", Ok(Http10));
        read("HTTP/1.1", Ok(Http11));
        read("HTP/2.0", Err(HttpVersionError));
        read("HTTP.2.0", Err(HttpVersionError));
        read("HTTP 2.0", Err(HttpVersionError));
        read("TTP 2.0", Err(HttpVersionError));
    }

    #[test]
    fn test_read_status() {
        fn read(s: &str, result: HttpResult<RawStatus>) {
            assert_eq!(read_status(&mut s.as_bytes()), result);
        }

        fn read_ignore_string(s: &str, result: HttpResult<RawStatus>) {
            match (read_status(&mut s.as_bytes()), result) {
                (Ok(RawStatus(ref c1, _)), Ok(RawStatus(ref c2, _))) => {
                    assert_eq!(c1, c2);
                },
                (r1, r2) => assert_eq!(r1, r2)
            }
        }

        read("200 OK\r\n", Ok(RawStatus(200, Borrowed("OK"))));
        read("404 Not Found\r\n", Ok(RawStatus(404, Borrowed("Not Found"))));
        read("200 crazy pants\r\n", Ok(RawStatus(200, Owned("crazy pants".to_string()))));
        read("301 Moved Permanently\r\n", Ok(RawStatus(301, Owned("Moved Permanently".to_string()))));
        read_ignore_string("301 Unreasonably long header that should not happen, \
                           but some men just want to watch the world burn\r\n",
             Ok(RawStatus(301, Owned("Ignored".to_string()))));
    }

    #[test]
    fn test_read_header() {
        fn read(s: &str, result: HttpResult<Option<RawHeaderLine>>) {
            assert_eq!(read_header(&mut s.as_bytes()), result);
        }

        read("Host: rust-lang.org\r\n", Ok(Some(("Host".to_string(),
                                                 b"rust-lang.org".to_vec()))));
    }

    #[test]
    fn test_write_chunked() {
        use std::str::from_utf8;
        let mut w = super::HttpWriter::ChunkedWriter(Vec::new());
        w.write_all(b"foo bar").unwrap();
        w.write_all(b"baz quux herp").unwrap();
        let buf = w.end().unwrap();
        let s = from_utf8(buf.as_slice()).unwrap();
        assert_eq!(s, "7\r\nfoo bar\r\nD\r\nbaz quux herp\r\n0\r\n\r\n");
    }

    #[test]
    fn test_write_sized() {
        use std::str::from_utf8;
        let mut w = super::HttpWriter::SizedWriter(Vec::new(), 8);
        w.write_all(b"foo bar").unwrap();
        assert_eq!(w.write(b"baz"), Ok(1));

        let buf = w.end().unwrap();
        let s = from_utf8(buf.as_slice()).unwrap();
        assert_eq!(s, "foo barb");
    }

    #[test]
    fn test_read_chunk_size() {
        fn read(s: &str, result: io::Result<u64>) {
            assert_eq!(read_chunk_size(&mut s.as_bytes()), result);
        }

        fn read_err(s: &str) {
            assert_eq!(read_chunk_size(&mut s.as_bytes()).unwrap_err().kind(), io::ErrorKind::InvalidInput);
        }

        read("1\r\n", Ok(1));
        read("01\r\n", Ok(1));
        read("0\r\n", Ok(0));
        read("00\r\n", Ok(0));
        read("A\r\n", Ok(10));
        read("a\r\n", Ok(10));
        read("Ff\r\n", Ok(255));
        read("Ff   \r\n", Ok(255));
        // Missing LF or CRLF
        read_err("F\rF");
        read_err("F");
        // Invalid hex digit
        read_err("X\r\n");
        read_err("1X\r\n");
        read_err("-\r\n");
        read_err("-1\r\n");
        // Acceptable (if not fully valid) extensions do not influence the size
        read("1;extension\r\n", Ok(1));
        read("a;ext name=value\r\n", Ok(10));
        read("1;extension;extension2\r\n", Ok(1));
        read("1;;;  ;\r\n", Ok(1));
        read("2; extension...\r\n", Ok(2));
        read("3   ; extension=123\r\n", Ok(3));
        read("3   ;\r\n", Ok(3));
        read("3   ;   \r\n", Ok(3));
        // Invalid extensions cause an error
        read_err("1 invalid extension\r\n");
        read_err("1 A\r\n");
        read_err("1;no CRLF");
    }

    #[bench]
    fn bench_read_method(b: &mut Bencher) {
        b.bytes = b"CONNECT ".len() as u64;
        b.iter(|| assert_eq!(read_method(&mut b"CONNECT "), Ok(method::Method::Connect)));
    }

    #[bench]
    fn bench_read_status(b: &mut Bencher) {
        b.bytes = b"404 Not Found\r\n".len() as u64;
        b.iter(|| assert_eq!(read_status(&mut b"404 Not Found\r\n"), Ok(RawStatus(404, Borrowed("Not Found")))));
    }

}