dbus_message_parser/message/
types.rs

1use crate::match_rule::MatchRuleError;
2use std::{
3    convert::TryFrom,
4    fmt::{Display, Formatter, Result as FmtResult},
5};
6
7/// An enum representing the [message type].
8///
9/// [message type]: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-types
10#[repr(u8)]
11#[derive(Debug, PartialOrd, PartialEq, Ord, Eq, Copy, Clone)]
12pub enum MessageType {
13    /// The message is a [`METHOD_CALL`].
14    ///
15    /// [`METHOD_CALL`]: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-types-method
16    MethodCall = 1,
17    /// The message is a [`METHOD_RETURN`].
18    ///
19    /// [`METHOD_RETURN`]: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-types-method
20    MethodReturn = 2,
21    /// The message is a [`ERROR`].
22    ///
23    /// [`ERROR`]: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-types-errors
24    Error = 3,
25    /// The message is a [`SIGNAL`].
26    ///
27    /// [`SIGNAL`]: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-types-signal
28    Signal = 4,
29}
30
31impl TryFrom<u8> for MessageType {
32    type Error = u8;
33
34    fn try_from(message_type: u8) -> Result<MessageType, u8> {
35        match message_type {
36            1 => Ok(MessageType::MethodCall),
37            2 => Ok(MessageType::MethodReturn),
38            3 => Ok(MessageType::Error),
39            4 => Ok(MessageType::Signal),
40            message_type => Err(message_type),
41        }
42    }
43}
44
45impl Display for MessageType {
46    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
47        match self {
48            MessageType::MethodCall => write!(f, "method_call"),
49            MessageType::MethodReturn => write!(f, "method_return"),
50            MessageType::Error => write!(f, "error"),
51            MessageType::Signal => write!(f, "signal"),
52        }
53    }
54}
55
56impl TryFrom<&str> for MessageType {
57    type Error = MatchRuleError;
58
59    fn try_from(r#type: &str) -> Result<Self, MatchRuleError> {
60        match r#type {
61            "method_call" => Ok(MessageType::MethodCall),
62            "method_return" => Ok(MessageType::MethodReturn),
63            "error" => Ok(MessageType::Error),
64            "signal" => Ok(MessageType::Signal),
65            _ => Err(MatchRuleError::TypeUnknown),
66        }
67    }
68}