Skip to main content

actix_web/http/header/
content_length.rs

1use std::{convert::Infallible, str};
2
3use derive_more::{Deref, DerefMut};
4
5use crate::{
6    error::ParseError,
7    http::header::{
8        from_one_raw_str, Header, HeaderName, HeaderValue, TryIntoHeaderValue, CONTENT_LENGTH,
9    },
10    HttpMessage,
11};
12
13/// `Content-Length` header, defined in [RFC 9110 §8.6].
14///
15/// The Content-Length
16///
17/// # ABNF
18///
19/// ```plain
20/// Content-Length = 1*DIGIT
21/// ```
22///
23/// # Example Values
24///
25/// - `0`
26/// - `3495`
27///
28/// # Examples
29///
30/// ```
31/// use actix_web::{http::header::ContentLength, HttpResponse};
32///
33/// let res_empty = HttpResponse::Ok()
34///     .insert_header(ContentLength(0));
35///
36/// let res_fake_cl = HttpResponse::Ok()
37///     .insert_header(ContentLength(3_495));
38/// ```
39///
40/// [RFC 9110 §8.6]: https://www.rfc-editor.org/info/rfc9110/#section-8.6
41#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deref, DerefMut)]
42pub struct ContentLength(pub usize);
43
44impl_more::impl_newtype_from_into!(ContentLength [<=>] usize);
45
46impl ContentLength {
47    /// Returns Content-Length value.
48    pub fn into_inner(&self) -> usize {
49        self.0
50    }
51}
52
53impl str::FromStr for ContentLength {
54    type Err = <usize as str::FromStr>::Err;
55
56    #[inline]
57    fn from_str(val: &str) -> Result<Self, Self::Err> {
58        let val = val.trim();
59
60        // decoder prevents this case
61        debug_assert!(!val.starts_with('+'));
62
63        val.parse().map(Self)
64    }
65}
66
67impl TryIntoHeaderValue for ContentLength {
68    type Error = Infallible;
69
70    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
71        Ok(HeaderValue::from(self.0))
72    }
73}
74
75impl Header for ContentLength {
76    fn name() -> HeaderName {
77        CONTENT_LENGTH
78    }
79
80    fn parse<M: HttpMessage>(msg: &M) -> Result<Self, ParseError> {
81        let val = from_one_raw_str(msg.headers().get(Self::name()))?;
82
83        // decoder prevents multiple CL headers
84        debug_assert_eq!(msg.headers().get_all(Self::name()).count(), 1);
85
86        Ok(val)
87    }
88}
89
90impl PartialEq<usize> for ContentLength {
91    fn eq(&self, other: &usize) -> bool {
92        self.0 == *other
93    }
94}
95
96impl PartialEq<ContentLength> for usize {
97    fn eq(&self, other: &ContentLength) -> bool {
98        *self == other.0
99    }
100}
101
102impl PartialOrd<usize> for ContentLength {
103    fn partial_cmp(&self, other: &usize) -> Option<std::cmp::Ordering> {
104        self.0.partial_cmp(other)
105    }
106}
107
108impl PartialOrd<ContentLength> for usize {
109    fn partial_cmp(&self, other: &ContentLength) -> Option<std::cmp::Ordering> {
110        self.partial_cmp(&other.0)
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use std::fmt;
117
118    use super::*;
119    use crate::{test::TestRequest, HttpRequest};
120
121    fn req_from_raw_headers<H: Header, I: IntoIterator<Item = V>, V: AsRef<[u8]>>(
122        header_lines: I,
123    ) -> HttpRequest {
124        header_lines
125            .into_iter()
126            .fold(TestRequest::default(), |req, item| {
127                req.append_header((H::name(), item.as_ref().to_vec()))
128            })
129            .to_http_request()
130    }
131
132    #[track_caller]
133    pub(crate) fn assert_parse_fail<
134        H: Header + fmt::Debug,
135        I: IntoIterator<Item = V>,
136        V: AsRef<[u8]>,
137    >(
138        headers: I,
139    ) {
140        let req = req_from_raw_headers::<H, _, _>(headers);
141        H::parse(&req).unwrap_err();
142    }
143
144    #[track_caller]
145    pub(crate) fn assert_parse_eq<
146        H: Header + fmt::Debug + PartialEq,
147        I: IntoIterator<Item = V>,
148        V: AsRef<[u8]>,
149    >(
150        headers: I,
151        expect: H,
152    ) {
153        let req = req_from_raw_headers::<H, _, _>(headers);
154        assert_eq!(H::parse(&req).unwrap(), expect);
155    }
156
157    #[test]
158    fn missing_header() {
159        assert_parse_fail::<ContentLength, _, _>([""; 0]);
160        assert_parse_fail::<ContentLength, _, _>([""]);
161    }
162
163    #[test]
164    fn bad_header() {
165        assert_parse_fail::<ContentLength, _, _>(["-123"]);
166        assert_parse_fail::<ContentLength, _, _>(["123_456"]);
167        assert_parse_fail::<ContentLength, _, _>(["123.456"]);
168
169        // too large for u64 (2^64, 2^64 + 1)
170        assert_parse_fail::<ContentLength, _, _>(["18446744073709551616"]);
171        assert_parse_fail::<ContentLength, _, _>(["18446744073709551617"]);
172
173        // hex notation
174        assert_parse_fail::<ContentLength, _, _>(["0x123"]);
175
176        // multi-value
177        assert_parse_fail::<ContentLength, _, _>(["0, 123"]);
178    }
179
180    #[test]
181    #[should_panic]
182    fn bad_header_plus() {
183        // prevented by HTTP decoder anyway
184        assert_parse_fail::<ContentLength, _, _>(["+123"]);
185    }
186
187    #[test]
188    #[should_panic]
189    fn bad_multiple_value() {
190        // prevented by HTTP decoder anyway
191        assert_parse_fail::<ContentLength, _, _>(["0", "123"]);
192    }
193
194    #[test]
195    fn good_header() {
196        assert_parse_eq::<ContentLength, _, _>(["0"], ContentLength(0));
197        assert_parse_eq::<ContentLength, _, _>(["1"], ContentLength(1));
198        assert_parse_eq::<ContentLength, _, _>(["123"], ContentLength(123));
199
200        // value that looks like octal notation is not interpreted as such
201        assert_parse_eq::<ContentLength, _, _>(["0123"], ContentLength(123));
202
203        // whitespace variations
204        assert_parse_eq::<ContentLength, _, _>([" 0"], ContentLength(0));
205        assert_parse_eq::<ContentLength, _, _>(["0 "], ContentLength(0));
206        assert_parse_eq::<ContentLength, _, _>([" 0 "], ContentLength(0));
207    }
208
209    #[cfg(target_pointer_width = "64")]
210    #[test]
211    fn good_header_max_usize() {
212        // large value (2^64 - 1)
213        assert_parse_eq::<ContentLength, _, _>(
214            ["18446744073709551615"],
215            ContentLength(18_446_744_073_709_551_615),
216        );
217    }
218
219    #[test]
220    fn equality() {
221        assert!(ContentLength(0) == ContentLength(0));
222        assert!(ContentLength(0) == 0);
223        assert!(0 != ContentLength(123));
224    }
225
226    #[test]
227    fn ordering() {
228        assert!(ContentLength(0) < ContentLength(123));
229        assert!(ContentLength(0) < 123);
230        assert!(0 < ContentLength(123));
231    }
232}