Debian Codegraph @

third_party/rust/dbus/src/arg/msgarg.rs

raw
1 #![allow(dead_code)]
2
3 use {Signature, Message, arg::TypeMismatchError};
4 use std::{fmt, any};
5 use std::sync::Arc;
6 use std::rc::Rc;
7
8 use super::{Iter, IterAppend, ArgType};
9
10 /// Types that can represent a D-Bus message argument implement this trait.
11 ///
12 /// Types should also implement either Append or Get to be useful.
13 pub trait Arg {
14 /// The corresponding D-Bus argument type code.
15 const ARG_TYPE: ArgType;
16 /// The corresponding D-Bus argument type code; just returns ARG_TYPE.
17 ///
18 /// For backwards compatibility.
19 #[deprecated(note = "Use associated constant ARG_TYPE instead")]
20 fn arg_type() -> ArgType { return Self::ARG_TYPE; }
21 /// The corresponding D-Bus type signature for this type.
22 fn signature() -> Signature<'static>;
23 }
24
25 /// Types that can be appended to a message as arguments implement this trait.
26 pub trait Append: Sized {
27 /// Performs the append operation.
28 fn append(self, &mut IterAppend);
29 }
30
31 /// Helper trait to append many arguments to a message.
32 pub trait AppendAll: Sized {
33 /// Performs the append operation.
34 fn append(self, &mut IterAppend);
35 }
36
37 /// Types that can be retrieved from a message as arguments implement this trait.
38 pub trait Get<'a>: Sized {
39 /// Performs the get operation.
40 fn get(i: &mut Iter<'a>) -> Option<Self>;
41 }
42
43 /// Helper trait to read all arguments from a message.
44 pub trait ReadAll: Sized {
45 /// Performs the read operation.
46 fn read(i: &mut Iter) -> Result<Self, TypeMismatchError>;
47 }
48
49
50 /// Object safe version of Arg + Append + Get.
51 pub trait RefArg: fmt::Debug {
52 /// The corresponding D-Bus argument type code.
53 fn arg_type(&self) -> ArgType;
54 /// The corresponding D-Bus type signature for this type.
55 fn signature(&self) -> Signature<'static>;
56 /// Performs the append operation.
57 fn append(&self, &mut IterAppend);
58 /// Transforms this argument to Any (which can be downcasted to read the current value).
59 ///
60 /// Note: The internal representation of complex types (Array, Dict, Struct) is unstable
61 /// and as_any should not be relied upon for these types. Use as_iter instead.
62 fn as_any(&self) -> &any::Any where Self: 'static;
63 /// Transforms this argument to Any (which can be downcasted to read the current value).
64 ///
65 /// Note: The internal representation of complex types (Array, Dict, Struct) is unstable
66 /// and as_any should not be relied upon for these types. Use as_iter instead.
67 ///
68 /// # Panic
69 /// Will panic if the interior cannot be made mutable, e g, if encapsulated
70 /// inside a Rc with a reference count > 1.
71 fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static;
72 /// Try to read the argument as an i64.
73 ///
74 /// Works for: Boolean, Byte, Int16, UInt16, Int32, UInt32, Int64, UnixFd.
75 #[inline]
76 fn as_i64(&self) -> Option<i64> { None }
77 /// Try to read the argument as an u64.
78 ///
79 /// Works for: Boolean, Byte, Int16, UInt16, Int32, UInt32, UInt64.
80 #[inline]
81 fn as_u64(&self) -> Option<u64> { None }
82 /// Try to read the argument as an f64.
83 ///
84 /// Works for: Boolean, Byte, Int16, UInt16, Int32, UInt32, Double.
85 #[inline]
86 fn as_f64(&self) -> Option<f64> { None }
87 /// Try to read the argument as a str.
88 ///
89 /// Works for: String, ObjectPath, Signature.
90 #[inline]
91 fn as_str(&self) -> Option<&str> { None }
92 /// Try to read the argument as an iterator.
93 ///
94 /// Works for: Array/Dict, Struct, Variant.
95 #[inline]
96 fn as_iter<'a>(&'a self) -> Option<Box<Iterator<Item=&'a RefArg> + 'a>> { None }
97 /// Deep clone of the RefArg, causing the result to be 'static.
98 ///
99 /// Usable as an escape hatch in case of lifetime problems with RefArg.
100 ///
101 /// In case of complex types (Array, Dict, Struct), the clone is not guaranteed
102 /// to have the same internal representation as the original.
103 fn box_clone(&self) -> Box<RefArg + 'static> { unimplemented!() /* Needed for backwards comp */ }
104 }
105
106 impl<'a> Get<'a> for Box<RefArg> {
107 fn get(i: &mut Iter<'a>) -> Option<Self> { i.get_refarg() }
108 }
109
110 /// Cast a RefArg as a specific type (shortcut for any + downcast)
111 #[inline]
112 pub fn cast<'a, T: 'static>(a: &'a (RefArg + 'static)) -> Option<&'a T> { a.as_any().downcast_ref() }
113
114 /// Cast a RefArg as a specific type (shortcut for any_mut + downcast_mut)
115 ///
116 /// # Panic
117 /// Will panic if the interior cannot be made mutable, e g, if encapsulated
118 /// inside a Rc with a reference count > 1.
119 #[inline]
120 pub fn cast_mut<'a, T: 'static>(a: &'a mut (RefArg + 'static)) -> Option<&'a mut T> { a.as_any_mut().downcast_mut() }
121
122 /// If a type implements this trait, it means the size and alignment is the same
123 /// as in D-Bus. This means that you can quickly append and get slices of this type.
124 ///
125 /// Note: Booleans do not implement this trait because D-Bus booleans are 4 bytes and Rust booleans are 1 byte.
126 pub unsafe trait FixedArray: Arg + 'static + Clone + Copy {}
127
128 /// Types that can be used as keys in a dict type implement this trait.
129 pub trait DictKey: Arg {}
130
131
132
133 /// Simple lift over reference to value - this makes some iterators more ergonomic to use
134 impl<'a, T: Arg> Arg for &'a T {
135 const ARG_TYPE: ArgType = T::ARG_TYPE;
136 fn signature() -> Signature<'static> { T::signature() }
137 }
138 impl<'a, T: Append + Clone> Append for &'a T {
139 fn append(self, i: &mut IterAppend) { self.clone().append(i) }
140 }
141 impl<'a, T: DictKey> DictKey for &'a T {}
142
143 impl<'a, T: RefArg + ?Sized> RefArg for &'a T {
144 #[inline]
145 fn arg_type(&self) -> ArgType { (&**self).arg_type() }
146 #[inline]
147 fn signature(&self) -> Signature<'static> { (&**self).signature() }
148 #[inline]
149 fn append(&self, i: &mut IterAppend) { (&**self).append(i) }
150 #[inline]
151 fn as_any(&self) -> &any::Any where T: 'static { (&**self).as_any() }
152 #[inline]
153 fn as_any_mut(&mut self) -> &mut any::Any where T: 'static { unreachable!() }
154 #[inline]
155 fn as_i64(&self) -> Option<i64> { (&**self).as_i64() }
156 #[inline]
157 fn as_u64(&self) -> Option<u64> { (&**self).as_u64() }
158 #[inline]
159 fn as_f64(&self) -> Option<f64> { (&**self).as_f64() }
160 #[inline]
161 fn as_str(&self) -> Option<&str> { (&**self).as_str() }
162 #[inline]
163 fn as_iter<'b>(&'b self) -> Option<Box<Iterator<Item=&'b RefArg> + 'b>> { (&**self).as_iter() }
164 #[inline]
165 fn box_clone(&self) -> Box<RefArg + 'static> { (&**self).box_clone() }
166 }
167
168
169
170 macro_rules! deref_impl {
171 ($t: ident, $ss: ident, $make_mut: expr) => {
172
173 impl<T: RefArg + ?Sized> RefArg for $t<T> {
174 #[inline]
175 fn arg_type(&self) -> ArgType { (&**self).arg_type() }
176 #[inline]
177 fn signature(&self) -> Signature<'static> { (&**self).signature() }
178 #[inline]
179 fn append(&self, i: &mut IterAppend) { (&**self).append(i) }
180 #[inline]
181 fn as_any(&self) -> &any::Any where T: 'static { (&**self).as_any() }
182 #[inline]
183 fn as_any_mut<'a>(&'a mut $ss) -> &'a mut any::Any where T: 'static { $make_mut.as_any_mut() }
184 #[inline]
185 fn as_i64(&self) -> Option<i64> { (&**self).as_i64() }
186 #[inline]
187 fn as_u64(&self) -> Option<u64> { (&**self).as_u64() }
188 #[inline]
189 fn as_f64(&self) -> Option<f64> { (&**self).as_f64() }
190 #[inline]
191 fn as_str(&self) -> Option<&str> { (&**self).as_str() }
192 #[inline]
193 fn as_iter<'a>(&'a self) -> Option<Box<Iterator<Item=&'a RefArg> + 'a>> { (&**self).as_iter() }
194 #[inline]
195 fn box_clone(&self) -> Box<RefArg + 'static> { (&**self).box_clone() }
196 }
197 impl<T: DictKey> DictKey for $t<T> {}
198
199 impl<T: Arg> Arg for $t<T> {
200 const ARG_TYPE: ArgType = T::ARG_TYPE;
201 fn signature() -> Signature<'static> { T::signature() }
202 }
203 impl<'a, T: Get<'a>> Get<'a> for $t<T> {
204 fn get(i: &mut Iter<'a>) -> Option<Self> { T::get(i).map(|v| $t::new(v)) }
205 }
206
207 }
208 }
209
210 impl<T: Append> Append for Box<T> {
211 fn append(self, i: &mut IterAppend) { let q: T = *self; q.append(i) }
212 }
213
214 deref_impl!(Box, self, &mut **self );
215 deref_impl!(Rc, self, Rc::get_mut(self).unwrap());
216 deref_impl!(Arc, self, Arc::get_mut(self).unwrap());
217
218 /// Internal trait to help generics. Implemented for (), (A1), (A1, A2) and so on (where A1: Arg, A2: Arg etc).
219 ///
220 /// You would probably not use this trait directly, instead use generic functions which
221 /// take ArgBuilder as an argument. It helps reading and appending multiple arguments
222 /// to/from a message in one go.
223 pub trait ArgBuilder: Sized {
224 /// A tuple of &static str. Used for introspection.
225 type strs;
226 /// Low-level introspection helper method.
227 fn strs_sig<F: FnMut(&'static str, Signature<'static>)>(a: Self::strs, f: F);
228 /// Low-level method to read arguments from a message.
229 fn read(msg: &Message) -> Result<Self, TypeMismatchError>;
230 /// Low-level method to append arguments to a message.
231 fn append(self, msg: &mut Message);
232 }
233
234 impl ArgBuilder for () {
235 type strs = ();
236 fn strs_sig<F: FnMut(&'static str, Signature<'static>)>(_: Self::strs, _: F) {}
237 fn read(_: &Message) -> Result<Self, TypeMismatchError> { Ok(()) }
238 fn append(self, _: &mut Message) {}
239 }
240
241 macro_rules! argbuilder_impl {
242 ($($n: ident $t: ident $s: ty,)+) => {
243
244 impl<$($t: Arg + Append + for<'z> Get<'z>),*> ArgBuilder for ($($t,)*) {
245 type strs = ($(&'static $s,)*);
246 fn strs_sig<Q: FnMut(&'static str, Signature<'static>)>(z: Self::strs, mut q: Q) {
247 let ( $($n,)*) = z;
248 $( q($n, $t::signature()); )*
249 }
250
251 fn read(msg: &Message) -> Result<Self, TypeMismatchError> {
252 let mut ii = msg.iter_init();
253 $( let $n = ii.read()?; )*
254 Ok(($( $n, )* ))
255 }
256
257 fn append(self, msg: &mut Message) {
258 let ( $($n,)*) = self;
259 let mut ia = IterAppend::new(msg);
260 $( ia.append($n); )*
261 }
262 }
263
264 impl<$($t: Append),*> AppendAll for ($($t,)*) {
265 fn append(self, ia: &mut IterAppend) {
266 let ( $($n,)*) = self;
267 $( ia.append($n); )*
268 }
269 }
270
271 impl<$($t: Arg + for<'z> Get<'z>),*> ReadAll for ($($t,)*) {
272 fn read(ii: &mut Iter) -> Result<Self, TypeMismatchError> {
273 $( let $n = ii.read()?; )*
274 Ok(($( $n, )* ))
275 }
276 }
277
278
279 }
280 }
281
282 argbuilder_impl!(a A str,);
283 argbuilder_impl!(a A str, b B str,);
284 argbuilder_impl!(a A str, b B str, c C str,);
285 argbuilder_impl!(a A str, b B str, c C str, d D str,);
286 argbuilder_impl!(a A str, b B str, c C str, d D str, e E str,);
287 argbuilder_impl!(a A str, b B str, c C str, d D str, e E str, f F str,);
288 argbuilder_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str,);
289 argbuilder_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str,);
290 argbuilder_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str,);
291 argbuilder_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str,);
292
293
294
295 #[cfg(test)]
296 mod test {
297 extern crate tempdir;
298
299 use {Connection, ConnectionItem, Message, BusType, Path, Signature};
300 use arg::{Array, Variant, Dict, Iter, ArgType, TypeMismatchError, RefArg, cast};
301
302 use std::collections::HashMap;
303
304 #[test]
305 fn refarg() {
306 let c = Connection::get_private(BusType::Session).unwrap();
307 c.register_object_path("/mooh").unwrap();
308 let m = Message::new_method_call(&c.unique_name(), "/mooh", "com.example.hello", "Hello").unwrap();
309
310 let mut vv: Vec<Variant<Box<RefArg>>> = vec!();
311 vv.push(Variant(Box::new(5i32)));
312 vv.push(Variant(Box::new(String::from("Hello world"))));
313 let m = m.append_ref(&vv);
314
315 let (f1, f2) = (false, 7u64);
316 let mut v: Vec<&RefArg> = vec!();
317 v.push(&f1);
318 v.push(&f2);
319 let m = m.append_ref(&v);
320 let vi32 = vec![7i32, 9i32];
321 let vstr: Vec<String> = ["This", "is", "dbus", "rs"].iter().map(|&s| s.into()).collect();
322 let m = m.append_ref(&[&vi32 as &RefArg, &vstr as &RefArg]);
323 let mut map = HashMap::new();
324 map.insert(true, String::from("Yes"));
325 map.insert(false, String::from("No"));
326 let m = m.append_ref(&[&map as &RefArg, &1.5f64 as &RefArg]);
327
328 c.send(m).unwrap();
329
330 for n in c.iter(1000) {
331 if let ConnectionItem::MethodCall(m) = n {
332 let rv: Vec<Box<RefArg + 'static>> = m.iter_init().collect();
333 println!("Receiving {:?}", rv);
334 let rv0: &Variant<Box<RefArg>> = cast(&rv[0]).unwrap();
335 let rv00: &i32 = cast(&rv0.0).unwrap();
336 assert_eq!(rv00, &5i32);
337 assert_eq!(Some(&false), rv[2].as_any().downcast_ref::<bool>());
338 assert_eq!(Some(&vi32), rv[4].as_any().downcast_ref::<Vec<i32>>());
339 assert_eq!(Some(&vstr), rv[5].as_any().downcast_ref::<Vec<String>>());
340 let mut diter = rv[6].as_iter().unwrap();
341 {
342 let mut mmap: HashMap<bool, String> = HashMap::new();
343 while let Some(k) = diter.next() {
344 let x: String = diter.next().unwrap().as_str().unwrap().into();
345 mmap.insert(*cast::<bool>(&k.box_clone()).unwrap(), x);
346 }
347 assert_eq!(mmap[&true], "Yes");
348 }
349 let mut iter = rv[6].as_iter().unwrap();
350 assert!(iter.next().unwrap().as_i64().is_some());
351 assert!(iter.next().unwrap().as_str().is_some());
352 assert!(iter.next().unwrap().as_str().is_none());
353 assert!(iter.next().unwrap().as_i64().is_none());
354 assert!(iter.next().is_none());
355 assert!(rv[7].as_f64().unwrap() > 1.0);
356 assert!(rv[7].as_f64().unwrap() < 2.0);
357 break;
358 }
359 }
360 }
361
362 #[test]
363 fn message_types() {
364 let c = Connection::get_private(BusType::Session).unwrap();
365 c.register_object_path("/hello").unwrap();
366 let m = Message::new_method_call(&c.unique_name(), "/hello", "com.example.hello", "Hello").unwrap();
367 let m = m.append1(2000u16);
368 let m = m.append1(Array::new(&vec![129u8, 5, 254]));
369 let m = m.append2(Variant(&["Hello", "world"][..]), &[32768u16, 16u16, 12u16][..]);
370 let m = m.append3(-1i32, &*format!("Hello world"), -3.14f64);
371 let m = m.append1((256i16, Variant(18_446_744_073_709_551_615u64)));
372 let m = m.append2(Path::new("/a/valid/path").unwrap(), Signature::new("a{sv}").unwrap());
373 let mut z = HashMap::new();
374 z.insert(123543u32, true);
375 z.insert(0u32, false);
376 let m = m.append1(Dict::new(&z));
377 let sending = format!("{:?}", m.iter_init());
378 println!("Sending {}", sending);
379 c.send(m).unwrap();
380
381 for n in c.iter(1000) {
382 match n {
383 ConnectionItem::MethodCall(m) => {
384 use super::Arg;
385 let receiving = format!("{:?}", m.iter_init());
386 println!("Receiving {}", receiving);
387 assert_eq!(sending, receiving);
388
389 assert_eq!(2000u16, m.get1().unwrap());
390 assert_eq!(m.get2(), (Some(2000u16), Some(&[129u8, 5, 254][..])));
391 assert_eq!(m.read2::<u16, bool>().unwrap_err(),
392 TypeMismatchError { position: 1, found: ArgType::Array, expected: ArgType::Boolean });
393
394 let mut g = m.iter_init();
395 let e = g.read::<u32>().unwrap_err();
396 assert_eq!(e.pos(), 0);
397 assert_eq!(e.expected_arg_type(), ArgType::UInt32);
398 assert_eq!(e.found_arg_type(), ArgType::UInt16);
399
400 assert!(g.next() && g.next());
401 let v: Variant<Iter> = g.get().unwrap();
402 let mut viter = v.0;
403 assert_eq!(viter.arg_type(), Array::<&str,()>::ARG_TYPE);
404 let a: Array<&str, _> = viter.get().unwrap();
405 assert_eq!(a.collect::<Vec<&str>>(), vec!["Hello", "world"]);
406
407 assert!(g.next());
408 assert_eq!(g.get::<u16>(), None); // It's an array, not a single u16
409 assert!(g.next() && g.next() && g.next() && g.next());
410
411 assert_eq!(g.get(), Some((256i16, Variant(18_446_744_073_709_551_615u64))));
412 assert!(g.next());
413 assert_eq!(g.get(), Some(Path::new("/a/valid/path").unwrap()));
414 assert!(g.next());
415 assert_eq!(g.get(), Some(Signature::new("a{sv}").unwrap()));
416 assert!(g.next());
417 let d: Dict<u32, bool, _> = g.get().unwrap();
418 let z2: HashMap<_, _> = d.collect();
419 assert_eq!(z, z2);
420 break;
421 }
422 _ => println!("Got {:?}", n),
423 }
424 }
425 }
426 }