hyper_sync/header/common/content_length.rs
1use std::fmt;
2
3use header::{Header, Raw, 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/// use hyper_sync::header::{Headers, ContentLength};
38///
39/// let mut headers = Headers::new();
40/// headers.set(ContentLength(1024u64));
41/// ```
42#[derive(Clone, Copy, Debug, PartialEq)]
43pub struct ContentLength(pub u64);
44
45impl Header for ContentLength {
46 #[inline]
47 fn header_name() -> &'static str {
48 static NAME: &'static str = "Content-Length";
49 NAME
50 }
51
52 fn parse_header(raw: &Raw) -> ::Result<ContentLength> {
53 // If multiple Content-Length headers were sent, everything can still
54 // be alright if they all contain the same value, and all parse
55 // correctly. If not, then it's an error.
56 raw.iter()
57 .map(parsing::from_raw_str)
58 .fold(None, |prev, x| {
59 match (prev, x) {
60 (None, x) => Some(x),
61 (e @ Some(Err(_)), _ ) => e,
62 (Some(Ok(prev)), Ok(x)) if prev == x => Some(Ok(prev)),
63 _ => Some(Err(::Error::Header)),
64 }
65 })
66 .unwrap_or(Err(::Error::Header))
67 .map(ContentLength)
68 }
69
70 #[inline]
71 fn fmt_header(&self, f: &mut ::header::Formatter) -> fmt::Result {
72 f.danger_fmt_line_without_newline_replacer(self)
73 }
74}
75
76impl fmt::Display for ContentLength {
77 #[inline]
78 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79 fmt::Display::fmt(&self.0, f)
80 }
81}
82
83__hyper__deref!(ContentLength => u64);
84
85__hyper__tm!(ContentLength, tests {
86 // Testcase from RFC
87 test_header!(test1, vec![b"3495"], Some(HeaderField(3495)));
88
89 test_header!(test_invalid, vec![b"34v95"], None);
90
91 // Can't use the test_header macro because "5, 5" gets cleaned to "5".
92 #[test]
93 fn test_duplicates() {
94 let parsed = HeaderField::parse_header(&vec![b"5".to_vec(),
95 b"5".to_vec()].into()).unwrap();
96 assert_eq!(parsed, HeaderField(5));
97 assert_eq!(format!("{}", parsed), "5");
98 }
99
100 test_header!(test_duplicates_vary, vec![b"5", b"6", b"5"], None);
101});
102
103bench_header!(bench, ContentLength, { vec![b"42349984".to_vec()] });