zulip-api 0.0.8

Client library for interacting with the Zulip API
Documentation
use serde::{Deserialize, Serialize};

use crate::{impl_default, impl_display, Error, Result};

/// Represents a Zulip message type.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum MessageType {
    /// Represents a channel messsage.
    Channel,
    /// Represents a stream message.
    Stream,
    /// Represents a direct message.
    Direct,
    /// (Deprecated) Alias for a `Direct` message.
    Private,
}

impl MessageType {
    /// Represents the string value of the channel [MessageType].
    pub const CHANNEL: &str = "channel";
    /// Represents the string value of the stream [MessageType].
    pub const STREAM: &str = "stream";
    /// Represents the string value of the direct [MessageType].
    pub const DIRECT: &str = "direct";
    /// Represents the string value of the private [MessageType].
    pub const PRIVATE: &str = "private";

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

    /// Gets the string representation of the [MessageType].
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Channel => Self::CHANNEL,
            Self::Stream => Self::STREAM,
            Self::Direct => Self::DIRECT,
            Self::Private => Self::PRIVATE,
        }
    }

    /// Attempts to convert a string into a [MessageType].
    pub fn try_from_str(val: &str) -> Result<Self> {
        match val.to_lowercase().as_str() {
            Self::CHANNEL => Ok(Self::Channel),
            Self::STREAM => Ok(Self::Stream),
            Self::DIRECT => Ok(Self::Direct),
            Self::PRIVATE => Ok(Self::Private),
            s => Err(Error::invalid_field(
                "message type",
                s,
                "channel | stream | direct | private",
            )),
        }
    }
}

impl_default!(MessageType);
impl_display!(MessageType);

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

    #[test]
    fn test_message_type() {
        [
            MessageType::Channel,
            MessageType::Stream,
            MessageType::Direct,
        ]
        .into_iter()
        .zip([r#""channel""#, r#""stream""#, r#""direct""#])
        .for_each(|(ty, ty_str)| {
            assert_eq!(serde_json::to_string(&ty).unwrap().as_str(), ty_str);
            assert_eq!(serde_json::from_str::<MessageType>(ty_str).unwrap(), ty);
        });
    }
}