Skip to main content

webbluetooth_linux/dbus/
value.rs

1//! The D-Bus type system.
2//!
3//! Every value on the bus is one of these, and every message body is described
4//! by a *signature* — a string of type codes like `a{sv}` (array of string →
5//! variant) or `oa{sa{sv}}` (the reply to `GetManagedObjects`). Marshalling is
6//! signature-directed: the bytes carry no type tags, so the decoder must be
7//! told what it is reading.
8
9use std::collections::HashMap;
10use std::fmt;
11
12/// A D-Bus value.
13#[derive(Debug, Clone, PartialEq)]
14pub enum Value {
15    Byte(u8),
16    Bool(bool),
17    Int16(i16),
18    Uint16(u16),
19    Int32(i32),
20    Uint32(u32),
21    Int64(i64),
22    Uint64(u64),
23    Double(f64),
24    /// `s`
25    Str(String),
26    /// `o` — syntactically a string, semantically a path.
27    ObjectPath(String),
28    /// `g`
29    Signature(String),
30    /// `h` — an index into the message's file-descriptor array.
31    UnixFd(u32),
32    /// `a<elem>`. The element signature is carried so an empty array still
33    /// marshals with the right type.
34    Array {
35        element: String,
36        items: Vec<Value>,
37    },
38    /// `(...)`
39    Struct(Vec<Value>),
40    /// `v` — a value that carries its own signature.
41    Variant(Box<Value>),
42    /// `{kv}`, only ever valid as an array element.
43    DictEntry(Box<Value>, Box<Value>),
44}
45
46impl Value {
47    /// The signature of this value.
48    pub fn signature(&self) -> String {
49        match self {
50            Self::Byte(_) => "y".into(),
51            Self::Bool(_) => "b".into(),
52            Self::Int16(_) => "n".into(),
53            Self::Uint16(_) => "q".into(),
54            Self::Int32(_) => "i".into(),
55            Self::Uint32(_) => "u".into(),
56            Self::Int64(_) => "x".into(),
57            Self::Uint64(_) => "t".into(),
58            Self::Double(_) => "d".into(),
59            Self::Str(_) => "s".into(),
60            Self::ObjectPath(_) => "o".into(),
61            Self::Signature(_) => "g".into(),
62            Self::UnixFd(_) => "h".into(),
63            Self::Array { element, .. } => format!("a{element}"),
64            Self::Struct(fields) => {
65                let inner: String = fields.iter().map(Self::signature).collect();
66                format!("({inner})")
67            }
68            Self::Variant(_) => "v".into(),
69            Self::DictEntry(k, v) => format!("{{{}{}}}", k.signature(), v.signature()),
70        }
71    }
72
73    /// Build an `a{sv}` from pairs — the shape of nearly every BlueZ argument.
74    pub fn dict(entries: impl IntoIterator<Item = (String, Value)>) -> Self {
75        Self::Array {
76            element: "{sv}".into(),
77            items: entries
78                .into_iter()
79                .map(|(k, v)| {
80                    Value::DictEntry(
81                        Box::new(Value::Str(k)),
82                        Box::new(Value::Variant(Box::new(v))),
83                    )
84                })
85                .collect(),
86        }
87    }
88
89    /// Build an `as` from strings.
90    pub fn string_array(items: impl IntoIterator<Item = String>) -> Self {
91        Self::Array {
92            element: "s".into(),
93            items: items.into_iter().map(Value::Str).collect(),
94        }
95    }
96
97    /// Build an `ay` from bytes.
98    pub fn bytes(data: &[u8]) -> Self {
99        Self::Array {
100            element: "y".into(),
101            items: data.iter().copied().map(Value::Byte).collect(),
102        }
103    }
104
105    // ── Accessors ───────────────────────────────────────────────────────────
106    // A value that came off the bus may be wrapped in a variant, sometimes
107    // several deep, so every accessor unwraps first. Reading `Value::Str` from
108    // a property without that is the single most common D-Bus client bug.
109
110    /// Peel off any `Variant` wrappers.
111    pub fn peel(&self) -> &Value {
112        match self {
113            Self::Variant(inner) => inner.peel(),
114            other => other,
115        }
116    }
117
118    pub fn as_str(&self) -> Option<&str> {
119        match self.peel() {
120            Self::Str(s) | Self::ObjectPath(s) | Self::Signature(s) => Some(s),
121            _ => None,
122        }
123    }
124
125    pub fn as_bool(&self) -> Option<bool> {
126        match self.peel() {
127            Self::Bool(b) => Some(*b),
128            _ => None,
129        }
130    }
131
132    pub fn as_u64(&self) -> Option<u64> {
133        match self.peel() {
134            Self::Byte(v) => Some(*v as u64),
135            Self::Uint16(v) => Some(*v as u64),
136            Self::Uint32(v) => Some(*v as u64),
137            Self::Uint64(v) => Some(*v),
138            Self::UnixFd(v) => Some(*v as u64),
139            _ => None,
140        }
141    }
142
143    pub fn as_i64(&self) -> Option<i64> {
144        match self.peel() {
145            Self::Byte(v) => Some(*v as i64),
146            Self::Int16(v) => Some(*v as i64),
147            Self::Uint16(v) => Some(*v as i64),
148            Self::Int32(v) => Some(*v as i64),
149            Self::Uint32(v) => Some(*v as i64),
150            Self::Int64(v) => Some(*v),
151            _ => None,
152        }
153    }
154
155    pub fn as_array(&self) -> Option<&[Value]> {
156        match self.peel() {
157            Self::Array { items, .. } => Some(items),
158            Self::Struct(fields) => Some(fields),
159            _ => None,
160        }
161    }
162
163    /// Collect an `ay` into bytes.
164    pub fn as_bytes(&self) -> Option<Vec<u8>> {
165        let items = self.as_array()?;
166        items
167            .iter()
168            .map(|v| match v.peel() {
169                Self::Byte(b) => Some(*b),
170                _ => None,
171            })
172            .collect()
173    }
174
175    /// Collect an `as` / `ao` into strings.
176    pub fn as_strings(&self) -> Vec<String> {
177        self.as_array()
178            .map(|items| {
179                items
180                    .iter()
181                    .filter_map(|v| v.as_str().map(str::to_owned))
182                    .collect()
183            })
184            .unwrap_or_default()
185    }
186
187    /// Interpret an `a{sv}` (or any dict) as a map.
188    pub fn as_map(&self) -> HashMap<String, Value> {
189        let mut out = HashMap::new();
190        if let Some(items) = self.as_array() {
191            for item in items {
192                if let Self::DictEntry(k, v) = item.peel() {
193                    if let Some(key) = k.as_str() {
194                        out.insert(key.to_owned(), (**v).clone());
195                    }
196                }
197            }
198        }
199        out
200    }
201
202    /// Look a key up in an `a{sv}`.
203    pub fn get(&self, key: &str) -> Option<Value> {
204        if let Some(items) = self.as_array() {
205            for item in items {
206                if let Self::DictEntry(k, v) = item.peel() {
207                    if k.as_str() == Some(key) {
208                        return Some((**v).clone());
209                    }
210                }
211            }
212        }
213        None
214    }
215}
216
217impl fmt::Display for Value {
218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219        match self {
220            Self::Str(s) | Self::ObjectPath(s) | Self::Signature(s) => write!(f, "{s}"),
221            Self::Variant(v) => write!(f, "{v}"),
222            other => write!(f, "{other:?}"),
223        }
224    }
225}
226
227// ── Signatures ──────────────────────────────────────────────────────────────
228
229/// The natural alignment of a type code, in bytes.
230///
231/// Padding between values is what makes D-Bus marshalling fiddly: every value
232/// starts at a multiple of its alignment, counted from the **start of the
233/// message**, not from the start of the body.
234pub fn alignment(code: u8) -> usize {
235    match code {
236        b'y' | b'g' | b'v' => 1,
237        b'n' | b'q' => 2,
238        b'b' | b'i' | b'u' | b's' | b'o' | b'a' | b'h' => 4,
239        b'x' | b't' | b'd' | b'(' | b')' | b'{' | b'}' | b'r' | b'e' => 8,
240        _ => 1,
241    }
242}
243
244/// Split a signature into its complete top-level types.
245///
246/// `"sa{sv}u"` → `["s", "a{sv}", "u"]`. Needed because a struct or array body
247/// is described by a concatenation, not a list.
248pub fn complete_types(signature: &str) -> Vec<String> {
249    let bytes = signature.as_bytes();
250    let mut out = Vec::new();
251    let mut i = 0;
252    while i < bytes.len() {
253        let len = match type_length(&bytes[i..]) {
254            Some(n) => n,
255            None => break,
256        };
257        out.push(signature[i..i + len].to_string());
258        i += len;
259    }
260    out
261}
262
263/// How many bytes of `signature` the first complete type occupies.
264pub fn type_length(signature: &[u8]) -> Option<usize> {
265    let first = *signature.first()?;
266    match first {
267        // `a` is followed by exactly one complete type.
268        b'a' => Some(1 + type_length(&signature[1..])?),
269        // Balanced brackets, which may nest.
270        b'(' | b'{' => {
271            let (open, close) = if first == b'(' {
272                (b'(', b')')
273            } else {
274                (b'{', b'}')
275            };
276            let mut depth = 0usize;
277            for (i, &c) in signature.iter().enumerate() {
278                if c == open {
279                    depth += 1;
280                } else if c == close {
281                    depth -= 1;
282                    if depth == 0 {
283                        return Some(i + 1);
284                    }
285                }
286            }
287            None
288        }
289        _ => Some(1),
290    }
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    #[test]
298    fn signatures_round_trip_through_values() {
299        assert_eq!(Value::Str("x".into()).signature(), "s");
300        assert_eq!(Value::bytes(&[1, 2]).signature(), "ay");
301        assert_eq!(Value::string_array(["a".into()]).signature(), "as");
302        assert_eq!(
303            Value::dict([("k".into(), Value::Uint32(1))]).signature(),
304            "a{sv}"
305        );
306        assert_eq!(
307            Value::Struct(vec![Value::Str("a".into()), Value::Uint32(2)]).signature(),
308            "(su)"
309        );
310        assert_eq!(Value::UnixFd(3).as_u64(), Some(3));
311    }
312
313    #[test]
314    fn complete_types_splits_concatenations() {
315        assert_eq!(complete_types("sa{sv}u"), vec!["s", "a{sv}", "u"]);
316        assert_eq!(complete_types("ay"), vec!["ay"]);
317        assert_eq!(complete_types(""), Vec::<String>::new());
318        // The GetManagedObjects reply type — nested arrays of dicts.
319        assert_eq!(complete_types("a{oa{sa{sv}}}"), vec!["a{oa{sa{sv}}}"]);
320        assert_eq!(complete_types("(is)(bb)"), vec!["(is)", "(bb)"]);
321    }
322
323    #[test]
324    fn nested_brackets_are_balanced_not_counted() {
325        assert_eq!(type_length(b"a{sa{sv}}"), Some(9));
326        assert_eq!(type_length(b"((ii)(ss))x"), Some(10));
327        // Unbalanced input must not panic or over-read.
328        assert_eq!(type_length(b"(is"), None);
329        assert_eq!(type_length(b""), None);
330    }
331
332    #[test]
333    fn alignments_match_the_specification() {
334        for (code, want) in [
335            (b'y', 1),
336            (b'b', 4),
337            (b'n', 2),
338            (b'q', 2),
339            (b'i', 4),
340            (b'u', 4),
341            (b'x', 8),
342            (b't', 8),
343            (b'd', 8),
344            (b's', 4),
345            (b'o', 4),
346            (b'g', 1),
347            (b'a', 4),
348            (b'(', 8),
349            (b'{', 8),
350            (b'v', 1),
351            (b'h', 4),
352        ] {
353            assert_eq!(alignment(code), want, "alignment of {}", code as char);
354        }
355    }
356
357    #[test]
358    fn accessors_peel_variants() {
359        // BlueZ returns every property wrapped in a variant.
360        let wrapped = Value::Variant(Box::new(Value::Str("Pixel".into())));
361        assert_eq!(wrapped.as_str(), Some("Pixel"));
362
363        let nested = Value::Variant(Box::new(Value::Variant(Box::new(Value::Bool(true)))));
364        assert_eq!(nested.as_bool(), Some(true));
365
366        let map = Value::dict([("Name".into(), Value::Str("Pixel".into()))]);
367        assert_eq!(map.get("Name").unwrap().as_str(), Some("Pixel"));
368        assert_eq!(map.get("Missing"), None);
369    }
370
371    #[test]
372    fn byte_arrays_collect() {
373        let v = Value::bytes(&[0xDE, 0xAD]);
374        assert_eq!(v.as_bytes(), Some(vec![0xDE, 0xAD]));
375        // A non-byte array is not bytes.
376        assert_eq!(Value::string_array(["a".into()]).as_bytes(), None);
377    }
378}