Skip to main content

freeswitch_types/event/
format.rs

1wire_enum! {
2    /// Event format types supported by FreeSWITCH ESL.
3    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4    pub enum EventFormat {
5        /// Plain text format (default)
6        Plain => "plain",
7        /// JSON format
8        Json => "json",
9        /// XML format
10        Xml => "xml",
11    }
12    error ParseEventFormatError("event format");
13    from_str: ignore_case;
14}
15
16impl EventFormat {
17    /// Determine event format from a Content-Type header value.
18    ///
19    /// Returns `Err` for unrecognized content types to avoid silently
20    /// misparsing events if FreeSWITCH adds a new format.
21    pub fn from_content_type(ct: &str) -> Result<Self, ParseEventFormatError> {
22        match ct {
23            "text/event-json" => Ok(Self::Json),
24            "text/event-xml" => Ok(Self::Xml),
25            "text/event-plain" => Ok(Self::Plain),
26            _ => Err(ParseEventFormatError(ct.to_string())),
27        }
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34
35    #[test]
36    fn test_event_format_from_str() {
37        assert_eq!("plain".parse::<EventFormat>(), Ok(EventFormat::Plain));
38        assert_eq!("json".parse::<EventFormat>(), Ok(EventFormat::Json));
39        assert_eq!("xml".parse::<EventFormat>(), Ok(EventFormat::Xml));
40        assert!("foo"
41            .parse::<EventFormat>()
42            .is_err());
43    }
44
45    #[test]
46    fn test_event_format_from_str_case_insensitive() {
47        assert_eq!("PLAIN".parse::<EventFormat>(), Ok(EventFormat::Plain));
48        assert_eq!("Json".parse::<EventFormat>(), Ok(EventFormat::Json));
49        assert_eq!("XML".parse::<EventFormat>(), Ok(EventFormat::Xml));
50        assert_eq!("Xml".parse::<EventFormat>(), Ok(EventFormat::Xml));
51    }
52
53    #[test]
54    fn test_event_format_from_content_type() {
55        assert_eq!(
56            EventFormat::from_content_type("text/event-json"),
57            Ok(EventFormat::Json)
58        );
59        assert_eq!(
60            EventFormat::from_content_type("text/event-xml"),
61            Ok(EventFormat::Xml)
62        );
63        assert_eq!(
64            EventFormat::from_content_type("text/event-plain"),
65            Ok(EventFormat::Plain)
66        );
67        assert!(EventFormat::from_content_type("unknown").is_err());
68    }
69}