rhymuweb 1.2.1

Common types for the Hypertext Transfer Protocol (HTTP)
Documentation
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
950
951
use super::{
    chunked_body::{
        ChunkedBody,
        DecodeStatus as ChunkedBodyDecodeStatus,
    },
    error::Error,
    find_crlf,
    CRLF,
};
use rhymessage::{
    Header,
    MessageHeaders,
};
use std::io::Write;

fn parse_status_line(status_line: &str) -> Result<(usize, &str), Error> {
    // Parse the protocol.
    let protocol_delimiter = status_line.find(' ').ok_or_else(|| {
        Error::StatusLineNoProtocolDelimiter(status_line.into())
    })?;
    let protocol = &status_line[..protocol_delimiter];
    if protocol != "HTTP/1.1" {
        return Err(Error::StatusLineProtocol(status_line.into()));
    }

    // Parse the status code.
    let status_line_at_status_code = &status_line[protocol_delimiter + 1..];
    let status_code_delimiter =
        status_line_at_status_code.find(' ').ok_or_else(|| {
            Error::StatusLineNoStatusCodeDelimiter(status_line.into())
        })?;
    let status_code = status_line_at_status_code[..status_code_delimiter]
        .parse::<usize>()
        .map_err(Error::InvalidStatusCode)
        .and_then(|status_code| match status_code {
            status_code if status_code < 1000 => Ok(status_code),
            status_code => Err(Error::StatusCodeOutOfRange(status_code)),
        })?;

    // Parse the reason phrase.
    let reason_phrase =
        &status_line_at_status_code[status_code_delimiter + 1..];
    Ok((status_code, reason_phrase))
}

#[derive(Debug)]
enum ResponseState {
    ChunkedBody(ChunkedBody),
    FixedBody(usize),
    Headers,
    StatusLine,
}

impl Default for ResponseState {
    fn default() -> Self {
        Self::StatusLine
    }
}

/// This enumerates the possible non-error states `Response` can be in
/// after parsing a bit of input.
#[derive(Debug, Eq, PartialEq)]
pub enum ParseStatus {
    /// The response was fully parsed.
    Complete,

    /// The response has not yet been fully parsed.
    ///
    /// The user is expected to call `parse` again with more input, starting
    /// with the unparsed portion of the previous input string, and adding more
    /// to it.
    Incomplete,
}

/// This holds the values returned by `Response::parse`.
#[derive(Debug, Eq, PartialEq)]
pub struct ParseResults {
    /// This indicates the state of the parser.
    pub status: ParseStatus,

    /// This is the number of bytes of input consumed by the last
    /// `Response::parse` call.
    pub consumed: usize,
}

enum ParseStatusInternal {
    CompletePart,
    CompleteWhole,
    Incomplete,
}

#[derive(Debug)]
/// This type is used to parse and generate HTTP 1.1 responses.
pub struct Response {
    /// This holds the bytes which compose the body of the response.
    pub body: Vec<u8>,

    /// This holds any headers for the response.
    pub headers: MessageHeaders,

    /// This is the reason phrase in the response, which is a textual
    /// description associated with the numeric status code.
    pub reason_phrase: std::borrow::Cow<'static, str>,

    state: ResponseState,

    /// This is the numeric status code in the response, which describes the
    /// result of the server's attempt to understand and satisfy the client's
    /// corresponding request.  It is defined in [IETF RFC 7231 section
    /// 6](https://tools.ietf.org/html/rfc7231#section-6).
    pub status_code: usize,

    /// This holds any bytes received from the server that came after
    /// the HTTP response.  They may be junk or the first bytes of the
    /// first message(s) sent by the server using a higher-level protocol.
    /// It's not our business to judge. ¯\_(ツ)_/¯
    pub trailer: Vec<u8>,
}

