zbus_names/
error_name.rs

1use crate::{
2    utils::{impl_str_basic, impl_try_from},
3    Error, Result,
4};
5use serde::{de, Deserialize, Serialize};
6use static_assertions::assert_impl_all;
7use std::{
8    borrow::{Borrow, Cow},
9    fmt::{self, Debug, Display, Formatter},
10    ops::Deref,
11    sync::Arc,
12};
13use zvariant::{NoneValue, OwnedValue, Str, Type, Value};
14
15/// String that identifies an [error name][en] on the bus.
16///
17/// Error names have same constraints as error names.
18///
19/// # Examples
20///
21/// ```
22/// use zbus_names::ErrorName;
23///
24/// // Valid error names.
25/// let name = ErrorName::try_from("org.gnome.Error_for_you").unwrap();
26/// assert_eq!(name, "org.gnome.Error_for_you");
27/// let name = ErrorName::try_from("a.very.loooooooooooooooooo_ooooooo_0000o0ng.ErrorName").unwrap();
28/// assert_eq!(name, "a.very.loooooooooooooooooo_ooooooo_0000o0ng.ErrorName");
29///
30/// // Invalid error names
31/// ErrorName::try_from("").unwrap_err();
32/// ErrorName::try_from(":start.with.a.colon").unwrap_err();
33/// ErrorName::try_from("double..dots").unwrap_err();
34/// ErrorName::try_from(".").unwrap_err();
35/// ErrorName::try_from(".start.with.dot").unwrap_err();
36/// ErrorName::try_from("no-dots").unwrap_err();
37/// ErrorName::try_from("1st.element.starts.with.digit").unwrap_err();
38/// ErrorName::try_from("the.2nd.element.starts.with.digit").unwrap_err();
39/// ErrorName::try_from("contains.dashes-in.the.name").unwrap_err();
40/// ```
41///
42/// [en]: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-error
43#[derive(
44    Clone, Debug, Hash, PartialEq, Eq, Serialize, Type, Value, PartialOrd, Ord, OwnedValue,
45)]
46pub struct ErrorName<'name>(Str<'name>);
47
48assert_impl_all!(ErrorName<'_>: Send, Sync, Unpin);
49
50impl_str_basic!(ErrorName<'_>);
51
52impl<'name> ErrorName<'name> {
53    /// This is faster than `Clone::clone` when `self` contains owned data.
54    pub fn as_ref(&self) -> ErrorName<'_> {
55        ErrorName(self.0.as_ref())
56    }
57
58    /// The error name as string.
59    pub fn as_str(&self) -> &str {
60        self.0.as_str()
61    }
62
63    /// Create a new `ErrorName` from the given string.
64    ///
65    /// Since the passed string is not checked for correctness, prefer using the
66    /// `TryFrom<&str>` implementation.
67    pub fn from_str_unchecked(name: &'name str) -> Self {
68        Self(Str::from(name))
69    }
70
71    /// Same as `try_from`, except it takes a `&'static str`.
72    pub fn from_static_str(name: &'static str) -> Result<Self> {
73        validate(name)?;
74        Ok(Self(Str::from_static(name)))
75    }
76
77    /// Same as `from_str_unchecked`, except it takes a `&'static str`.
78    pub const fn from_static_str_unchecked(name: &'static str) -> Self {
79        Self(Str::from_static(name))
80    }
81
82    /// Same as `from_str_unchecked`, except it takes an owned `String`.
83    ///
84    /// Since the passed string is not checked for correctness, prefer using the
85    /// `TryFrom<String>` implementation.
86    pub fn from_string_unchecked(name: String) -> Self {
87        Self(Str::from(name))
88    }
89
90    /// Creates an owned clone of `self`.
91    pub fn to_owned(&self) -> ErrorName<'static> {
92        ErrorName(self.0.to_owned())
93    }
94
95    /// Creates an owned clone of `self`.
96    pub fn into_owned(self) -> ErrorName<'static> {
97        ErrorName(self.0.into_owned())
98    }
99}
100
101impl Deref for ErrorName<'_> {
102    type Target = str;
103
104    fn deref(&self) -> &Self::Target {
105        self.as_str()
106    }
107}
108
109impl Borrow<str> for ErrorName<'_> {
110    fn borrow(&self) -> &str {
111        self.as_str()
112    }
113}
114
115impl Display for ErrorName<'_> {
116    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
117        Display::fmt(&self.as_str(), f)
118    }
119}
120
121impl PartialEq<str> for ErrorName<'_> {
122    fn eq(&self, other: &str) -> bool {
123        self.as_str() == other
124    }
125}
126
127impl PartialEq<&str> for ErrorName<'_> {
128    fn eq(&self, other: &&str) -> bool {
129        self.as_str() == *other
130    }
131}
132
133impl PartialEq<OwnedErrorName> for ErrorName<'_> {
134    fn eq(&self, other: &OwnedErrorName) -> bool {
135        *self == other.0
136    }
137}
138
139impl<'de: 'name, 'name> Deserialize<'de> for ErrorName<'name> {
140    fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
141    where
142        D: serde::Deserializer<'de>,
143    {
144        let name = <Cow<'name, str>>::deserialize(deserializer)?;
145
146        Self::try_from(name).map_err(|e| de::Error::custom(e.to_string()))
147    }
148}
149
150impl_try_from! {
151    ty: ErrorName<'s>,
152    owned_ty: OwnedErrorName,
153    validate_fn: validate,
154    try_from: [&'s str, String, Arc<str>, Cow<'s, str>, Str<'s>],
155}
156
157fn validate(name: &str) -> Result<()> {
158    // Error names follow the same rules as interface names.
159    crate::interface_name::validate_bytes(name.as_bytes()).map_err(|_| {
160        Error::InvalidName(
161            "Invalid error name. See \
162            https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-error",
163        )
164    })
165}
166
167/// This never succeeds but is provided so it's easier to pass `Option::None` values for API
168/// requiring `Option<TryInto<impl BusName>>`, since type inference won't work here.
169impl TryFrom<()> for ErrorName<'_> {
170    type Error = Error;
171
172    fn try_from(_value: ()) -> Result<Self> {
173        unreachable!("Conversion from `()` is not meant to actually work");
174    }
175}
176
177impl<'name> From<&ErrorName<'name>> for ErrorName<'name> {
178    fn from(name: &ErrorName<'name>) -> Self {
179        name.clone()
180    }
181}
182
183impl<'name> From<ErrorName<'name>> for Str<'name> {
184    fn from(value: ErrorName<'name>) -> Self {
185        value.0
186    }
187}
188
189impl<'name> NoneValue for ErrorName<'name> {
190    type NoneType = &'name str;
191
192    fn null_value() -> Self::NoneType {
193        <&str>::default()
194    }
195}
196
197/// Owned sibling of [`ErrorName`].
198#[derive(Clone, Hash, PartialEq, Eq, Serialize, Type, Value, PartialOrd, Ord, OwnedValue)]
199pub struct OwnedErrorName(#[serde(borrow)] ErrorName<'static>);
200
201assert_impl_all!(OwnedErrorName: Send, Sync, Unpin);
202
203impl_str_basic!(OwnedErrorName);
204
205impl OwnedErrorName {
206    /// Convert to the inner `ErrorName`, consuming `self`.
207    pub fn into_inner(self) -> ErrorName<'static> {
208        self.0
209    }
210
211    /// Get a reference to the inner `ErrorName`.
212    pub fn inner(&self) -> &ErrorName<'static> {
213        &self.0
214    }
215}
216
217impl Deref for OwnedErrorName {
218    type Target = ErrorName<'static>;
219
220    fn deref(&self) -> &Self::Target {
221        &self.0
222    }
223}
224
225impl Borrow<str> for OwnedErrorName {
226    fn borrow(&self) -> &str {
227        self.0.as_str()
228    }
229}
230
231impl From<OwnedErrorName> for ErrorName<'_> {
232    fn from(o: OwnedErrorName) -> Self {
233        o.into_inner()
234    }
235}
236
237impl<'unowned, 'owned: 'unowned> From<&'owned OwnedErrorName> for ErrorName<'unowned> {
238    fn from(name: &'owned OwnedErrorName) -> Self {
239        ErrorName::from_str_unchecked(name.as_str())
240    }
241}
242
243impl From<ErrorName<'_>> for OwnedErrorName {
244    fn from(name: ErrorName<'_>) -> Self {
245        OwnedErrorName(name.into_owned())
246    }
247}
248
249impl From<OwnedErrorName> for Str<'_> {
250    fn from(value: OwnedErrorName) -> Self {
251        value.into_inner().0
252    }
253}
254
255impl<'de> Deserialize<'de> for OwnedErrorName {
256    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
257    where
258        D: de::Deserializer<'de>,
259    {
260        String::deserialize(deserializer)
261            .and_then(|n| ErrorName::try_from(n).map_err(|e| de::Error::custom(e.to_string())))
262            .map(Self)
263    }
264}
265
266impl PartialEq<&str> for OwnedErrorName {
267    fn eq(&self, other: &&str) -> bool {
268        self.as_str() == *other
269    }
270}
271
272impl PartialEq<ErrorName<'_>> for OwnedErrorName {
273    fn eq(&self, other: &ErrorName<'_>) -> bool {
274        self.0 == *other
275    }
276}
277
278impl Debug for OwnedErrorName {
279    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
280        f.debug_tuple("OwnedErrorName")
281            .field(&self.as_str())
282            .finish()
283    }
284}
285
286impl Display for OwnedErrorName {
287    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
288        Display::fmt(&ErrorName::from(self), f)
289    }
290}
291
292impl NoneValue for OwnedErrorName {
293    type NoneType = <ErrorName<'static> as NoneValue>::NoneType;
294
295    fn null_value() -> Self::NoneType {
296        ErrorName::null_value()
297    }
298}