logo
  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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#![cfg(feature = "xml")]

//! Introspection XML support (`xml` feature)
//!
//! Thanks to the [`org.freedesktop.DBus.Introspectable`] interface, objects may be introspected at
//! runtime, returning an XML string that describes the object.
//!
//! This optional `xml` module provides facilities to parse the XML data into more convenient Rust
//! structures. The XML string may be parsed to a tree with [`Node.from_reader()`].
//!
//! See also:
//!
//! * [Introspection format] in the DBus specification
//!
//! [`Node.from_reader()`]: struct.Node.html#method.from_reader
//! [Introspection format]: https://dbus.freedesktop.org/doc/dbus-specification.html#introspection-format
//! [`org.freedesktop.DBus.Introspectable`]: https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-introspectable

use serde::{Deserialize, Serialize};
use serde_xml_rs::{from_reader, from_str, to_writer};
use static_assertions::assert_impl_all;
use std::{
    io::{Read, Write},
    result::Result,
};

use crate::Error;

// note: serde-xml-rs doesn't handle nicely interleaved elements, so we have to use enums:
// https://github.com/RReverser/serde-xml-rs/issues/55

macro_rules! get_vec {
    ($vec:expr, $kind:path) => {
        $vec.iter()
            .filter_map(|e| if let $kind(m) = e { Some(m) } else { None })
            .collect()
    };
}

/// Annotations are generic key/value pairs of metadata.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Annotation {
    name: String,
    value: String,
}

assert_impl_all!(Annotation: Send, Sync, Unpin);

impl Annotation {
    /// Return the annotation name/key.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Return the annotation value.
    pub fn value(&self) -> &str {
        &self.value
    }
}

/// An argument
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Arg {
    name: Option<String>,
    r#type: String,
    direction: Option<String>,
    #[serde(rename = "annotation", default)]
    annotations: Vec<Annotation>,
}

assert_impl_all!(Arg: Send, Sync, Unpin);

impl Arg {
    /// Return the argument name, if any.
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Return the argument type.
    pub fn ty(&self) -> &str {
        &self.r#type
    }

    /// Return the argument direction (should be "in" or "out"), if any.
    pub fn direction(&self) -> Option<&str> {
        self.direction.as_deref()
    }

    /// Return the associated annotations.
    pub fn annotations(&self) -> Vec<&Annotation> {
        self.annotations.iter().collect()
    }
}

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "lowercase")]
enum MethodElement {
    Arg(Arg),
    Annotation(Annotation),
}

/// A method
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Method {
    name: String,

    #[serde(rename = "$value", default)]
    elems: Vec<MethodElement>,
}

assert_impl_all!(Method: Send, Sync, Unpin);

impl Method {
    /// Return the method name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Return the method arguments.
    pub fn args(&self) -> Vec<&Arg> {
        get_vec!(self.elems, MethodElement::Arg)
    }

    /// Return the method annotations.
    pub fn annotations(&self) -> Vec<&Annotation> {
        get_vec!(self.elems, MethodElement::Annotation)
    }
}

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "lowercase")]
enum SignalElement {
    Arg(Arg),
    Annotation(Annotation),
}

/// A signal
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Signal {
    name: String,

    #[serde(rename = "$value", default)]
    elems: Vec<SignalElement>,
}

assert_impl_all!(Signal: Send, Sync, Unpin);

impl Signal {
    /// Return the signal name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Return the signal arguments.
    pub fn args(&self) -> Vec<&Arg> {
        get_vec!(self.elems, SignalElement::Arg)
    }

    /// Return the signal annotations.
    pub fn annotations(&self) -> Vec<&Annotation> {
        get_vec!(self.elems, SignalElement::Annotation)
    }
}

/// A property
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Property {
    name: String,
    r#type: String,
    access: String,

    #[serde(rename = "annotation", default)]
    annotations: Vec<Annotation>,
}

assert_impl_all!(Property: Send, Sync, Unpin);

impl Property {
    /// Returns the property name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the property type.
    pub fn ty(&self) -> &str {
        &self.r#type
    }

    /// Returns the property access flags (should be "read", "write" or "readwrite").
    pub fn access(&self) -> &str {
        &self.access
    }

