1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
/// Does the heavy lifting of visiting borrowed strings
struct TypedStrVisitor<T>(std::marker::PhantomData<T>);

macro_rules! typed_str {
  ($(#[$meta:meta])* $vis:vis $name:ident) => {
    $(#[$meta])*
    #[derive(Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
    $vis struct $name<'a>(pub(crate) std::borrow::Cow<'a, str>);

    impl<'a> From<std::borrow::Cow<'a, str>> for $name<'a> {
      #[inline]
      fn from(value: std::borrow::Cow<'a, str>) -> Self {
        Self(value)
      }
    }

    impl<'a> From<&'a str> for $name<'a> {
      #[inline]
      fn from(value: &'a str) -> Self {
        Self(std::borrow::Cow::Borrowed(value))
      }
    }

    impl From<String> for $name<'_> {
      #[inline]
      fn from(value: String) -> Self {
        Self(std::borrow::Cow::Owned(value))
      }
    }

    impl<'a> std::fmt::Debug for $name<'a> {
      #[inline]
      fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Debug::fmt(&**self, f)
      }
    }

    impl<'a> std::fmt::Display for $name<'a> {
      #[inline]
      fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&**self, f)
      }
    }

    impl<'a> std::borrow::Borrow<str> for $name<'a> {
      #[inline]
      fn borrow(&self) -> &str {
        &**self
      }
    }

    impl<'a> AsRef<str> for $name<'a> {
      #[inline]
      fn as_ref(&self) -> &str {
        &**self
      }
    }

    impl<'a> std::ops::Deref for $name<'a> {
      type Target = str;

      fn deref(&self) -> &Self::Target {
        &*self.0
      }
    }

    impl<'a> serde::Serialize for $name<'a> {
      #[inline]
      fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
      where
        S: serde::Serializer,
      {
        self.0.serialize(serializer)
      }
    }

    impl<'a, 'de: 'a> serde::de::Visitor<'de> for TypedStrVisitor<$name<'a>> {
      type Value = $name<'a>;

      fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("a string")
      }

      // Borrowed directly from the input string, which has lifetime 'de
      // The input must outlive the resulting Cow.
      fn visit_borrowed_str<E>(self, value: &'de str) -> Result<Self::Value, E>
      where
        E: serde::de::Error,
      {
        Ok($name(std::borrow::Cow::Borrowed(value)))
      }

      // A string that currently only lives in a temporary buffer -- we need a copy
      // (Example: serde is reading from a BufRead)
      fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
      where
        E: serde::de::Error,
      {
        Ok($name(std::borrow::Cow::Owned(value.to_owned())))
      }

      // An optimisation of visit_str for situations where the deserializer has
      // already taken ownership. For example, the string contains escaped characters.
      fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
      where
        E: serde::de::Error,
      {
        Ok($name(std::borrow::Cow::Owned(value)))
      }
    }

    impl<'a, 'de: 'a> serde::Deserialize<'de> for $name<'a> {
      fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
      where
        D: serde::Deserializer<'de>,
      {
        deserializer.deserialize_str(TypedStrVisitor::<$name>(std::marker::PhantomData))
      }
    }
  };
}

typed_str!(
  /// MQTT Topic name.
  pub Topic
);

typed_str!(
  /// Message payload.
  pub Payload
);

typed_str!(
  /// [Home-Assistant device icon][icon].
  ///
  /// [icon]: https://www.home-assistant.io/docs/configuration/customizing-devices/#icon
  pub Icon
);

typed_str!(
  /// [Home-Assistant template][template].
  ///
  /// [template]: https://www.home-assistant.io/docs/configuration/templating/
  pub Template
);

typed_str!(
  /// A device/entity name.
  pub Name
);

typed_str!(
  /// An ID that uniquely identifies this sensor. If two sensors have the same unique ID,
  /// Home Assistant will raise an exception..
  pub UniqueId
);

#[cfg(test)]
mod tests {
  use super::*;
  use assert_matches::assert_matches;
  use serde_test::{assert_tokens, Token};
  use std::borrow::Cow;

  #[test]
  fn topic_ser_de() {
    assert_tokens(&Topic(Cow::Borrowed("test")), &[Token::Str("test")])
  }

  #[test]
  fn topic_ser_de_borrowed() {
    let json = r#""test""#;
    let topic: Topic = serde_json::from_str(json).expect("should parse");
    assert_matches!(topic.0, Cow::Borrowed(_));
  }

  #[test]
  fn topic_ser_de_escaped() {
    let json = r#""\test""#;
    let topic: Topic = serde_json::from_str(json).expect("should parse");
    assert_matches!(topic.0, Cow::Owned(_));
  }
}