Skip to main content

rama_http_headers/common/
content_length.rs

1use rama_http_types::HeaderValue;
2
3use crate::{Error, HeaderDecode, HeaderEncode, TypedHeader};
4
5/// `Content-Length` header, defined in
6/// [RFC7230](https://datatracker.ietf.org/doc/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](https://datatracker.ietf.org/doc/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 rama_http_headers::ContentLength;
38///
39/// let len = ContentLength(1_000);
40/// ```
41#[derive(Clone, Copy, Debug, PartialEq)]
42pub struct ContentLength(pub u64);
43
44impl TypedHeader for ContentLength {
45    fn name() -> &'static ::rama_http_types::header::HeaderName {
46        &::rama_http_types::header::CONTENT_LENGTH
47    }
48}
49
50impl HeaderDecode for ContentLength {
51    fn decode<'i, I: Iterator<Item = &'i HeaderValue>>(values: &mut I) -> Result<Self, Error> {
52        // If multiple Content-Length headers were sent, everything can still
53        // be alright if they all contain the same value, and all parse
54        // correctly. If not, then it's an error.
55        let mut len = None;
56        for value in values {
57            let parsed = value
58                .to_str()
59                .map_err(|_e| Error::invalid())?
60                .parse::<u64>()
61                .map_err(|_e| Error::invalid())?;
62
63            if let Some(prev) = len {
64                if prev != parsed {
65                    return Err(Error::invalid());
66                }
67            } else {
68                len = Some(parsed);
69            }
70        }
71
72        len.map(ContentLength).ok_or_else(Error::invalid)
73    }
74}
75
76impl HeaderEncode for ContentLength {
77    fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
78        values.extend(::std::iter::once(self.0.into()));
79    }
80}
81
82/*
83__hyper__tm!(ContentLength, tests {
84    // Testcase from RFC
85    test_header!(test1, vec![b"3495"], Some(HeaderField(3495)));
86
87    test_header!(test_invalid, vec![b"34v95"], None);
88
89    // Can't use the test_header macro because "5, 5" gets cleaned to "5".
90    #[test]
91    fn test_duplicates() {
92        let parsed = HeaderField::parse_header(&vec![b"5".to_vec(),
93                                                 b"5".to_vec()].into()).unwrap();
94        assert_eq!(parsed, HeaderField(5));
95        assert_eq!(format!("{}", parsed), "5");
96    }
97
98    test_header!(test_duplicates_vary, vec![b"5", b"6", b"5"], None);
99});
100*/