impl Response {
    /// Produce the raw bytes form of the response, according to the rules of
    /// [IETF RFC 7320 section
    /// 3](https://tools.ietf.org/html/rfc7230#section-3):
    ///
    /// * The status line appears first, containing the protocol identifier,
    ///   numeric status code, and reason phrase.
    /// * The response header lines follow the status line.
    /// * An empty text line follows the header lines.
    /// * The body, if any, appears last.  Its length is determined by the
    ///   "Content-Length" header.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate rhymuweb;
    /// use rhymessage::Header;
    /// use rhymuweb::Response;
    ///
    /// # fn main() -> Result<(), rhymessage::Error> {
    /// let mut response = Response::new();
    /// response.status_code = 200;
    /// response.reason_phrase = "OK".into();
    /// response.headers.add_header(Header{
    ///     name: "Date".into(),
    ///     value: "Mon, 27 Jul 2009 12:28:53 GMT".into()
    /// });
    /// response.headers.add_header(Header{
    ///     name: "Accept-Ranges".into(),
    ///     value: "bytes".into()
    /// });
    /// response.headers.add_header(Header{
    ///     name: "Content-Type".into(),
    ///     value: "text/plain".into()
    /// });
    /// response.body = "Hello World! My payload includes a trailing CRLF.\r\n".into();
    /// response.headers.add_header(Header{
    ///     name: "Content-Length".into(),
    ///     value: format!("{}", response.body.len())
    /// });
    /// assert!(matches!(
    ///     response.generate(),
    ///     Ok(raw_response) if raw_response == format!(
    ///         concat!(
    ///             "HTTP/1.1 200 OK\r\n",
    ///             "Date: Mon, 27 Jul 2009 12:28:53 GMT\r\n",
    ///             "Accept-Ranges: bytes\r\n",
    ///             "Content-Type: text/plain\r\n",
    ///             "Content-Length: {}\r\n",
    ///             "\r\n",
    ///             "Hello World! My payload includes a trailing CRLF.\r\n",
    ///         ),
    ///         response.body.len()
    ///     ).as_bytes()
    /// ));
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// * [`Error::Headers`](enum.Error.html#variant.Headers) &ndash; the
    ///   headers generator is configured with a line limit constraint and one
    ///   or more headers are too long and cannot be folded to fit within the
    ///   constraint.
    /// * [`Error::StringFormat`](enum.Error.html#variant.StringFormat) &ndash;
    ///   while technically it shouldn't happen, logically this may be returned
    ///   if one of the internal string formatting functions should fail (which
    ///   they shouldn't unless something used internally doesn't implement
    ///   [`Display`](https://doc.rust-lang.org/std/fmt/trait.Display.html)
    ///   properly.
    pub fn generate(&self) -> Result<Vec<u8>, Error> {
        let mut output = Vec::new();
        write!(
            &mut output,
            "HTTP/1.1 {} {}\r\n",
            self.status_code, self.reason_phrase
        )
        .map_err(Error::StringFormat)?;
        output.append(&mut self.headers.generate().map_err(Error::Headers)?);
        output.extend(&self.body);
        Ok(output)
    }

    /// Create a new response value with default status code (200), reason
    /// phrase ("OK"), and no headers or body.
    #[must_use]
    pub fn new() -> Self {
        Self {
            body: Vec::new(),
            headers: MessageHeaders::new(),
            reason_phrase: "OK".into(),
            state: ResponseState::default(),
            status_code: 200,
            trailer: Vec::new(),
        }
    }

