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
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use std::collections::HashMap;
use std::result::Result;

use crate::HttpHeaderError;
use crate::RequestError;

/// Wrapper over an HTTP Header type.
#[derive(Debug, Eq, Hash, PartialEq)]
pub enum Header {
    /// Header `Content-Length`.
    ContentLength,
    /// Header `Content-Type`.
    ContentType,
    /// Header `Expect`.
    Expect,
    /// Header `Transfer-Encoding`.
    TransferEncoding,
    /// Header `Server`.
    Server,
    /// Header `Accept`
    Accept,
    /// Header `Accept-Encoding`
    AcceptEncoding,
}

impl Header {
    /// Returns a byte slice representation of the object.
    pub fn raw(&self) -> &'static [u8] {
        match self {
            Self::ContentLength => b"Content-Length",
            Self::ContentType => b"Content-Type",
            Self::Expect => b"Expect",
            Self::TransferEncoding => b"Transfer-Encoding",
            Self::Server => b"Server",
            Self::Accept => b"Accept",
            Self::AcceptEncoding => b"Accept-Encoding",
        }
    }

    /// Parses a byte slice into a Header structure. Header must be ASCII, so also
    /// UTF-8 valid.
    ///
    /// # Errors
    /// `InvalidRequest` is returned if slice contains invalid utf8 characters.
    /// `InvalidHeader` is returned if unsupported header found.
    fn try_from(string: &[u8]) -> Result<Self, RequestError> {
        if let Ok(mut utf8_string) = String::from_utf8(string.to_vec()) {
            utf8_string.make_ascii_lowercase();
            match utf8_string.trim() {
                "content-length" => Ok(Self::ContentLength),
                "content-type" => Ok(Self::ContentType),
                "expect" => Ok(Self::Expect),
                "transfer-encoding" => Ok(Self::TransferEncoding),
                "server" => Ok(Self::Server),
                "accept" => Ok(Self::Accept),
                "accept-encoding" => Ok(Self::AcceptEncoding),
                invalid_key => Err(RequestError::HeaderError(HttpHeaderError::UnsupportedName(
                    invalid_key.to_string(),
                ))),
            }
        } else {
            Err(RequestError::InvalidRequest)
        }
    }
}

/// Wrapper over the list of headers associated with a Request that we need
/// in order to parse the request correctly and be able to respond to it.
///
/// The only `Content-Type`s supported are `text/plain` and `application/json`, which are both
/// in plain text actually and don't influence our parsing process.
///
/// All the other possible header fields are not necessary in order to serve this connection
/// and, thus, are not of interest to us. However, we still look for header fields that might
/// invalidate our request as we don't support the full set of HTTP/1.1 specification.
/// Such header entries are "Transfer-Encoding: identity; q=0", which means a compression
/// algorithm is applied to the body of the request, or "Expect: 103-checkpoint".
#[derive(Debug, Eq, PartialEq)]
pub struct Headers {
    /// The `Content-Length` header field tells us how many bytes we need to receive
    /// from the source after the headers.
    content_length: u32,
    /// The `Expect` header field is set when the headers contain the entry "Expect: 100-continue".
    /// This means that, per HTTP/1.1 specifications, we must send a response with the status code
    /// 100 after we have received the headers in order to receive the body of the request. This
    /// field should be known immediately after parsing the headers.
    expect: bool,
    /// `Chunked` is a possible value of the `Transfer-Encoding` header field and every HTTP/1.1
    /// server must support it. It is useful only when receiving the body of the request and should
    /// be known immediately after parsing the headers.
    chunked: bool,
    /// `Accept` header might be used by HTTP clients to enforce server responses with content
    /// formatted in a specific way.
    accept: MediaType,
    /// Hashmap reserved for storing custom headers.
    custom_entries: HashMap<String, String>,
}

impl Default for Headers {
    /// By default Requests are created with no headers.
    fn default() -> Self {
        Self {
            content_length: Default::default(),
            expect: Default::default(),
            chunked: Default::default(),
            // The default `Accept` media type is plain text. This is inclusive enough
            // for structured and unstructured text.
            accept: MediaType::PlainText,
            custom_entries: HashMap::default(),
        }
    }
}

