http_types_2/other/
expect.rs

1use crate::headers::{HeaderName, HeaderValue, Headers, EXPECT};
2use crate::{ensure_eq_status, headers::Header};
3
4use std::fmt::Debug;
5
6/// HTTP `Expect` header
7///
8/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Expect)
9///
10/// # Specifications
11///
12/// - [RFC 7231, section 5.1.1: Expect](https://tools.ietf.org/html/rfc7231#section-5.1.1)
13///
14/// # Examples
15///
16/// ```
17/// # fn main() -> http_types::Result<()> {
18/// #
19/// use http_types::Response;
20/// use http_types::other::Expect;
21///
22/// let expect = Expect::new();
23///
24/// let mut res = Response::new(200);
25/// res.insert_header(&expect, &expect);
26///
27/// let expect = Expect::from_headers(res)?.unwrap();
28/// assert_eq!(expect, Expect::new());
29/// #
30/// # Ok(()) }
31/// ```
32#[derive(Debug, Ord, PartialOrd, Eq, PartialEq)]
33pub struct Expect {
34    _priv: (),
35}
36
37impl Expect {
38    /// Create a new instance of `Expect`.
39    pub fn new() -> Self {
40        Self { _priv: () }
41    }
42
43    /// Create an instance of `Expect` from a `Headers` instance.
44    pub fn from_headers(headers: impl AsRef<Headers>) -> crate::Result<Option<Self>> {
45        let headers = match headers.as_ref().get(EXPECT) {
46            Some(headers) => headers,
47            None => return Ok(None),
48        };
49
50        // If we successfully parsed the header then there's always at least one
51        // entry. We want the last entry.
52        let header = headers.iter().last().unwrap();
53        ensure_eq_status!(header, "100-continue", 400, "malformed `Expect` header");
54
55        Ok(Some(Self { _priv: () }))
56    }
57}
58
59impl Header for Expect {
60    fn header_name(&self) -> HeaderName {
61        EXPECT
62    }
63    fn header_value(&self) -> HeaderValue {
64        let value = "100-continue";
65        // SAFETY: the internal string is validated to be ASCII.
66        unsafe { HeaderValue::from_bytes_unchecked(value.into()) }
67    }
68}
69
70#[cfg(test)]
71mod test {
72    use super::*;
73    use crate::headers::Headers;
74
75    #[test]
76    fn smoke() -> crate::Result<()> {
77        let expect = Expect::new();
78
79        let mut headers = Headers::new();
80        expect.apply_header(&mut headers);
81
82        let expect = Expect::from_headers(headers)?.unwrap();
83        assert_eq!(expect, Expect::new());
84        Ok(())
85    }
86
87    #[test]
88    fn bad_request_on_parse_error() {
89        let mut headers = Headers::new();
90        headers.insert(EXPECT, "<nori ate the tag. yum.>").unwrap();
91        let err = Expect::from_headers(headers).unwrap_err();
92        assert_eq!(err.status(), 400);
93    }
94}