Skip to main content

zbus/wire/
optional.rs

1use std::{
2    fmt::Display,
3    ops::{Deref, DerefMut},
4};
5
6use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
7
8use crate::wire::{Basic, Type};
9
10/// Type that uses a special value to be used as none.
11///
12/// See [`Optional`] documentation for the rationale for this trait's existence.
13///
14/// # Caveats
15///
16/// Since use of default values as none is typical, this trait is implemented for all types that
17/// implement [`Default`] for convenience. Unfortunately, this means you can not implement this
18/// trait manually for types that implement [`Default`].
19///
20/// Moreoever, since `bool` implements [`Default`], `NoneValue` gets implemented for `bool` as well.
21/// However, this is unsound since its not possible to distinguish between `false` and `None` in
22/// this case. This is why you'll get a panic on trying to serialize or deserialize an
23/// `Optionanl<bool>`.
24pub trait NoneValue {
25    /// The type of the none-equivalent value that [`NoneValue::null_value`] produces.
26    type NoneType;
27
28    /// The none-equivalent value.
29    fn null_value() -> Self::NoneType;
30}
31
32impl<T> NoneValue for T
33where
34    T: Default,
35{
36    type NoneType = Self;
37
38    fn null_value() -> Self {
39        Default::default()
40    }
41}
42
43/// An optional value.
44///
45/// Since D-Bus doesn't have the concept of nullability, it uses a special value (typically the
46/// default value) as the null value. For example [this signal][ts] uses empty strings for null
47/// values. Serde has built-in support for `Option` but unfortunately that doesn't work for us.
48/// Hence the need for this type.
49///
50/// The serialization and deserialization of `Optional` relies on [`NoneValue`] implementation of
51/// the underlying type.
52///
53/// # Examples
54///
55/// ```
56/// use zbus::{Optional, wire::{LE, serialized::Context, to_bytes}};
57///
58/// // `Null` case.
59/// let ctxt = Context::new(LE, 0);
60/// let s = Optional::<&str>::default();
61/// let encoded = to_bytes(ctxt, &s).unwrap();
62/// assert_eq!(encoded.bytes(), &[0, 0, 0, 0, 0]);
63/// let s: Optional<&str> = encoded.deserialize().unwrap().0;
64/// assert_eq!(*s, None);
65///
66/// // `Some` case.
67/// let s = Optional::from(Some("hello"));
68/// let encoded = to_bytes(ctxt, &s).unwrap();
69/// assert_eq!(encoded.len(), 10);
70/// // The first byte is the length of the string in Little-Endian format.
71/// assert_eq!(encoded[0], 5);
72/// let s: Optional<&str> = encoded.deserialize().unwrap().0;
73/// assert_eq!(*s, Some("hello"));
74/// ```
75///
76/// [ts]: https://dbus.freedesktop.org/doc/dbus-specification.html#bus-messages-name-owner-changed
77#[derive(Clone, Debug, PartialEq, Eq, Hash)]
78pub struct Optional<T>(Option<T>);
79
80impl<T> Basic for Optional<T>
81where
82    T: Basic,
83{
84    const SIGNATURE_CHAR: char = T::SIGNATURE_CHAR;
85    const SIGNATURE_STR: &'static str = T::SIGNATURE_STR;
86}
87
88impl<T> Type for Optional<T>
89where
90    T: Type,
91{
92    const SIGNATURE: &'static crate::Signature = T::SIGNATURE;
93}
94
95impl<T> Serialize for Optional<T>
96where
97    T: Type + NoneValue + Serialize,
98    <T as NoneValue>::NoneType: Serialize,
99{
100    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
101    where
102        S: Serializer,
103    {
104        if T::SIGNATURE == bool::SIGNATURE {
105            panic!("`Optional<bool>` type is not supported");
106        }
107
108        match &self.0 {
109            Some(value) => value.serialize(serializer),
110            None => T::null_value().serialize(serializer),
111        }
112    }
113}
114
115impl<'de, T, E> Deserialize<'de> for Optional<T>
116where
117    T: Type + NoneValue + Deserialize<'de>,
118    <T as NoneValue>::NoneType: Deserialize<'de> + TryInto<T, Error = E> + PartialEq,
119    E: Display,
120{
121    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
122    where
123        D: Deserializer<'de>,
124    {
125        if T::SIGNATURE == bool::SIGNATURE {
126            panic!("`Optional<bool>` type is not supported");
127        }
128
129        let value = <<T as NoneValue>::NoneType>::deserialize(deserializer)?;
130        if value == T::null_value() {
131            Ok(Optional(None))
132        } else {
133            Ok(Optional(Some(value.try_into().map_err(de::Error::custom)?)))
134        }
135    }
136}
137
138impl<T> From<Option<T>> for Optional<T> {
139    fn from(value: Option<T>) -> Self {
140        Optional(value)
141    }
142}
143
144impl<T> From<Optional<T>> for Option<T> {
145    fn from(value: Optional<T>) -> Self {
146        value.0
147    }
148}
149
150impl<T> Deref for Optional<T> {
151    type Target = Option<T>;
152
153    fn deref(&self) -> &Self::Target {
154        &self.0
155    }
156}
157
158impl<T> DerefMut for Optional<T> {
159    fn deref_mut(&mut self) -> &mut Self::Target {
160        &mut self.0
161    }
162}
163
164impl<T> Default for Optional<T> {
165    fn default() -> Self {
166        Self(None)
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use std::panic::catch_unwind;
173
174    #[test]
175    fn value_conversion_maps_null_sentinel_to_none() {
176        use crate::wire::{Optional, OwnedVariant, Str, Variant};
177
178        let opt = Optional::<String>::try_from(Variant::from("")).unwrap();
179        assert_eq!(*opt, None);
180        let opt = Optional::<String>::try_from(Variant::from("hello")).unwrap();
181        assert_eq!(*opt, Some("hello".to_string()));
182
183        let opt = Optional::<u32>::try_from(Variant::from(0u32)).unwrap();
184        assert_eq!(*opt, None);
185        let opt = Optional::<u32>::try_from(Variant::from(42u32)).unwrap();
186        assert_eq!(*opt, Some(42));
187
188        let owned = OwnedVariant::try_from(Variant::from(Str::from(""))).unwrap();
189        let opt = Optional::<String>::try_from(owned).unwrap();
190        assert_eq!(*opt, None);
191    }
192
193    #[test]
194    fn bool_in_optional() {
195        // Ensure trying to encode/decode `bool` in `Optional` fails.
196        use crate::wire::{LE, Optional, to_bytes};
197
198        let ctxt = crate::wire::serialized::Context::new(LE, 0);
199        let res = catch_unwind(|| to_bytes(ctxt, &Optional::<bool>::default()));
200        assert!(res.is_err());
201
202        let data = crate::wire::serialized::Data::new([0, 0, 0, 0].as_slice(), ctxt);
203        let res = catch_unwind(|| data.deserialize::<Optional<bool>>());
204        assert!(res.is_err());
205    }
206}