    /// Feed more bytes into the parser, building the response internally, and
    /// detecting when the end of the response has been found.
    ///
    /// This function may be called multiple times to parse input
    /// incrementally.  Each call returns an indication of whether or
    /// not a message was parsed and how many input bytes were consumed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate rhymuweb;
    /// use rhymuri::Uri;
    /// use rhymuweb::{Response, ResponseParseResults, ResponseParseStatus};
    ///
    /// # fn main() -> Result<(), rhymessage::Error> {
    /// let raw_response = concat!(
    ///     "HTTP/1.1 200 OK\r\n",
    ///     "Date: Mon, 27 Jul 2009 12:28:53 GMT\r\n",
    ///     "Server: Apache\r\n",
    ///     "Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT\r\n",
    ///     "ETag: \"34aa387-d-1568eb00\"\r\n",
    ///     "Accept-Ranges: bytes\r\n",
    ///     "Transfer-Encoding: chunked\r\n",
    ///     "Vary: Accept-Encoding\r\n",
    ///     "Content-Type: text/plain\r\n",
    ///     "Trailer: X-Foo\r\n",
    ///     "\r\n",
    ///     "C\r\n",
    ///     "Hello World!\r\n",
    ///     "16\r\n",
    ///     " My payload includes a\r\n",
    ///     "11\r\n",
    ///     " trailing CRLF.\r\n\r\n",
    ///     "0\r\n",
    ///     "X-Foo: Bar\r\n",
    ///     "\r\n",
    /// );
    /// let mut response = Response::new();
    /// assert!(matches!(
    ///     response.parse(raw_response),
    ///     Ok(ResponseParseResults{
    ///         status: ResponseParseStatus::Complete,
    ///         consumed
    ///     }) if consumed == raw_response.len()
    /// ));
    /// assert_eq!(200, response.status_code);
    /// assert_eq!("OK", response.reason_phrase);
    /// assert!(response.headers.has_header("Date"));
    /// assert_eq!(
    ///     Some("Mon, 27 Jul 2009 12:28:53 GMT"),
    ///     response.headers.header_value("Date").as_deref()
    /// );
    /// assert!(response.headers.has_header("Accept-Ranges"));
    /// assert_eq!(
    ///     Some("bytes"),
    ///     response.headers.header_value("Accept-Ranges").as_deref()
    /// );
    /// assert!(response.headers.has_header("Content-Type"));
    /// assert_eq!(
    ///     Some("text/plain"),
    ///     response.headers.header_value("Content-Type").as_deref()
    /// );
    /// assert_eq!(
    ///     Some("Bar"),
    ///     response.headers.header_value("X-Foo").as_deref()
    /// );
    /// assert_eq!(
    ///     Some("51"),
    ///     response.headers.header_value("Content-Length").as_deref()
    /// );
    /// assert_eq!(
    ///     "Hello World! My payload includes a trailing CRLF.\r\n".as_bytes(),
    ///     response.body
    /// );
    /// assert!(!response.headers.has_header_token("Transfer-Encoding", "chunked"));
    /// assert!(!response.headers.has_header("Trailer"));
    /// assert!(!response.headers.has_header("Transfer-Encoding"));
    /// assert_eq!(
    ///     "Hello World! My payload includes a trailing CRLF.\r\n".as_bytes(),
    ///     response.body
    /// );
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// * [`Error::StatusLineNotValidText`][StatusLineNotValidText] &ndash; the
    ///   status line contained bytes which could not be decoded as valid UTF-8
    ///   text
    /// * [`Error::StatusLineNoProtocolDelimiter`][StatusLineNoProtocolDelimiter]
    ///   &ndash; the protocol identifier part of the status line could not be
    ///   parsed because no space character delimiting the protocol identifier
    ///   from the numeric status code could be found
    /// * [`Error::StatusLineProtocol`][StatusLineProtocol] &ndash; the protocol
    ///   identifier part of the status line is either missing or does not match
    ///   "HTTP/1.1"
    /// * [`Error::StatusLineNoStatusCodeDelimiter`][StatusLineNoStatusCodeDelimiter]
    ///   &ndash; the numeric status code part of the status line could not be
    ///   parsed because no space character delimiting the numeric status code
    ///   from the reason phrase could be found
    /// * [`Error::InvalidStatusCode`][InvalidStatusCode] &ndash; the value of
    ///   the numeric status code in the status line could not be parsed
    /// * [`Error::StatusCodeOutOfRange`][StatusCodeOutOfRange] &ndash; the
    ///   value of the numeric status code in the status line is greater than
    ///   999, the maximum permitted value
    /// * [`Error::Headers`][Headers] &ndash; an error occurred parsing the
    ///   response headers
    /// * [`Error::InvalidContentLength`][InvalidContentLength] &ndash; the
    ///   value of the "Content-Length" header of the response could not be
    ///   parsed
    /// * [`Error::ChunkSizeLineNotValidText`][ChunkSizeLineNotValidText]
    ///   &ndash; a chunk size line contained bytes which could not be decoded
    ///   as valid UTF-8 text
    /// * [`Error::InvalidChunkSize`][InvalidChunkSize] &ndash; the value of a
    ///   chunk size could not be parsed
    /// * [`Error::InvalidChunkTerminator`][InvalidChunkTerminator] &ndash;
    ///   extra junk was found at the end of a chunk rather than carriage-return
    ///   and line-feed, which are required
    /// * [`Error::Trailer`][Trailer] &ndash; an error occurred parsing the
    ///   headers contained in the trailer for the chunked-encoded body
    ///
    /// [StatusLineNotValidText]: enum.Error.html#variant.StatusLineNotValidText
    /// [StatusLineNoProtocolDelimiter]:
    /// enum.Error.html#variant.StatusLineNoProtocolDelimiter
    /// [StatusLineProtocol]: enum.Error.html#variant.StatusLineProtocol
    /// [StatusLineNoStatusCodeDelimiter]:
    /// enum.Error.html#variant.StatusLineNoStatusCodeDelimiter
    /// [InvalidStatusCode]: enum.Error.html#variant.InvalidStatusCode
    /// [StatusCodeOutOfRange]: enum.Error.html#variant.StatusCodeOutOfRange
    /// [Headers]: enum.Error.html#variant.Headers
    /// [InvalidContentLength]: enum.Error.html#variant.InvalidContentLength
    /// [ChunkSizeLineNotValidText]:
    /// enum.Error.html#variant.ChunkSizeLineNotValidText
    /// [InvalidChunkSize]: enum.Error.html#variant.InvalidChunkSize
    /// [InvalidChunkTerminator]: enum.Error.html#variant.InvalidChunkTerminator
    /// [Trailer]: enum.Error.html#variant.Trailer
    pub fn parse<T>(
        &mut self,
        raw_message: T,
    ) -> Result<ParseResults, Error>
    where
        T: AsRef<[u8]>,
    {
        let raw_message = raw_message.as_ref();
        let mut total_consumed = 0;
        loop {
            let raw_message_remainder = &raw_message[total_consumed..];
            let state = std::mem::take(&mut self.state);
            let (parse_status, state, consumed) = match state {
                ResponseState::ChunkedBody(chunked_body) => self
                    .parse_message_for_chunked_body(
                        raw_message_remainder,
                        chunked_body,
                    )?,
                ResponseState::FixedBody(content_length) => {
                    let (parse_status, consumed) = self
                        .parse_message_for_fixed_body(
                            raw_message_remainder,
                            content_length,
                        );
                    (
                        parse_status,
                        ResponseState::FixedBody(content_length),
                        consumed,
                    )
                },
                ResponseState::Headers => {
                    self.parse_message_for_headers(raw_message_remainder)?
                },
                ResponseState::StatusLine => {
                    self.parse_message_for_status_line(raw_message_remainder)?
                },
            };
            self.state = state;
            total_consumed += consumed;
            match parse_status {
                ParseStatusInternal::CompletePart => (),
                ParseStatusInternal::CompleteWhole => {
                    return Ok(ParseResults {
                        status: ParseStatus::Complete,
                        consumed: total_consumed,
                    });
                },
                ParseStatusInternal::Incomplete => {
                    return Ok(ParseResults {
                        status: ParseStatus::Incomplete,
                        consumed: total_consumed,
                    });
                },
            };
        }
    }