impl Headers {
    /// Expects one header line and parses it, updating the header structure or returning an
    /// error if the header is invalid.
    ///
    /// # Errors
    /// `UnsupportedHeader` is returned when the parsed header line is not of interest
    /// to us or when it is unrecognizable.
    /// `InvalidHeader` is returned when the parsed header is formatted incorrectly or suggests
    /// that the client is using HTTP features that we do not support in this implementation,
    /// which invalidates the request.
    ///
    /// # Examples
    ///
    /// ```
    /// use dbs_uhttp::Headers;
    ///
    /// let mut request_header = Headers::default();
    /// assert!(request_header.parse_header_line(b"Content-Length: 24").is_ok());
    /// assert!(request_header.parse_header_line(b"Content-Length: 24: 2").is_err());
    /// ```
    pub fn parse_header_line(&mut self, header_line: &[u8]) -> Result<(), RequestError> {
        // Headers must be ASCII, so also UTF-8 valid.
        match std::str::from_utf8(header_line) {
            Ok(headers_str) => {
                let entry = headers_str.splitn(2, ':').collect::<Vec<&str>>();
                if entry.len() != 2 {
                    return Err(RequestError::HeaderError(HttpHeaderError::InvalidFormat(
                        entry[0].to_string(),
                    )));
                }
                if let Ok(head) = Header::try_from(entry[0].as_bytes()) {
                    match head {
                        Header::ContentLength => match entry[1].trim().parse::<u32>() {
                            Ok(content_length) => {
                                self.content_length = content_length;
                                Ok(())
                            }
                            Err(_) => {
                                Err(RequestError::HeaderError(HttpHeaderError::InvalidValue(
                                    entry[0].to_string(),
                                    entry[1].to_string(),
                                )))
                            }
                        },
                        Header::ContentType => {
                            match MediaType::try_from(entry[1].trim().as_bytes()) {
                                Ok(_) => Ok(()),
                                Err(_) => Err(RequestError::HeaderError(
                                    HttpHeaderError::UnsupportedValue(
                                        entry[0].to_string(),
                                        entry[1].to_string(),
                                    ),
                                )),
                            }
                        }
                        Header::Accept => match MediaType::try_from(entry[1].trim().as_bytes()) {
                            Ok(accept_type) => {
                                self.accept = accept_type;
                                Ok(())
                            }
                            Err(_) => Err(RequestError::HeaderError(
                                HttpHeaderError::UnsupportedValue(
                                    entry[0].to_string(),
                                    entry[1].to_string(),
                                ),
                            )),
                        },
                        Header::TransferEncoding => match entry[1].trim() {
                            "chunked" => {
                                self.chunked = true;
                                Ok(())
                            }
                            "identity" => Ok(()),
                            _ => Err(RequestError::HeaderError(
                                HttpHeaderError::UnsupportedValue(
                                    entry[0].to_string(),
                                    entry[1].to_string(),
                                ),
                            )),
                        },
                        Header::Expect => match entry[1].trim() {
                            "100-continue" => {
                                self.expect = true;
                                Ok(())
                            }
                            _ => Err(RequestError::HeaderError(
                                HttpHeaderError::UnsupportedValue(
                                    entry[0].to_string(),
                                    entry[1].to_string(),
                                ),
                            )),
                        },
                        Header::Server => Ok(()),
                        Header::AcceptEncoding => Encoding::try_from(entry[1].trim().as_bytes()),
                    }
                } else {
                    self.insert_custom_header(
                        entry[0].trim().to_string(),
                        entry[1].trim().to_string(),
                    )?;
                    Ok(())
                }
            }
            Err(utf8_err) => Err(RequestError::HeaderError(
                HttpHeaderError::InvalidUtf8String(utf8_err),
            )),
        }
    }

    /// Returns the content length of the body.
    pub fn content_length(&self) -> u32 {
        self.content_length
    }

    /// Returns `true` if the transfer encoding is chunked.
    #[allow(unused)]
    pub fn chunked(&self) -> bool {
        self.chunked
    }

    /// Returns `true` if the client is expecting the code 100.
    #[allow(unused)]
    pub fn expect(&self) -> bool {
        self.expect
    }

    /// Returns the `Accept` header `MediaType`.
    pub fn accept(&self) -> MediaType {
        self.accept
    }

