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