Skip to main content

zulip_api/
visibility_policy.rs

1use serde_repr::{Deserialize_repr, Serialize_repr};
2
3/// Represents the Zulip [visibility policy settings](https://zulip.com/api/update-user-topic#parameter-visibility_policy).
4#[repr(u64)]
5#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize_repr, Serialize_repr)]
6pub enum VisibilityPolicy {
7    /// No visibility policy
8    None = 0,
9    /// Topic is muted in the channel.
10    Muted = 1,
11    /// Topic is unmuted in the channel.
12    Unmuted = 2,
13    /// Follows the topic.
14    Followed = 3,
15}
16
17impl VisibilityPolicy {
18    /// Represents the string value of the `None` policy.
19    pub const NONE: &str = "none";
20    /// Represents the string value of the `Muted` policy.
21    pub const MUTED: &str = "muted";
22    /// Represents the string value of the `Unmuted` policy.
23    pub const UNMUTED: &str = "unmuted";
24    /// Represents the integer value of the `Followed` policy.
25    pub const FOLLOWED: &str = "followed";
26
27    /// Creates a new [VisibilityPolicy].
28    pub const fn new() -> Self {
29        Self::None
30    }
31
32    /// Converts the [VisibilityPolicy] to a [`u64`].
33    pub const fn to_u64(self) -> u64 {
34        self as u64
35    }
36
37    /// Gets the [VisibilityPolicy] string representation.
38    pub const fn as_str(&self) -> &'static str {
39        match self {
40            Self::None => Self::NONE,
41            Self::Muted => Self::MUTED,
42            Self::Unmuted => Self::UNMUTED,
43            Self::Followed => Self::FOLLOWED,
44        }
45    }
46}
47
48impl Default for VisibilityPolicy {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54impl From<VisibilityPolicy> for u64 {
55    fn from(val: VisibilityPolicy) -> Self {
56        val.to_u64()
57    }
58}
59
60impl From<VisibilityPolicy> for &'static str {
61    fn from(val: VisibilityPolicy) -> Self {
62        val.as_str()
63    }
64}
65
66impl From<VisibilityPolicy> for String {
67    fn from(val: VisibilityPolicy) -> Self {
68        val.as_str().to_string()
69    }
70}
71
72impl std::fmt::Display for VisibilityPolicy {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        write!(f, "{}", self.as_str())
75    }
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81
82    #[test]
83    fn test_visibility_policy() {
84        [
85            VisibilityPolicy::None,
86            VisibilityPolicy::Muted,
87            VisibilityPolicy::Unmuted,
88            VisibilityPolicy::Followed,
89        ]
90        .into_iter()
91        .for_each(|vp| {
92            let vp_json = format!("{}", vp.to_u64());
93
94            assert_eq!(serde_json::to_string(&vp).unwrap(), vp_json);
95            assert_eq!(
96                serde_json::from_str::<VisibilityPolicy>(&vp_json).unwrap(),
97                vp
98            );
99        });
100    }
101}