    /// Parses a byte slice into a Headers structure for a HTTP request.
    ///
    /// The byte slice is expected to have the following format: </br>
    ///     * Request Header Lines "<header_line> CRLF"- Optional </br>
    /// There can be any number of request headers, including none, followed by
    /// an extra sequence of Carriage Return and Line Feed.
    /// All header fields are parsed. However, only the ones present in the
    /// [`Headers`](struct.Headers.html) struct are relevant to us and stored
    /// for future use.
    ///
    /// # Errors
    /// The function returns `InvalidHeader` when parsing the byte stream fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use dbs_uhttp::Headers;
    ///
    /// let request_headers = Headers::try_from(b"Content-Length: 55\r\n\r\n");
    /// ```
    pub fn try_from(bytes: &[u8]) -> Result<Headers, RequestError> {
        // Headers must be ASCII, so also UTF-8 valid.
        if let Ok(text) = std::str::from_utf8(bytes) {
            let mut headers = Self::default();

            let header_lines = text.split("\r\n");
            for header_line in header_lines {
                if header_line.is_empty() {
                    break;
                }
                match headers.parse_header_line(header_line.as_bytes()) {
                    Ok(_)
                    | Err(RequestError::HeaderError(HttpHeaderError::UnsupportedValue(_, _))) => {
                        continue
                    }
                    Err(e) => return Err(e),
                };
            }
            return Ok(headers);
        }
        Err(RequestError::InvalidRequest)
    }

    /// Accept header setter.
    pub fn set_accept(&mut self, media_type: MediaType) {
        self.accept = media_type;
    }

    /// Insert a new custom header and value pair into the `HashMap`.
    pub fn insert_custom_header(&mut self, key: String, value: String) -> Result<(), RequestError> {
        self.custom_entries.insert(key, value);
        Ok(())
    }

    /// Returns the custom header `HashMap`.
    pub fn custom_entries(&self) -> &HashMap<String, String> {
        &self.custom_entries
    }
}

/// Wrapper over supported AcceptEncoding.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Encoding {}

impl Encoding {
    /// Parses a byte slice and checks if identity encoding is invalidated. Encoding
    /// must be ASCII, so also UTF-8 valid.
    ///
    /// # Errors
    /// `InvalidRequest` is returned when the byte stream is empty.
    ///
    /// `InvalidValue` is returned when the identity encoding is invalidated.
    ///
    /// `InvalidUtf8String` is returned when the byte stream contains invalid characters.
    ///
    /// # Examples
    ///
    /// ```
    /// use dbs_uhttp::Encoding;
    ///
    /// assert!(Encoding::try_from(b"deflate").is_ok());
    /// assert!(Encoding::try_from(b"identity;q=0").is_err());
    /// ```
    pub fn try_from(bytes: &[u8]) -> Result<(), RequestError> {
        if bytes.is_empty() {
            return Err(RequestError::InvalidRequest);
        }
        match std::str::from_utf8(bytes) {
            Ok(headers_str) => {
                let entry = headers_str.split(',').collect::<Vec<&str>>();

                for encoding in entry {
                    match encoding.trim() {
                        "identity;q=0" => {
                            Err(RequestError::HeaderError(HttpHeaderError::InvalidValue(
                                "Accept-Encoding".to_string(),
                                encoding.to_string(),
                            )))
                        }
                        "*;q=0" if !headers_str.contains("identity") => {
                            Err(RequestError::HeaderError(HttpHeaderError::InvalidValue(
                                "Accept-Encoding".to_string(),
                                encoding.to_string(),
                            )))
                        }
                        _ => Ok(()),
                    }?;
                }
                Ok(())
            }
            Err(utf8_err) => Err(RequestError::HeaderError(
                HttpHeaderError::InvalidUtf8String(utf8_err),
            )),
        }
    }
}

/// Wrapper over supported Media Types.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MediaType {
    /// Media Type: "text/plain".
    PlainText,
    /// Media Type: "application/json".
    ApplicationJson,
}

impl Default for MediaType {
    /// Default value for MediaType is application/json
    fn default() -> Self {
        Self::ApplicationJson
    }
}

