sparkplug_rs/
topic_namespace.rs

1use std::error::Error;
2use std::fmt::{Debug, Display, Formatter};
3use std::str::FromStr;
4
5/// Enumerator for Sparkplugs™ topic namespace.
6///
7/// The MQTT-Representation can be created with the [ToString::to_string]-method.
8/// ```
9/// # use sparkplug_rs::TopicNamespace;
10/// assert_eq!("spAv1.0".to_string(), TopicNamespace::SPAV1_0.to_string());
11/// assert_eq!("spBv1.0".to_string(), TopicNamespace::SPBV1_0.to_string());
12/// ```
13///
14/// The MQTT-String representation can be parsed with [FromStr::from_str].
15///
16/// # Examples
17/// ```
18/// # use std::str::FromStr;
19/// # use sparkplug_rs::TopicNamespace;
20/// assert_eq!(TopicNamespace::from_str("spAv1.0").unwrap(), TopicNamespace::SPAV1_0);
21/// assert!(TopicNamespace::from_str("xyz").is_err());
22/// ```
23#[derive(Debug, Clone, PartialEq)]
24pub enum TopicNamespace {
25    /// Sparkplug Payload Version 1.0a
26    SPAV1_0,
27    /// Sparkplug Payload Version 1.0b
28    SPBV1_0,
29}
30
31impl ToString for TopicNamespace {
32    fn to_string(&self) -> String {
33        match self {
34            TopicNamespace::SPAV1_0 => "spAv1.0".to_string(),
35            TopicNamespace::SPBV1_0 => "spBv1.0".to_string(),
36        }
37    }
38}
39
40pub struct TopicNamespaceParseError;
41
42impl Debug for TopicNamespaceParseError {
43    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
44        Display::fmt(self, f)
45    }
46}
47
48impl Display for TopicNamespaceParseError {
49    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
50        f.write_str("Error parsing topic's namespace")
51    }
52}
53
54impl Error for TopicNamespaceParseError {}
55
56impl FromStr for TopicNamespace {
57    type Err = TopicNamespaceParseError;
58
59    fn from_str(s: &str) -> Result<Self, Self::Err> {
60        match s {
61            "spAv1.0" => Ok(TopicNamespace::SPAV1_0),
62            "spBv1.0" => Ok(TopicNamespace::SPBV1_0),
63            _ => Err(TopicNamespaceParseError),
64        }
65    }
66}