Skip to main content

zulip_api/message/
msg_type.rs

1use serde::{Deserialize, Serialize};
2
3use crate::{impl_default, impl_display, Error, Result};
4
5/// Represents a Zulip message type.
6#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
7#[serde(rename_all = "lowercase")]
8pub enum MessageType {
9    /// Represents a channel messsage.
10    Channel,
11    /// Represents a stream message.
12    Stream,
13    /// Represents a direct message.
14    Direct,
15    /// (Deprecated) Alias for a `Direct` message.
16    Private,
17}
18
19impl MessageType {
20    /// Represents the string value of the channel [MessageType].
21    pub const CHANNEL: &str = "channel";
22    /// Represents the string value of the stream [MessageType].
23    pub const STREAM: &str = "stream";
24    /// Represents the string value of the direct [MessageType].
25    pub const DIRECT: &str = "direct";
26    /// Represents the string value of the private [MessageType].
27    pub const PRIVATE: &str = "private";
28
29    /// Creates a new [MessageType].
30    pub const fn new() -> Self {
31        Self::Channel
32    }
33
34    /// Gets the string representation of the [MessageType].
35    pub const fn as_str(&self) -> &'static str {
36        match self {
37            Self::Channel => Self::CHANNEL,
38            Self::Stream => Self::STREAM,
39            Self::Direct => Self::DIRECT,
40            Self::Private => Self::PRIVATE,
41        }
42    }
43
44    /// Attempts to convert a string into a [MessageType].
45    pub fn try_from_str(val: &str) -> Result<Self> {
46        match val.to_lowercase().as_str() {
47            Self::CHANNEL => Ok(Self::Channel),
48            Self::STREAM => Ok(Self::Stream),
49            Self::DIRECT => Ok(Self::Direct),
50            Self::PRIVATE => Ok(Self::Private),
51            s => Err(Error::invalid_field(
52                "message type",
53                s,
54                "channel | stream | direct | private",
55            )),
56        }
57    }
58}
59
60impl_default!(MessageType);
61impl_display!(MessageType);
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66
67    #[test]
68    fn test_message_type() {
69        [
70            MessageType::Channel,
71            MessageType::Stream,
72            MessageType::Direct,
73        ]
74        .into_iter()
75        .zip([r#""channel""#, r#""stream""#, r#""direct""#])
76        .for_each(|(ty, ty_str)| {
77            assert_eq!(serde_json::to_string(&ty).unwrap().as_str(), ty_str);
78            assert_eq!(serde_json::from_str::<MessageType>(ty_str).unwrap(), ty);
79        });
80    }
81}