hyperx/header/common/
content_length.rs

1use std::fmt;
2
3use header::{Header, RawLike, parsing};
4
5/// `Content-Length` header, defined in
6/// [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2)
7///
8/// When a message does not have a `Transfer-Encoding` header field, a
9/// Content-Length header field can provide the anticipated size, as a
10/// decimal number of octets, for a potential payload body.  For messages
11/// that do include a payload body, the Content-Length field-value
12/// provides the framing information necessary for determining where the
13/// body (and message) ends.  For messages that do not include a payload
14/// body, the Content-Length indicates the size of the selected
15/// representation.
16///
17/// Note that setting this header will *remove* any previously set
18/// `Transfer-Encoding` header, in accordance with
19/// [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2):
20///
21/// > A sender MUST NOT send a Content-Length header field in any message
22/// > that contains a Transfer-Encoding header field.
23///
24/// # ABNF
25///
26/// ```text
27/// Content-Length = 1*DIGIT
28/// ```
29///
30/// # Example values
31///
32/// * `3495`
33///
34/// # Example
35///
36/// ```
37/// # extern crate http;
38/// use hyperx::header::{ContentLength, TypedHeaders};
39///
40/// let mut headers = http::HeaderMap::new();
41/// headers.encode(&ContentLength(1024u64));
42/// ```
43#[derive(Clone, Copy, Debug, PartialEq)]
44pub struct ContentLength(pub u64);
45
46impl Header for ContentLength {
47    #[inline]
48    fn header_name() -> &'static str {
49        static NAME: &'static str = "Content-Length";
50        NAME
51    }
52
53    fn parse_header<'a, T>(raw: &'a T) -> ::Result<ContentLength>
54    where T: RawLike<'a>
55    {
56        // If multiple Content-Length headers were sent, everything can still
57        // be alright if they all contain the same value, and all parse
58        // correctly. If not, then it's an error.
59        raw.iter()
60            .map(parsing::from_raw_str)
61            .fold(None, |prev, x| {
62                match (prev, x) {
63                    (None, x) => Some(x),
64                    (e @ Some(Err(_)), _ ) => e,
65                    (Some(Ok(prev)), Ok(x)) if prev == x => Some(Ok(prev)),
66                    _ => Some(Err(::Error::Header)),
67                }
68            })
69            .unwrap_or(Err(::Error::Header))
70            .map(ContentLength)
71    }
72
73    #[inline]
74    fn fmt_header(&self, f: &mut ::header::Formatter) -> fmt::Result {
75        f.danger_fmt_line_without_newline_replacer(self)
76    }
77}
78
79standard_header!(ContentLength, CONTENT_LENGTH);
80
81impl fmt::Display for ContentLength {
82    #[inline]
83    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84        fmt::Display::fmt(&self.0, f)
85    }
86}
87
88__hyper__deref!(ContentLength => u64);
89
90__hyper__tm!(ContentLength, tests {
91    // Testcase from RFC
92    test_header!(test1, vec![b"3495"], Some(HeaderField(3495)));
93
94    test_header!(test_invalid, vec![b"34v95"], None);
95
96    // Can't use the test_header macro because "5, 5" gets cleaned to "5".
97    #[test]
98    fn test_duplicates() {
99        let r: Raw = vec![b"5".to_vec(), b"5".to_vec()].into();
100        let parsed = HeaderField::parse_header(&r).unwrap();
101        assert_eq!(parsed, HeaderField(5));
102        assert_eq!(format!("{}", parsed), "5");
103    }
104
105    test_header!(test_duplicates_vary, vec![b"5", b"6", b"5"], None);
106});
107
108bench_header!(bench, ContentLength, { vec![b"42349984".to_vec()] });