    fn parse_message_for_chunked_body(
        &mut self,
        raw_message: &[u8],
        mut chunked_body: ChunkedBody,
    ) -> Result<(ParseStatusInternal, ResponseState, usize), Error> {
        match chunked_body.decode(raw_message)? {
            (ChunkedBodyDecodeStatus::Complete, consumed) => {
                self.body = std::mem::take(&mut chunked_body.buffer);
                for header in chunked_body.trailer {
                    self.headers.add_header(header);
                }

                // Now that we've decoded the chunked body, we should remove
                // the "chunked" token from the `Transfer-Encoding` header,
                // and add a `Content-Length` header.
                let mut transfer_encodings =
                    self.headers.header_tokens("Transfer-Encoding");
                transfer_encodings.pop();
                if transfer_encodings.is_empty() {
                    self.headers.remove_header("Transfer-Encoding");
                } else {
                    self.headers.set_header(
                        "Transfer-Encoding",
                        transfer_encodings.join(" "),
                    );
                }
                self.headers.add_header(Header {
                    name: "Content-Length".into(),
                    value: self.body.len().to_string(),
                });
                self.headers.remove_header("Trailer");
                Ok((
                    ParseStatusInternal::CompleteWhole,
                    ResponseState::default(),
                    consumed,
                ))
            },
            (ChunkedBodyDecodeStatus::Incomplete, consumed) => Ok((
                ParseStatusInternal::Incomplete,
                ResponseState::ChunkedBody(chunked_body),
                consumed,
            )),
        }
    }

