Skip to main content

rama_http_headers/common/
last_event_id.rs

1use crate::util::HeaderValueString;
2use std::{fmt, str::FromStr};
3
4/// `Last-Event-ID` header, defined in
5/// [WhatWG's SSE spec](https://html.spec.whatwg.org/multipage/server-sent-events.html#the-last-event-id-header)
6///
7/// The Last-Event-ID` HTTP request header reports an EventSource object's
8/// last event ID string to the server when the user agent is to reestablish the connection.
9///
10/// The spec is a String with the id of the last event, it can be
11/// an empty string which acts a sort of "reset".
12#[derive(Clone, Debug, PartialEq)]
13pub struct LastEventId(HeaderValueString);
14
15derive_header! {
16    LastEventId(_),
17    name: LAST_EVENT_ID
18}
19
20impl LastEventId {
21    #[inline]
22    /// Return the id as a borrowed string.
23    pub fn as_str(&self) -> &str {
24        self.0.as_str()
25    }
26}
27
28impl AsRef<str> for LastEventId {
29    #[inline]
30    /// Return the id as a borrowed string.
31    fn as_ref(&self) -> &str {
32        self.0.as_str()
33    }
34}
35
36impl LastEventId {
37    /// Create a `LastEventId` with a static string.
38    ///
39    /// # Panic
40    ///
41    /// Panics if the string is not a legal header value.
42    #[must_use]
43    pub fn from_static(s: &'static str) -> Self {
44        Self(HeaderValueString::from_static(s))
45    }
46}
47
48rama_utils::macros::error::static_str_error! {
49    #[doc = "last-event-id is not valid"]
50    pub struct InvalidLastEventId;
51}
52
53impl FromStr for LastEventId {
54    type Err = InvalidLastEventId;
55    fn from_str(src: &str) -> Result<Self, Self::Err> {
56        HeaderValueString::from_str(src)
57            .map(LastEventId)
58            .map_err(|_e| InvalidLastEventId)
59    }
60}
61
62impl fmt::Display for LastEventId {
63    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64        fmt::Display::fmt(&self.0, f)
65    }
66}