zulip-api 0.0.8

Client library for interacting with the Zulip API
Documentation
use serde_repr::{Deserialize_repr, Serialize_repr};

/// Represents the Zulip [visibility policy settings](https://zulip.com/api/update-user-topic#parameter-visibility_policy).
#[repr(u64)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize_repr, Serialize_repr)]
pub enum VisibilityPolicy {
    /// No visibility policy
    None = 0,
    /// Topic is muted in the channel.
    Muted = 1,
    /// Topic is unmuted in the channel.
    Unmuted = 2,
    /// Follows the topic.
    Followed = 3,
}

impl VisibilityPolicy {
    /// Represents the string value of the `None` policy.
    pub const NONE: &str = "none";
    /// Represents the string value of the `Muted` policy.
    pub const MUTED: &str = "muted";
    /// Represents the string value of the `Unmuted` policy.
    pub const UNMUTED: &str = "unmuted";
    /// Represents the integer value of the `Followed` policy.
    pub const FOLLOWED: &str = "followed";

    /// Creates a new [VisibilityPolicy].
    pub const fn new() -> Self {
        Self::None
    }

    /// Converts the [VisibilityPolicy] to a [`u64`].
    pub const fn to_u64(self) -> u64 {
        self as u64
    }

    /// Gets the [VisibilityPolicy] string representation.
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::None => Self::NONE,
            Self::Muted => Self::MUTED,
            Self::Unmuted => Self::UNMUTED,
            Self::Followed => Self::FOLLOWED,
        }
    }
}

impl Default for VisibilityPolicy {
    fn default() -> Self {
        Self::new()
    }
}

impl From<VisibilityPolicy> for u64 {
    fn from(val: VisibilityPolicy) -> Self {
        val.to_u64()
    }
}

impl From<VisibilityPolicy> for &'static str {
    fn from(val: VisibilityPolicy) -> Self {
        val.as_str()
    }
}

impl From<VisibilityPolicy> for String {
    fn from(val: VisibilityPolicy) -> Self {
        val.as_str().to_string()
    }
}

impl std::fmt::Display for VisibilityPolicy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_visibility_policy() {
        [
            VisibilityPolicy::None,
            VisibilityPolicy::Muted,
            VisibilityPolicy::Unmuted,
            VisibilityPolicy::Followed,
        ]
        .into_iter()
        .for_each(|vp| {
            let vp_json = format!("{}", vp.to_u64());

            assert_eq!(serde_json::to_string(&vp).unwrap(), vp_json);
            assert_eq!(
                serde_json::from_str::<VisibilityPolicy>(&vp_json).unwrap(),
                vp
            );
        });
    }
}