    fn parse_message_for_fixed_body(
        &mut self,
        raw_message: &[u8],
        content_length: usize,
    ) -> (ParseStatusInternal, usize) {
        let needed = content_length - self.body.len();
        (
            if raw_message.len() >= needed {
                self.body.extend(&raw_message[..needed]);
                self.trailer.extend(&raw_message[needed..]);
                ParseStatusInternal::CompleteWhole
            } else {
                self.body.extend(raw_message);
                ParseStatusInternal::Incomplete
            },
            raw_message.len(),
        )
    }

    fn parse_message_for_headers(
        &mut self,
        raw_message: &[u8],
    ) -> Result<(ParseStatusInternal, ResponseState, usize), Error> {
        let parse_results =
            self.headers.parse(raw_message).map_err(Error::Headers)?;
        match parse_results.status {
            rhymessage::ParseStatus::Complete => {
                if let Some(content_length) =
                    self.headers.header_value("Content-Length")
                {
                    let content_length = content_length
                        .parse::<usize>()
                        .map_err(Error::InvalidContentLength)?;
                    self.body.reserve(content_length);
                    Ok((
                        ParseStatusInternal::CompletePart,
                        ResponseState::FixedBody(content_length),
                        parse_results.consumed,
                    ))
                } else if self
                    .headers
                    .has_header_token("Transfer-Encoding", "chunked")
                {
                    Ok((
                        ParseStatusInternal::CompletePart,
                        ResponseState::ChunkedBody(ChunkedBody::new()),
                        parse_results.consumed,
                    ))
                } else {
                    Ok((
                        ParseStatusInternal::CompleteWhole,
                        ResponseState::Headers,
                        parse_results.consumed,
                    ))
                }
            },
            rhymessage::ParseStatus::Incomplete => Ok((
                ParseStatusInternal::Incomplete,
                ResponseState::Headers,
                parse_results.consumed,
            )),
        }
    }

    fn parse_message_for_status_line(
        &mut self,
        raw_message: &[u8],
    ) -> Result<(ParseStatusInternal, ResponseState, usize), Error> {
        match find_crlf(raw_message) {
            Some(status_line_end) => {
                let status_line = &raw_message[0..status_line_end];
                let status_line =
                    std::str::from_utf8(status_line).map_err(|source| {
                        Error::StatusLineNotValidText {
                            status_line: status_line.to_vec(),
                            source,
                        }
                    })?;
                let consumed = status_line_end + CRLF.len();
                let (status_code, reason_phrase) =
                    parse_status_line(status_line)?;
                self.status_code = status_code;
                self.reason_phrase = reason_phrase.to_string().into();
                Ok((
                    ParseStatusInternal::CompletePart,
                    ResponseState::Headers,
                    consumed,
                ))
            },
            None => Ok((
                ParseStatusInternal::Incomplete,
                ResponseState::StatusLine,
                0,
            )),
        }
    }
}

impl Default for Response {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {

    #![allow(clippy::string_lit_as_bytes)]

    use super::*;

