ruma_client_api/filter/
url.rs

1use serde::{
2    de::{Deserialize, Deserializer},
3    ser::{Serialize, Serializer},
4};
5
6/// Options for filtering based on the presence of a URL.
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
8#[allow(clippy::exhaustive_enums)]
9pub enum UrlFilter {
10    /// Includes only events with a url key in their content.
11    EventsWithUrl,
12
13    /// Excludes events with a url key in their content.
14    EventsWithoutUrl,
15}
16
17impl Serialize for UrlFilter {
18    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
19    where
20        S: Serializer,
21    {
22        match *self {
23            Self::EventsWithUrl => serializer.serialize_bool(true),
24            Self::EventsWithoutUrl => serializer.serialize_bool(false),
25        }
26    }
27}
28
29impl<'de> Deserialize<'de> for UrlFilter {
30    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
31    where
32        D: Deserializer<'de>,
33    {
34        Ok(match bool::deserialize(deserializer)? {
35            true => Self::EventsWithUrl,
36            false => Self::EventsWithoutUrl,
37        })
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use ruma_common::canonical_json::assert_to_canonical_json_eq;
44    use serde_json::{from_value as from_json_value, json};
45
46    use super::UrlFilter;
47
48    #[test]
49    fn serialize_filter_events_with_url() {
50        let events_with_url = UrlFilter::EventsWithUrl;
51        assert_to_canonical_json_eq!(events_with_url, json!(true));
52    }
53
54    #[test]
55    fn serialize_filter_events_without_url() {
56        let events_without_url = UrlFilter::EventsWithoutUrl;
57        assert_to_canonical_json_eq!(events_without_url, json!(false));
58    }
59
60    #[test]
61    fn deserialize_filter_events_with_url() {
62        let json = json!(true);
63        assert_eq!(from_json_value::<UrlFilter>(json).unwrap(), UrlFilter::EventsWithUrl);
64    }
65
66    #[test]
67    fn deserialize_filter_events_without_url() {
68        let json = json!(false);
69        assert_eq!(from_json_value::<UrlFilter>(json).unwrap(), UrlFilter::EventsWithoutUrl);
70    }
71}