impl MediaType {
    /// Parses a byte slice into a MediaType structure for a HTTP request. MediaType
    /// must be ASCII, so also UTF-8 valid.
    ///
    /// # Errors
    /// The function returns `InvalidRequest` when parsing the byte stream fails or
    /// unsupported MediaType found.
    ///
    /// # Examples
    ///
    /// ```
    /// use dbs_uhttp::MediaType;
    ///
    /// assert!(MediaType::try_from(b"application/json").is_ok());
    /// assert!(MediaType::try_from(b"application/json2").is_err());
    /// ```
    pub fn try_from(bytes: &[u8]) -> Result<Self, RequestError> {
        if bytes.is_empty() {
            return Err(RequestError::InvalidRequest);
        }
        let utf8_slice =
            String::from_utf8(bytes.to_vec()).map_err(|_| RequestError::InvalidRequest)?;
        match utf8_slice.as_str().trim() {
            "text/plain" => Ok(Self::PlainText),
            "application/json" => Ok(Self::ApplicationJson),
            _ => Err(RequestError::InvalidRequest),
        }
    }

    /// Returns a static string representation of the object.
    ///
    /// # Examples
    ///
    /// ```
    /// use dbs_uhttp::MediaType;
    ///
    /// let media_type = MediaType::ApplicationJson;
    /// assert_eq!(media_type.as_str(), "application/json");
    /// ```
    pub fn as_str(self) -> &'static str {
        match self {
            Self::PlainText => "text/plain",
            Self::ApplicationJson => "application/json",
        }
    }
}

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

    impl Headers {
        pub fn new(content_length: u32, expect: bool, chunked: bool) -> Self {
            Self {
                content_length,
                expect,
                chunked,
                accept: MediaType::PlainText,
                custom_entries: HashMap::default(),
            }
        }
    }

    #[test]
    fn test_default() {
        let headers = Headers::default();
        assert_eq!(headers.content_length(), 0);
        assert!(!headers.chunked());
        assert!(!headers.expect());
        assert_eq!(headers.accept(), MediaType::PlainText);
        assert_eq!(headers.custom_entries(), &HashMap::default());
    }

    #[test]
    fn test_try_from_media() {
        assert_eq!(
            MediaType::try_from(b"application/json").unwrap(),
            MediaType::ApplicationJson
        );

        assert_eq!(
            MediaType::try_from(b"text/plain").unwrap(),
            MediaType::PlainText
        );

        assert_eq!(
            MediaType::try_from(b"").unwrap_err(),
            RequestError::InvalidRequest
        );

        assert_eq!(
            MediaType::try_from(b"application/json-patch").unwrap_err(),
            RequestError::InvalidRequest
        );
    }

    #[test]
    fn test_media_as_str() {
        let media_type = MediaType::ApplicationJson;
        assert_eq!(media_type.as_str(), "application/json");

        let media_type = MediaType::PlainText;
        assert_eq!(media_type.as_str(), "text/plain");
    }

    #[test]
    fn test_try_from_encoding() {
        assert_eq!(
            Encoding::try_from(b"").unwrap_err(),
            RequestError::InvalidRequest
        );

        assert_eq!(
            Encoding::try_from(b"identity;q=0").unwrap_err(),
            RequestError::HeaderError(HttpHeaderError::InvalidValue(
                "Accept-Encoding".to_string(),
                "identity;q=0".to_string()
            ))
        );

        assert!(Encoding::try_from(b"identity;q").is_ok());

        assert_eq!(
            Encoding::try_from(b"*;q=0").unwrap_err(),
            RequestError::HeaderError(HttpHeaderError::InvalidValue(
                "Accept-Encoding".to_string(),
                "*;q=0".to_string()
            ))
        );

        let bytes: [u8; 10] = [130, 140, 150, 130, 140, 150, 130, 140, 150, 160];
        assert!(Encoding::try_from(&bytes[..]).is_err());

        assert!(Encoding::try_from(b"identity;q=1").is_ok());
        assert!(Encoding::try_from(b"identity;q=0.1").is_ok());
        assert!(Encoding::try_from(b"deflate, identity, *;q=0").is_ok());
        assert!(Encoding::try_from(b"br").is_ok());
        assert!(Encoding::try_from(b"compress").is_ok());
        assert!(Encoding::try_from(b"gzip").is_ok());
    }

    #[test]
    fn test_try_from_headers() {
        // Valid headers.
        let headers =  Headers::try_from(
            b"Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT\r\nAccept: application/json\r\nContent-Length: 55\r\n\r\n"
        )
            .unwrap();
        assert_eq!(headers.content_length, 55);
        assert_eq!(headers.accept, MediaType::ApplicationJson);
        assert_eq!(
            headers.custom_entries().get("Last-Modified").unwrap(),
            "Tue, 15 Nov 1994 12:45:26 GMT"
        );
        assert_eq!(headers.custom_entries().len(), 1);

        // Valid headers. (${HEADER_NAME} : WHITESPACE ${HEADER_VALUE})
        // Any number of whitespace characters should be accepted including zero.
        let headers =  Headers::try_from(
            b"Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT\r\nAccept:text/plain\r\nContent-Length:   49\r\n\r\n"
        )
            .unwrap();
        assert_eq!(headers.content_length, 49);
        assert_eq!(headers.accept, MediaType::PlainText);

        // Valid headers.
        let headers = Headers::try_from(
            b"Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT\r\nContent-Length: 29\r\n\r\n",
        )
        .unwrap();
        assert_eq!(headers.content_length, 29);

        // Custom headers only.
        let headers = Headers::try_from(
            b"Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT\r\nfoo: bar\r\nbar: 15\r\n\r\n",
        )
        .unwrap();
        let custom_entries = headers.custom_entries();
        assert_eq!(custom_entries.get("foo").unwrap(), "bar");
        assert_eq!(custom_entries.get("bar").unwrap(), "15");
        assert_eq!(custom_entries.len(), 3);

        // Valid headers, invalid value.
        assert_eq!(
            Headers::try_from(
                b"Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT\r\nContent-Length: -55\r\n\r\n"
            )
            .unwrap_err(),
            RequestError::HeaderError(HttpHeaderError::InvalidValue(
                "Content-Length".to_string(),
                " -55".to_string()
            ))
        );

        let bytes: [u8; 10] = [130, 140, 150, 130, 140, 150, 130, 140, 150, 160];
        // Invalid headers.
        assert!(Headers::try_from(&bytes[..]).is_err());
    }

    #[test]
    fn test_parse_header_line() {
        let mut header = Headers::default();

        // Invalid header syntax.
        assert_eq!(
            header.parse_header_line(b"Expect"),
            Err(RequestError::HeaderError(HttpHeaderError::InvalidFormat(
                "Expect".to_string()
            )))
        );

        // Invalid content length.
        assert_eq!(
            header.parse_header_line(b"Content-Length: five"),
            Err(RequestError::HeaderError(HttpHeaderError::InvalidValue(
                "Content-Length".to_string(),
                " five".to_string()
            )))
        );

        // Invalid transfer encoding.
        assert_eq!(
            header.parse_header_line(b"Transfer-Encoding: gzip"),
            Err(RequestError::HeaderError(
                HttpHeaderError::UnsupportedValue(
                    "Transfer-Encoding".to_string(),
                    " gzip".to_string()
                )
            ))
        );

        // Invalid expect.
        assert_eq!(
            header
                .parse_header_line(b"Expect: 102-processing")
                .unwrap_err(),
            RequestError::HeaderError(HttpHeaderError::UnsupportedValue(
                "Expect".to_string(),
                " 102-processing".to_string()
            ))
        );

        // Unsupported media type.
        assert_eq!(
            header
                .parse_header_line(b"Content-Type: application/json-patch")
                .unwrap_err(),
            RequestError::HeaderError(HttpHeaderError::UnsupportedValue(
                "Content-Type".to_string(),
                " application/json-patch".to_string()
            ))
        );

        // Invalid input format.
        let input: [u8; 10] = [130, 140, 150, 130, 140, 150, 130, 140, 150, 160];
        assert_eq!(
            header.parse_header_line(&input[..]).unwrap_err(),
            RequestError::HeaderError(HttpHeaderError::InvalidUtf8String(
                String::from_utf8(input.to_vec()).unwrap_err().utf8_error()
            ))
        );

        // Test valid transfer encoding.
        assert!(header
            .parse_header_line(b"Transfer-Encoding: chunked")
            .is_ok());
        assert!(header.chunked());

        // Test valid expect.
        assert!(header.parse_header_line(b"Expect: 100-continue").is_ok());
        assert!(header.expect());

        // Test valid media type.
        assert!(header
            .parse_header_line(b"Content-Type: application/json")
            .is_ok());

        // Test valid accept media type.
        assert!(header
            .parse_header_line(b"Accept: application/json")
            .is_ok());
        assert_eq!(header.accept, MediaType::ApplicationJson);
        assert!(header.parse_header_line(b"Accept: text/plain").is_ok());
        assert_eq!(header.accept, MediaType::PlainText);

        // Test invalid accept media type.
        assert!(header
            .parse_header_line(b"Accept: application/json-patch")
            .is_err());

        // Invalid content length.
        assert_eq!(
            header.parse_header_line(b"Content-Length: -1"),
            Err(RequestError::HeaderError(HttpHeaderError::InvalidValue(
                "Content-Length".to_string(),
                " -1".to_string()
            )))
        );

        assert!(header
            .parse_header_line(b"Accept-Encoding: deflate")
            .is_ok());
        assert_eq!(
            header.parse_header_line(b"Accept-Encoding: compress, identity;q=0"),
            Err(RequestError::HeaderError(HttpHeaderError::InvalidValue(
                "Accept-Encoding".to_string(),
                " identity;q=0".to_string()
            )))
        );

        // Test custom header.
        assert_eq!(header.custom_entries().len(), 0);
        assert!(header.parse_header_line(b"Custom-Header: foo").is_ok());
        assert_eq!(
            header.custom_entries().get("Custom-Header").unwrap(),
            &"foo".to_string()
        );
        assert_eq!(header.custom_entries().len(), 1);
    }

    #[test]
    fn test_parse_header_whitespace() {
        let mut header = Headers::default();
        // Test that any number of whitespace characters are accepted before the header value.
        // For Content-Length
        assert!(header.parse_header_line(b"Content-Length:24").is_ok());
        assert!(header.parse_header_line(b"Content-Length:   24").is_ok());

        // For ContentType
        assert!(header
            .parse_header_line(b"Content-Type:application/json")
            .is_ok());
        assert!(header
            .parse_header_line(b"Content-Type:    application/json")
            .is_ok());

        // For Accept
        assert!(header.parse_header_line(b"Accept:application/json").is_ok());
        assert!(header
            .parse_header_line(b"Accept:  application/json")
            .is_ok());

        // For Transfer-Encoding
        assert!(header
            .parse_header_line(b"Transfer-Encoding:chunked")
            .is_ok());
        assert!(header.chunked());
        assert!(header
            .parse_header_line(b"Transfer-Encoding:    chunked")
            .is_ok());
        assert!(header.chunked());

        // For Server
        assert!(header.parse_header_line(b"Server:xxx.yyy.zzz").is_ok());
        assert!(header.parse_header_line(b"Server:   xxx.yyy.zzz").is_ok());

        // For Expect
        assert!(header.parse_header_line(b"Expect:100-continue").is_ok());
        assert!(header.parse_header_line(b"Expect:    100-continue").is_ok());

        // Test that custom headers' names and values are trimmed before being stored
        // inside the HashMap.
        assert!(header.parse_header_line(b"Foo:bar").is_ok());
        assert_eq!(header.custom_entries().get("Foo").unwrap(), "bar");
        assert!(header.parse_header_line(b"  Bar  :  foo  ").is_ok());
        assert_eq!(header.custom_entries().get("Bar").unwrap(), "foo");
    }

    #[test]
    fn test_header_try_from() {
        // Bad header.
        assert_eq!(
            Header::try_from(b"Encoding").unwrap_err(),
            RequestError::HeaderError(HttpHeaderError::UnsupportedName("encoding".to_string()))
        );

        // Invalid encoding.
        let input: [u8; 10] = [130, 140, 150, 130, 140, 150, 130, 140, 150, 160];
        assert_eq!(
            Header::try_from(&input[..]).unwrap_err(),
            RequestError::InvalidRequest
        );

        // Test valid headers.
        let header = Header::try_from(b"Expect").unwrap();
        assert_eq!(header.raw(), b"Expect");

        let header = Header::try_from(b"Transfer-Encoding").unwrap();
        assert_eq!(header.raw(), b"Transfer-Encoding");

        let header = Header::try_from(b"content-length").unwrap();
        assert_eq!(header.raw(), b"Content-Length");

        let header = Header::try_from(b"Accept").unwrap();
        assert_eq!(header.raw(), b"Accept");
    }

    #[test]
    fn test_set_accept() {
        let mut headers = Headers::default();
        assert_eq!(headers.accept(), MediaType::PlainText);

        headers.set_accept(MediaType::ApplicationJson);
        assert_eq!(headers.accept(), MediaType::ApplicationJson);
    }
}