    #[test]
    fn generate_get_response() {
        let mut response = Response::new();
        response.status_code = 200;
        response.reason_phrase = "OK".into();
        response.headers.add_header(Header {
            name: "Date".into(),
            value: "Mon, 27 Jul 2009 12:28:53 GMT".into(),
        });
        response.headers.add_header(Header {
            name: "Accept-Ranges".into(),
            value: "bytes".into(),
        });
        response.headers.add_header(Header {
            name: "Content-Type".into(),
            value: "text/plain".into(),
        });
        response.body =
            "Hello World! My payload includes a trailing CRLF.\r\n".into();
        response.headers.add_header(Header {
            name: "Content-Length".into(),
            value: format!("{}", response.body.len()),
        });
        assert!(matches!(
            response.generate(),
            Ok(raw_response) if raw_response == format!(
                concat!(
                    "HTTP/1.1 200 OK\r\n",
                    "Date: Mon, 27 Jul 2009 12:28:53 GMT\r\n",
                    "Accept-Ranges: bytes\r\n",
                    "Content-Type: text/plain\r\n",
                    "Content-Length: {}\r\n",
                    "\r\n",
                    "Hello World! My payload includes a trailing CRLF.\r\n",
                ),
                response.body.len()
            ).as_bytes()
        ));
    }

    #[test]
    fn parse_get_response_with_body_and_content_length() {
        let raw_response = concat!(
            "HTTP/1.1 200 OK\r\n",
            "Date: Mon, 27 Jul 2009 12:28:53 GMT\r\n",
            "Server: Apache\r\n",
            "Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT\r\n",
            "ETag: \"34aa387-d-1568eb00\"\r\n",
            "Accept-Ranges: bytes\r\n",
            "Content-Length: 51\r\n",
            "Vary: Accept-Encoding\r\n",
            "Content-Type: text/plain\r\n",
            "\r\n",
            "Hello World! My payload includes a trailing CRLF.\r\n",
        );
        let mut response = Response::new();
        assert!(matches!(
            response.parse(raw_response),
            Ok(ParseResults{
                status: ParseStatus::Complete,
                consumed
            }) if consumed == raw_response.len()
        ));
        assert_eq!(200, response.status_code);
        assert_eq!("OK", response.reason_phrase);
        assert!(response.headers.has_header("Date"));
        assert_eq!(
            Some("Mon, 27 Jul 2009 12:28:53 GMT"),
            response.headers.header_value("Date").as_deref()
        );
        assert!(response.headers.has_header("Accept-Ranges"));
        assert_eq!(
            Some("bytes"),
            response.headers.header_value("Accept-Ranges").as_deref()
        );
        assert!(response.headers.has_header("Content-Type"));
        assert_eq!(
            Some("text/plain"),
            response.headers.header_value("Content-Type").as_deref()
        );
        assert!(response.headers.has_header("Content-Length"));
        assert_eq!(
            Some("51"),
            response.headers.header_value("Content-Length").as_deref()
        );
        assert_eq!(
            "Hello World! My payload includes a trailing CRLF.\r\n".as_bytes(),
            response.body
        );
    }

    #[test]
    fn parse_get_response_with_chunked_body_no_other_transfer_coding() {
        let raw_response = concat!(
            "HTTP/1.1 200 OK\r\n",
            "Date: Mon, 27 Jul 2009 12:28:53 GMT\r\n",
            "Server: Apache\r\n",
            "Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT\r\n",
            "ETag: \"34aa387-d-1568eb00\"\r\n",
            "Accept-Ranges: bytes\r\n",
            "Transfer-Encoding: chunked\r\n",
            "Vary: Accept-Encoding\r\n",
            "Content-Type: text/plain\r\n",
            "Trailer: X-Foo\r\n",
            "\r\n",
            "C\r\n",
            "Hello World!\r\n",
            "16\r\n",
            " My payload includes a\r\n",
            "11\r\n",
            " trailing CRLF.\r\n\r\n",
            "0\r\n",
            "X-Foo: Bar\r\n",
            "\r\n",
        );
        let mut response = Response::new();
        assert!(matches!(
            response.parse(raw_response),
            Ok(ParseResults{
                status: ParseStatus::Complete,
                consumed
            }) if consumed == raw_response.len()
        ));
        assert_eq!(200, response.status_code);
        assert_eq!("OK", response.reason_phrase);
        assert!(response.headers.has_header("Date"));
        assert_eq!(
            Some("Mon, 27 Jul 2009 12:28:53 GMT"),
            response.headers.header_value("Date").as_deref()
        );
        assert!(response.headers.has_header("Accept-Ranges"));
        assert_eq!(
            Some("bytes"),
            response.headers.header_value("Accept-Ranges").as_deref()
        );
        assert!(response.headers.has_header("Content-Type"));
        assert_eq!(
            Some("text/plain"),
            response.headers.header_value("Content-Type").as_deref()
        );
        assert_eq!(
            Some("Bar"),
            response.headers.header_value("X-Foo").as_deref()
        );
        assert_eq!(
            Some("51"),
            response.headers.header_value("Content-Length").as_deref()
        );
        assert_eq!(
            "Hello World! My payload includes a trailing CRLF.\r\n".as_bytes(),
            response.body
        );
        assert!(!response
            .headers
            .has_header_token("Transfer-Encoding", "chunked"));
        assert!(!response.headers.has_header("Trailer"));
        assert!(!response.headers.has_header("Transfer-Encoding"));
        assert_eq!(
            "Hello World! My payload includes a trailing CRLF.\r\n".as_bytes(),
            response.body
        );
    }

