sparkplug_rs/
node_message_types.rs

1use std::error::Error;
2use std::fmt::{Debug, Display, Formatter};
3use std::str::FromStr;
4
5/// Enum for node-message types.
6///
7/// The string representation for use in MQTT's topic name can produced by [ToString::to_string]
8///
9/// # Examples
10/// ```
11/// # use sparkplug_rs::NodeMessageType;
12/// assert_eq!(NodeMessageType::NBIRTH.to_string(), "NBIRTH".to_string());
13/// ```
14///
15/// For conversion from the MQTT's topic representation use [FromStr::from_str]
16///
17/// # Examples
18/// ```
19/// # use std::str::FromStr;
20/// # use sparkplug_rs::NodeMessageType;
21/// assert_eq!(NodeMessageType::from_str("NBIRTH").unwrap(), NodeMessageType::NBIRTH);
22/// assert!(NodeMessageType::from_str("xyz").is_err());
23/// ```
24#[derive(Debug, Clone, PartialEq)]
25pub enum NodeMessageType {
26    NBIRTH,
27    NDEATH,
28    NDATA,
29    NCMD,
30}
31
32impl ToString for NodeMessageType {
33    fn to_string(&self) -> String {
34        match self {
35            NodeMessageType::NBIRTH => "NBIRTH".to_string(),
36            NodeMessageType::NDEATH => "NDEATH".to_string(),
37            NodeMessageType::NDATA => "NDATA".to_string(),
38            NodeMessageType::NCMD => "NCMD".to_string(),
39        }
40    }
41}
42
43pub struct NodeMessageTypeParseError;
44
45impl Debug for NodeMessageTypeParseError {
46    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
47        Display::fmt(self, f)
48    }
49}
50
51impl Display for NodeMessageTypeParseError {
52    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
53        f.write_str("Unknown NodeMessageType")
54    }
55}
56
57impl Error for NodeMessageTypeParseError {}
58
59impl FromStr for NodeMessageType {
60    type Err = NodeMessageTypeParseError;
61
62    fn from_str(s: &str) -> Result<Self, Self::Err> {
63        match s {
64            "NBIRTH" => Ok(NodeMessageType::NBIRTH),
65            "NDEATH" => Ok(NodeMessageType::NDEATH),
66            "NDATA" => Ok(NodeMessageType::NDATA),
67            "NCMD" => Ok(NodeMessageType::NCMD),
68            _ => Err(NodeMessageTypeParseError),
69        }
70    }
71}