headers/common/
expect.rs

1use std::fmt;
2
3use http::{HeaderName, HeaderValue};
4
5use crate::util::IterExt;
6use crate::{Error, Header};
7
8/// The `Expect` header.
9///
10/// > The "Expect" header field in a request indicates a certain set of
11/// > behaviors (expectations) that need to be supported by the server in
12/// > order to properly handle this request.  The only such expectation
13/// > defined by this specification is 100-continue.
14/// >
15/// >    Expect  = "100-continue"
16///
17/// # Example
18///
19/// ```
20/// use headers::Expect;
21///
22/// let expect = Expect::CONTINUE;
23/// ```
24#[derive(Clone, PartialEq)]
25pub struct Expect(());
26
27impl Expect {
28    /// "100-continue"
29    pub const CONTINUE: Expect = Expect(());
30}
31
32impl Header for Expect {
33    fn name() -> &'static HeaderName {
34        &::http::header::EXPECT
35    }
36
37    fn decode<'i, I: Iterator<Item = &'i HeaderValue>>(values: &mut I) -> Result<Self, Error> {
38        values
39            .just_one()
40            .and_then(|value| {
41                if value == "100-continue" {
42                    Some(Expect::CONTINUE)
43                } else {
44                    None
45                }
46            })
47            .ok_or_else(Error::invalid)
48    }
49
50    fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
51        values.extend(::std::iter::once(HeaderValue::from_static("100-continue")));
52    }
53}
54
55impl fmt::Debug for Expect {
56    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
57        f.debug_tuple("Expect").field(&"100-continue").finish()
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::super::test_decode;
64    use super::Expect;
65
66    #[test]
67    fn expect_continue() {
68        assert_eq!(
69            test_decode::<Expect>(&["100-continue"]),
70            Some(Expect::CONTINUE),
71        );
72    }
73
74    #[test]
75    fn expectation_failed() {
76        assert_eq!(test_decode::<Expect>(&["sandwich"]), None,);
77    }
78
79    #[test]
80    fn too_many_values() {
81        assert_eq!(
82            test_decode::<Expect>(&["100-continue", "100-continue"]),
83            None,
84        );
85    }
86}