    #[test]
    fn parse_get_response_with_chunked_body_with_other_transfer_coding() {
        let raw_response = concat!(
            "HTTP/1.1 200 OK\r\n",
            "Date: Mon, 27 Jul 2009 12:28:53 GMT\r\n",
            "Transfer-Encoding: foobar, chunked\r\n",
            "Content-Type: text/plain\r\n",
            "\r\n",
            "0\r\n",
            "\r\n",
        );
        let mut response = Response::new();
        assert!(matches!(
            response.parse(raw_response),
            Ok(ParseResults{
                status: ParseStatus::Complete,
                consumed
            }) if consumed == raw_response.len()
        ));
        assert_eq!(
            Some("foobar"),
            response.headers.header_value("Transfer-Encoding").as_deref()
        );
    }

    #[test]
    fn parse_incomplete_body_response() {
        let raw_response = concat!(
            "HTTP/1.1 200 OK\r\n",
            "Date: Mon, 27 Jul 2009 12:28:53 GMT\r\n",
            "Server: Apache\r\n",
            "Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT\r\n",
            "ETag: \"34aa387-d-1568eb00\"\r\n",
            "Accept-Ranges: bytes\r\n",
            "Content-Length: 52\r\n",
            "Vary: Accept-Encoding\r\n",
            "Content-Type: text/plain\r\n",
            "\r\n",
            "Hello World! My payload includes a trailing CRLF.\r\n",
        );
        let mut response = Response::new();
        assert!(matches!(
            response.parse(raw_response),
            Ok(ParseResults{
                status: ParseStatus::Incomplete,
                consumed
            }) if consumed == raw_response.len()
        ));
    }

    #[test]
    fn parse_incomplete_headers_between_lines_response() {
        let raw_response_first_part = concat!(
            "HTTP/1.1 200 OK\r\n",
            "Date: Mon, 27 Jul 2009 12:28:53 GMT\r\n",
            "Server: Apache\r\n",
            "Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT\r\n",
        );
        let raw_response = String::from(raw_response_first_part)
            + "ETag: \"34aa387-d-1568eb00\"\r\n";
        let mut response = Response::new();
        assert!(matches!(
            response.parse(raw_response),
            Ok(ParseResults{
                status: ParseStatus::Incomplete,
                consumed
            }) if consumed == raw_response_first_part.len()
        ));
    }

    #[test]
    fn parse_incomplete_headers_mid_line_response() {
        let raw_response_first_part = concat!(
            "HTTP/1.1 200 OK\r\n",
            "Date: Mon, 27 Jul 2009 12:28:53 GMT\r\n",
        );
        let raw_response = String::from(raw_response_first_part)
            + "Server: Apache\r\n"
            + "Last-Modified: Wed, 22 Ju";
        let mut response = Response::new();
        assert!(matches!(
            response.parse(raw_response),
            Ok(ParseResults{
                status: ParseStatus::Incomplete,
                consumed
            }) if consumed == raw_response_first_part.len()
        ));
    }

