hyperx/header/common/
last_event_id.rs

1use std::fmt::{self, Display};
2use header::{self, Header, RawLike};
3
4/// `Last-Event-ID` header, defined in
5/// [RFC3864](https://html.spec.whatwg.org/multipage/references.html#refsRFC3864)
6///
7/// The `Last-Event-ID` header contains information about
8/// the last event in an http interaction so that it's easier to
9/// track of event state. This is helpful when working
10/// with [Server-Sent-Events](http://www.html5rocks.com/en/tutorials/eventsource/basics/). If the connection were to be dropped, for example, it'd
11/// be useful to let the server know what the last event you
12/// received was.
13///
14/// The spec is a String with the id of the last event, it can be
15/// an empty string which acts a sort of "reset".
16///
17/// # Example
18/// ```
19/// # extern crate http;
20/// use hyperx::header::LastEventId;
21///
22/// let mut headers = http::HeaderMap::new();
23/// headers.insert(
24///     "last-event-id",
25///     LastEventId("1".to_owned()).to_string().parse().unwrap()
26/// );
27/// ```
28#[derive(Clone, Debug, PartialEq)]
29pub struct LastEventId(pub String);
30
31impl Header for LastEventId {
32    #[inline]
33    fn header_name() -> &'static str {
34        static NAME: &'static str = "Last-Event-ID";
35        NAME
36    }
37
38    #[inline]
39    fn parse_header<'a, T>(raw: &'a T) -> ::Result<Self>
40    where T: RawLike<'a>
41    {
42        match raw.one() {
43            Some(line) if line.is_empty() => Ok(LastEventId("".to_owned())),
44            Some(line) => header::parsing::from_raw_str(line).map(LastEventId),
45            None => Err(::Error::Header),
46        }
47    }
48
49    #[inline]
50    fn fmt_header(&self, f: &mut header::Formatter) -> fmt::Result {
51        f.fmt_line(self)
52    }
53}
54
55impl Display for LastEventId {
56    #[inline]
57    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
58        Display::fmt(&self.0, f)
59    }
60}
61
62__hyper__deref!(LastEventId => String);
63
64__hyper__tm!(LastEventId, tests {
65    // Initial state
66    test_header!(test1, vec![b""]);
67    // Own testcase
68    test_header!(test2, vec![b"1"], Some(LastEventId("1".to_owned())));
69});