    /// Return the associated annotations.
    pub fn annotations(&self) -> Vec<&Annotation> {
        self.annotations.iter().collect()
    }
}

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "lowercase")]
enum InterfaceElement {
    Method(Method),
    Signal(Signal),
    Property(Property),
    Annotation(Annotation),
}

/// An interface
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Interface {
    name: String,

    #[serde(rename = "$value", default)]
    elems: Vec<InterfaceElement>,
}

assert_impl_all!(Interface: Send, Sync, Unpin);

impl Interface {
    /// Returns the interface name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the interface methods.
    pub fn methods(&self) -> Vec<&Method> {
        get_vec!(self.elems, InterfaceElement::Method)
    }

    /// Returns the interface signals.
    pub fn signals(&self) -> Vec<&Signal> {
        get_vec!(self.elems, InterfaceElement::Signal)
    }

    /// Returns the interface properties.
    pub fn properties(&self) -> Vec<&Property> {
        get_vec!(self.elems, InterfaceElement::Property)
    }

    /// Return the associated annotations.
    pub fn annotations(&self) -> Vec<&Annotation> {
        get_vec!(self.elems, InterfaceElement::Annotation)
    }
}

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "lowercase")]
enum NodeElement {
    Node(Node),
    Interface(Interface),
}

/// An introspection tree node (typically the root of the XML document).
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Node {
    name: Option<String>,

    #[serde(rename = "$value", default)]
    elems: Vec<NodeElement>,
}

assert_impl_all!(Node: Send, Sync, Unpin);

impl Node {
    /// Parse the introspection XML document from reader.
    pub fn from_reader<R: Read>(reader: R) -> Result<Node, Error> {
        Ok(from_reader(reader)?)
    }

    /// Write the XML document to writer.
    pub fn to_writer<W: Write>(&self, writer: W) -> Result<(), Error> {
        Ok(to_writer(writer, &self)?)
    }

    /// Returns the node name, if any.
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Returns the children nodes.
    pub fn nodes(&self) -> Vec<&Node> {
        get_vec!(self.elems, NodeElement::Node)
    }

    /// Returns the interfaces on this node.
    pub fn interfaces(&self) -> Vec<&Interface> {
        get_vec!(self.elems, NodeElement::Interface)
    }
}

impl std::str::FromStr for Node {
    type Err = Error;

    /// Parse the introspection XML document from `s`.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(from_str(s)?)
    }
}

#[cfg(test)]
mod tests {
    use std::{error::Error, str::FromStr};
    use test_log::test;

    use super::Node;

    static EXAMPLE: &str = r##"
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
  "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
 <node name="/com/example/sample_object0">
   <node name="first"/>
   <interface name="com.example.SampleInterface0">
     <method name="Frobate">
       <arg name="foo" type="i" direction="in"/>
       <arg name="bar" type="s" direction="out"/>
       <arg name="baz" type="a{us}" direction="out"/>
       <annotation name="org.freedesktop.DBus.Deprecated" value="true"/>
     </method>
     <method name="Bazify">
       <arg name="bar" type="(iiu)" direction="in"/>
       <arg name="bar" type="v" direction="out"/>
     </method>
     <method name="Mogrify">
       <arg name="bar" type="(iiav)" direction="in"/>
     </method>
     <signal name="Changed">
       <arg name="new_value" type="b"/>
     </signal>
     <property name="Bar" type="y" access="readwrite"/>
   </interface>
   <node name="child_of_sample_object"/>
   <node name="another_child_of_sample_object"/>
</node>
"##;

    #[test]
    fn serde() -> Result<(), Box<dyn Error>> {
        let node = Node::from_reader(EXAMPLE.as_bytes())?;
        assert_eq!(node.interfaces().len(), 1);
        assert_eq!(node.nodes().len(), 3);

        let node_str = Node::from_str(EXAMPLE)?;
        assert_eq!(node_str.interfaces().len(), 1);
        assert_eq!(node_str.nodes().len(), 3);

        // TODO: Fails at the moment, this seems fresh & related:
        // https://github.com/RReverser/serde-xml-rs/pull/129
        //let mut writer = Vec::with_capacity(128);
        //node.to_writer(&mut writer).unwrap();
        Ok(())
    }
}