    #[test]
    fn parse_incomplete_status_line() {
        let raw_response = "HTTP/1.1 200 OK\r";
        let mut response = Response::new();
        assert!(matches!(
            response.parse(raw_response),
            Ok(ParseResults {
                status: ParseStatus::Incomplete,
                consumed: 0
            })
        ));
    }

    #[test]
    fn parse_no_headers_response() {
        let raw_response = "HTTP/1.1 200 OK\r\n";
        let mut response = Response::new();
        assert!(matches!(
            response.parse(raw_response),
            Ok(ParseResults{
                status: ParseStatus::Incomplete,
                consumed
            }) if consumed == raw_response.len()
        ));
    }

    #[test]
    fn parse_invalid_response_no_protocol() {
        let raw_response = " 200 OK\r\n";
        let mut response = Response::new();
        assert!(matches!(
            response.parse(raw_response),
            Err(Error::StatusLineProtocol(line)) if line == " 200 OK"
        ));
    }

    #[test]
    fn parse_invalid_response_no_status_code() {
        let raw_response = "HTTP/1.1  OK\r\n";
        let mut response = Response::new();
        assert!(matches!(
            response.parse(raw_response),
            Err(Error::InvalidStatusCode(_))
        ));
    }

    #[test]
    fn parse_invalid_response_no_reason_phrase() {
        let raw_response = "HTTP/1.1 200\r\n";
        let mut response = Response::new();
        assert!(matches!(
            response.parse(raw_response),
            Err(Error::StatusLineNoStatusCodeDelimiter(line))
                if line == "HTTP/1.1 200"
        ));
    }

    #[test]
    fn parse_invalid_damaged_header() {
        let raw_response = concat!(
            "HTTP/1.1 200 OK\r\n",
            "Date: Mon, 27 Jul 2009 12:28:53 GMT\r\n",
            "Server: Apache\r\n",
            "Last-Modified Wed, 22 Jul 2009 19:15:56 GMT\r\n",
            "ETag: \"34aa387-d-1568eb00\"\r\n",
            "Accept-Ranges: bytes\r\n",
            "Content-Length: 51\r\n",
            "Vary: Accept-Encoding\r\n",
            "Content-Type: text/plain\r\n",
            "\r\n",
            "Hello World! My payload includes a trailing CRLF.\r\n",
        );
        let mut response = Response::new();
        assert!(matches!(
            response.parse(raw_response),
            Err(Error::Headers(
                rhymessage::Error::HeaderNameContainsIllegalCharacter(name)
            )) if name == "Last-Modified Wed, 22 Jul 2009 19"
        ));
    }

    #[test]
    fn response_with_no_content_length_or_chunked_transfer_encoding_has_no_body(
    ) {
        let raw_response = concat!(
            "HTTP/1.1 200 OK\r\n",
            "Date: Mon, 27 Jul 2009 12:28:53 GMT\r\n",
            "Server: Apache\r\n",
            "Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT\r\n",
            "ETag: \"34aa387-d-1568eb00\"\r\n",
            "Accept-Ranges: bytes\r\n",
            "Vary: Accept-Encoding\r\n",
            "Content-Type: text/plain\r\n",
            "\r\n",
        );
        let trailer = "Hello World! My payload includes a trailing CRLF.\r\n";
        let mut response = Response::new();
        assert!(matches!(
            response.parse(String::from(raw_response) + trailer),
            Ok(ParseResults{
                status: ParseStatus::Complete,
                consumed
            }) if consumed == raw_response.len()
        ));
        assert!(response.body.is_empty());
    }

    #[test]
    fn parse_response_trailer() {
        let raw_response = concat!(
            "HTTP/1.1 200 OK\r\n",
            "Content-Length: 18\r\n",
            "Content-Type: text/plain\r\n",
            "\r\n",
            "This is the body\r\n",
            "This is some extra trailer junk.",
        );
        let mut response = Response::new();
        assert!(matches!(
            response.parse(raw_response),
            Ok(ParseResults{
                status: ParseStatus::Complete,
                consumed
            }) if consumed == raw_response.len()
        ));
        assert_eq!("This is the body\r\n".as_bytes(), response.body);
        assert_eq!(
            "This is some extra trailer junk.".as_bytes(),
            response.trailer
        );
    }
}