ruma_client_api/filter/
lazy_load.rs
1use serde::{ser::SerializeStruct as _, Deserialize, Serialize, Serializer};
2
3#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Deserialize)]
8#[serde(from = "LazyLoadJsonRepr")]
9#[allow(clippy::exhaustive_enums)]
10pub enum LazyLoadOptions {
11 #[default]
13 Disabled,
14
15 Enabled {
17 include_redundant_members: bool,
22 },
23}
24
25impl LazyLoadOptions {
26 pub fn is_disabled(&self) -> bool {
28 matches!(self, Self::Disabled)
29 }
30}
31
32impl Serialize for LazyLoadOptions {
33 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
34 where
35 S: Serializer,
36 {
37 let mut state;
38 match *self {
39 Self::Enabled { include_redundant_members: true } => {
40 state = serializer.serialize_struct("LazyLoad", 2)?;
41 state.serialize_field("lazy_load_members", &true)?;
42 state.serialize_field("include_redundant_members", &true)?;
43 }
44 Self::Enabled { .. } => {
45 state = serializer.serialize_struct("LazyLoad", 1)?;
46 state.serialize_field("lazy_load_members", &true)?;
47 }
48 Self::Disabled => {
49 state = serializer.serialize_struct("LazyLoad", 0)?;
50 }
51 }
52 state.end()
53 }
54}
55
56#[derive(Deserialize)]
57struct LazyLoadJsonRepr {
58 lazy_load_members: Option<bool>,
59 include_redundant_members: Option<bool>,
60}
61
62impl From<LazyLoadJsonRepr> for LazyLoadOptions {
63 fn from(opts: LazyLoadJsonRepr) -> Self {
64 if opts.lazy_load_members.unwrap_or(false) {
65 Self::Enabled {
66 include_redundant_members: opts.include_redundant_members.unwrap_or(false),
67 }
68 } else {
69 Self::Disabled
70 }
71 }
72}
73
74#[cfg(test)]
75mod tests {
76 use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
77
78 use super::LazyLoadOptions;
79
80 #[test]
81 fn serialize_disabled() {
82 let lazy_load_options = LazyLoadOptions::Disabled;
83 assert_eq!(to_json_value(lazy_load_options).unwrap(), json!({}));
84 }
85
86 #[test]
87 fn serialize_no_redundant() {
88 let lazy_load_options = LazyLoadOptions::Enabled { include_redundant_members: false };
89 assert_eq!(to_json_value(lazy_load_options).unwrap(), json!({ "lazy_load_members": true }));
90 }
91
92 #[test]
93 fn serialize_with_redundant() {
94 let lazy_load_options = LazyLoadOptions::Enabled { include_redundant_members: true };
95 assert_eq!(
96 to_json_value(lazy_load_options).unwrap(),
97 json!({ "lazy_load_members": true, "include_redundant_members": true })
98 );
99 }
100
101 #[test]
102 fn deserialize_no_lazy_load() {
103 let json = json!({});
104 assert_eq!(from_json_value::<LazyLoadOptions>(json).unwrap(), LazyLoadOptions::Disabled);
105
106 let json = json!({ "include_redundant_members": true });
107 assert_eq!(from_json_value::<LazyLoadOptions>(json).unwrap(), LazyLoadOptions::Disabled);
108 }
109}