Skip to main content

dbus_serialize/
encoder.rs

1//! Implements the rustc_serialize::Encoder trait
2use std::collections::HashMap;
3
4use rustc_serialize::{Encoder,Encodable};
5
6use types::{Value,BasicValue,Struct,Signature,Dictionary,Array};
7
8pub struct DBusEncoder {
9    val: Vec<Value>,
10    key: Option<BasicValue>
11}
12
13#[derive(Debug,PartialEq)]
14pub enum EncoderError {
15    BadKeyType,
16    Unsupported,
17    EmptyArray,
18    EmptyMap,
19}
20
21impl DBusEncoder {
22    fn handle_struct (&mut self, len: usize) -> Result<(),EncoderError> {
23        let mut objs = Vec::new();
24        let mut sig = "(".to_string();
25        let offset = self.val.len() - len;
26        for v in self.val.drain(offset..) {
27            sig.push_str(v.get_signature());
28            objs.push(v);
29        }
30        sig.push(')');
31        self.val.push(Value::Struct(Struct {
32            objects: objs,
33            signature: Signature(sig),
34        }));
35        Ok(())
36    }
37
38    fn handle_array (&mut self, len: usize) -> Result<(),EncoderError> {
39        let mut objs = Vec::new();
40        let offset = self.val.len() - len;
41        for v in self.val.drain(offset..) {
42            objs.push(v);
43        }
44        self.val.push(Value::Array(Array::new(objs)));
45        Ok(())
46    }
47
48    pub fn new() -> DBusEncoder {
49        DBusEncoder {
50            val: Vec::new(),
51            key: None
52        }
53    }
54
55    pub fn encode<T: Encodable>(obj: &T) -> Result<Value,EncoderError> {
56        let mut encoder = DBusEncoder::new();
57        try!(obj.encode(&mut encoder));
58        Ok(encoder.val.remove(0))
59    }
60}
61
62impl<T: Encodable> From<T> for Value {
63    fn from(x: T) -> Value {
64        DBusEncoder::encode(&x).unwrap()
65    }
66}
67
68impl Encoder for DBusEncoder {
69    type Error = EncoderError;
70
71    fn emit_nil(&mut self) -> Result<(), Self::Error> {
72        Err(EncoderError::Unsupported)
73    }
74    fn emit_usize(&mut self, v: usize) -> Result<(), Self::Error> {
75        self.val.push(Value::BasicValue(BasicValue::Uint64(v as u64)));
76        Ok(())
77    }
78    fn emit_u64(&mut self, v: u64) -> Result<(), Self::Error> {
79        self.val.push(Value::BasicValue(BasicValue::Uint64(v)));
80        Ok(())
81    }
82    fn emit_u32(&mut self, v: u32) -> Result<(), Self::Error> {
83        self.val.push(Value::BasicValue(BasicValue::Uint32(v)));
84        Ok(())
85    }
86    fn emit_u16(&mut self, v: u16) -> Result<(), Self::Error> {
87        self.val.push(Value::BasicValue(BasicValue::Uint16(v)));
88        Ok(())
89    }
90    fn emit_u8(&mut self, v: u8) -> Result<(), Self::Error> {
91        self.val.push(Value::BasicValue(BasicValue::Byte(v)));
92        Ok(())
93    }
94    fn emit_isize(&mut self, v: isize) -> Result<(), Self::Error> {
95        self.val.push(Value::BasicValue(BasicValue::Int64(v as i64)));
96        Ok(())
97    }
98    fn emit_i64(&mut self, v: i64) -> Result<(), Self::Error> {
99        self.val.push(Value::BasicValue(BasicValue::Int64(v)));
100        Ok(())
101    }
102    fn emit_i32(&mut self, v: i32) -> Result<(), Self::Error> {
103        self.val.push(Value::BasicValue(BasicValue::Int32(v)));
104        Ok(())
105    }
106    fn emit_i16(&mut self, v: i16) -> Result<(), Self::Error> {
107        self.val.push(Value::BasicValue(BasicValue::Int16(v)));
108        Ok(())
109    }
110    fn emit_i8(&mut self, _v: i8) -> Result<(), Self::Error> {
111        Err(EncoderError::Unsupported)
112    }
113    fn emit_bool(&mut self, v: bool) -> Result<(), Self::Error> {
114        self.val.push(Value::BasicValue(BasicValue::Boolean(v)));
115        Ok(())
116    }
117    fn emit_f64(&mut self, v: f64) -> Result<(), Self::Error> {
118        self.val.push(Value::Double(v));
119        Ok(())
120    }
121    fn emit_f32(&mut self, v: f32) -> Result<(), Self::Error> {
122        self.val.push(Value::Double(v as f64));
123        Ok(())
124    }
125    fn emit_char(&mut self, v: char) -> Result<(), Self::Error> {
126        self.val.push(Value::BasicValue(BasicValue::Byte(v as u8)));
127        Ok(())
128    }
129    fn emit_str(&mut self, v: &str) -> Result<(), Self::Error> {
130        self.val.push(Value::BasicValue(BasicValue::String(v.to_string())));
131        Ok(())
132    }
133
134    fn emit_struct<F>(&mut self, _name: &str, len: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
135        try!(f(self));
136        self.handle_struct(len)
137    }
138    fn emit_struct_field<F>(&mut self, _f_name: &str, _f_idx: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
139        f(self)
140    }
141    fn emit_tuple<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
142        try!(f(self));
143        self.handle_struct(len)
144    }
145    fn emit_tuple_arg<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
146        f(self)
147    }
148    fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
149        try!(f(self));
150        self.handle_struct(len)
151    }
152    fn emit_tuple_struct_arg<F>(&mut self, _f_idx: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
153        f(self)
154    }
155
156    fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
157        if len == 0 {
158            return Err(EncoderError::EmptyArray)
159        }
160        try!(f(self));
161        self.handle_array(len)
162    }
163    fn emit_seq_elt<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
164        f(self)
165    }
166
167    fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
168        if len == 0 {
169            return Err(EncoderError::EmptyMap)
170        }
171        // Yes, i'm intentionally creating a Dictionary with an invalid signature...
172        let map : Dictionary = Dictionary::new_with_sig(HashMap::new(), "".to_string());
173        self.val.push(Value::Dictionary(map));
174        try!(f(self));
175
176        // Fix up the signature now that the map hopefully has elements in it.
177        let x = match self.val.pop().unwrap() {
178            Value::Dictionary(x) => x.map,
179            _ => panic!("Where'd my dictionary go?!")
180        };
181        self.val.push(Value::Dictionary(Dictionary::new(x)));
182        Ok(())
183    }
184    fn emit_map_elt_key<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
185        try!(f(self));
186        self.key = match self.val.pop().unwrap() {
187            Value::BasicValue(x) => Some(x),
188            _ => return Err(EncoderError::BadKeyType)
189        };
190        Ok(())
191    }
192    fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
193        let key : BasicValue = self.key.take().unwrap();
194        try!(f(self));
195        let val : Value = self.val.pop().unwrap();
196        let mut map = self.val.pop().unwrap();
197        match map {
198            Value::Dictionary(ref mut x) => x.map.insert(key, val),
199            _ => panic!("No dictionary on stack")
200        };
201        self.val.push(map);
202        Ok(())
203    }
204
205    fn emit_option<F>(&mut self, _f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
206        Err(EncoderError::Unsupported)
207    }
208    fn emit_option_none(&mut self) -> Result<(), Self::Error> {
209        Err(EncoderError::Unsupported)
210    }
211    fn emit_option_some<F>(&mut self, _f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
212        Err(EncoderError::Unsupported)
213    }
214    fn emit_enum<F>(&mut self, _name: &str, _f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
215        Err(EncoderError::Unsupported)
216    }
217    fn emit_enum_variant<F>(&mut self, _v_name: &str, _v_id: usize, _len: usize, _f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
218        Err(EncoderError::Unsupported)
219    }
220    fn emit_enum_variant_arg<F>(&mut self, _a_idx: usize, _f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
221        Err(EncoderError::Unsupported)
222    }
223    fn emit_enum_struct_variant<F>(&mut self, _v_name: &str, _v_id: usize, _len: usize, _f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
224        Err(EncoderError::Unsupported)
225    }
226    fn emit_enum_struct_variant_field<F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> {
227        Err(EncoderError::Unsupported)
228    }
229}
230
231#[cfg(test)]
232mod test {
233    use rustc_serialize::{Encoder,Encodable};
234    use std::collections::HashMap;
235    use types::{Value,BasicValue,Struct,Signature,Dictionary,Array};
236    use encoder::*;
237
238    #[test]
239    fn test_array() {
240        let array : Vec<u32> = vec![1,2,3];
241        let v = DBusEncoder::encode(&array).ok().unwrap();
242        let a2 = vec![
243            Value::BasicValue(BasicValue::Uint32(1)),
244            Value::BasicValue(BasicValue::Uint32(2)),
245            Value::BasicValue(BasicValue::Uint32(3)),
246        ];
247        assert_eq!(v, Value::Array(Array::new(a2)));
248    }
249
250    #[test]
251    fn test_empty_array() {
252        let array : Vec<u32> = vec![];
253        assert_eq!(DBusEncoder::encode(&array), Err(EncoderError::EmptyArray));
254    }
255
256    #[test]
257    fn test_nested_array() {
258        let a1 : Vec<u32> = vec![1,2,3];
259        let a2 : Vec<u32> = vec![16,17];
260        let a3 : Vec<u32> = vec![9];
261        let array : Vec<Vec<u32>> = vec![a1,a2,a3];
262        let v = DBusEncoder::encode(&array).ok().unwrap();
263        let expected_a1 = vec![
264            Value::BasicValue(BasicValue::Uint32(1)),
265            Value::BasicValue(BasicValue::Uint32(2)),
266            Value::BasicValue(BasicValue::Uint32(3)),
267        ];
268        let expected_a2 = vec![
269            Value::BasicValue(BasicValue::Uint32(16)),
270            Value::BasicValue(BasicValue::Uint32(17)),
271        ];
272        let expected_a3 = vec![
273            Value::BasicValue(BasicValue::Uint32(9)),
274        ];
275        let expected_array = vec![
276            Value::Array(Array::new(expected_a1)),
277            Value::Array(Array::new(expected_a2)),
278            Value::Array(Array::new(expected_a3)),
279        ];
280        assert_eq!(v, Value::Array(Array::new(expected_array)));
281    }
282
283    #[test]
284    fn test_map() {
285        let mut map : HashMap<u32,u64> = HashMap::new();
286        map.insert(1, 100);
287        map.insert(2, 200);
288        map.insert(3, 300);
289        let v = DBusEncoder::encode(&map).ok().unwrap();
290        let mut map2 : HashMap<BasicValue,Value> = HashMap::new();
291        map2.insert(BasicValue::Uint32(1), Value::BasicValue(BasicValue::Uint64(100)));
292        map2.insert(BasicValue::Uint32(2), Value::BasicValue(BasicValue::Uint64(200)));
293        map2.insert(BasicValue::Uint32(3), Value::BasicValue(BasicValue::Uint64(300)));
294        assert_eq!(v, Value::Dictionary(Dictionary::new(map2)));
295    }
296
297    #[test]
298    fn test_empty_map() {
299        let map : HashMap<u32,u64> = HashMap::new();
300        assert_eq!(DBusEncoder::encode(&map), Err(EncoderError::EmptyMap));
301    }
302
303    #[test]
304    fn test_bad_map_key() {
305        let mut map : HashMap<(u32,u32),u32> = HashMap::new();
306        map.insert((1,2), 100);
307        assert_eq!(DBusEncoder::encode(&map), Err(EncoderError::BadKeyType));
308    }
309
310    #[test]
311    fn test_nested_map() {
312        let mut map1 : HashMap<u64,u16> = HashMap::new();
313        map1.insert(1, 10);
314        map1.insert(2, 20);
315        map1.insert(3, 30);
316        let mut map2 : HashMap<u64,u16> = HashMap::new();
317        map2.insert(1, 10);
318        map2.insert(2, 20);
319        let mut map3 : HashMap<u64,u16> = HashMap::new();
320        map3.insert(19, 190);
321        let mut map : HashMap<i32,HashMap<u64,u16>> = HashMap::new();
322        map.insert(-1, map1);
323        map.insert(-2, map2);
324        map.insert(-3, map3);
325        let v = DBusEncoder::encode(&map).ok().unwrap();
326        let mut expected_map1 : HashMap<BasicValue,Value> = HashMap::new();
327        expected_map1.insert(BasicValue::Uint64(1), Value::BasicValue(BasicValue::Uint16(10)));
328        expected_map1.insert(BasicValue::Uint64(2), Value::BasicValue(BasicValue::Uint16(20)));
329        expected_map1.insert(BasicValue::Uint64(3), Value::BasicValue(BasicValue::Uint16(30)));
330        let mut expected_map2 : HashMap<BasicValue,Value> = HashMap::new();
331        expected_map2.insert(BasicValue::Uint64(1), Value::BasicValue(BasicValue::Uint16(10)));
332        expected_map2.insert(BasicValue::Uint64(2), Value::BasicValue(BasicValue::Uint16(20)));
333        let mut expected_map3 : HashMap<BasicValue,Value> = HashMap::new();
334        expected_map3.insert(BasicValue::Uint64(19), Value::BasicValue(BasicValue::Uint16(190)));
335        let mut expected_map : HashMap<BasicValue,Value> = HashMap::new();
336        expected_map.insert(BasicValue::Int32(-1), Value::Dictionary(Dictionary::new(expected_map1)));
337        expected_map.insert(BasicValue::Int32(-2), Value::Dictionary(Dictionary::new(expected_map2)));
338        expected_map.insert(BasicValue::Int32(-3), Value::Dictionary(Dictionary::new(expected_map3)));
339        assert_eq!(v, Value::Dictionary(Dictionary::new(expected_map)));
340    }
341
342    struct SimpleTestStruct {
343        a: i32,
344        b: u64,
345    }
346
347    impl Encodable for SimpleTestStruct {
348        fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
349            s.emit_struct("SimpleTestStruct", 2, |s| {
350                try!(s.emit_struct_field("a", 0, |s| {
351                    s.emit_i32(self.a)
352                }));
353                try!(s.emit_struct_field("b", 1, |s| {
354                    s.emit_u64(self.b)
355                }));
356                Ok(())
357            })
358        }
359    }
360
361    struct EmptyTestStruct {
362    }
363
364    impl Encodable for EmptyTestStruct {
365        fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
366            s.emit_struct("EmptyTestStruct", 0, |_| { Ok(()) })
367        }
368    }
369
370    struct NestedTestStruct {
371        x: SimpleTestStruct,
372        y: SimpleTestStruct,
373        z: EmptyTestStruct,
374    }
375
376    impl Encodable for NestedTestStruct {
377        fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
378            s.emit_struct("NestedTestStruct", 3, |s| {
379                try!(s.emit_struct_field("x", 0, |s| {
380                    Encodable::encode(&self.x, s)
381                }));
382                try!(s.emit_struct_field("y", 1, |s| {
383                    Encodable::encode(&self.y, s)
384                }));
385                try!(s.emit_struct_field("z", 2, |s| {
386                    Encodable::encode(&self.z, s)
387                }));
388                Ok(())
389            })
390        }
391    }
392
393    #[test]
394    fn test_struct() {
395        let struc = SimpleTestStruct {
396            a: 1,
397            b: 2,
398        };
399        let v = DBusEncoder::encode(&struc).ok().unwrap();
400        let expected_struct = Struct {
401            objects: vec![
402                Value::BasicValue(BasicValue::Int32(1)),
403                Value::BasicValue(BasicValue::Uint64(2)),
404            ],
405            signature: Signature("(it)".to_string()),
406        };
407        assert_eq!(v, Value::Struct(expected_struct));
408    }
409
410    #[test]
411    fn test_empty_struct() {
412        let struc = EmptyTestStruct {};
413        let v = DBusEncoder::encode(&struc).ok().unwrap();
414        let expected_struct = Struct {
415            objects: vec![],
416            signature: Signature("()".to_string()),
417        };
418        assert_eq!(v, Value::Struct(expected_struct));
419    }
420
421    #[test]
422    fn test_nested_struct() {
423        let struc = NestedTestStruct {
424            x: SimpleTestStruct {
425                a: 1,
426                b: 2,
427            },
428            y: SimpleTestStruct {
429                a: 9,
430                b: 10,
431            },
432            z: EmptyTestStruct {},
433        };
434        let v = DBusEncoder::encode(&struc).ok().unwrap();
435        let inner_struct_x = Struct {
436            objects: vec![
437                Value::BasicValue(BasicValue::Int32(1)),
438                Value::BasicValue(BasicValue::Uint64(2)),
439            ],
440            signature: Signature("(it)".to_string()),
441        };
442        let inner_struct_y = Struct {
443            objects: vec![
444                Value::BasicValue(BasicValue::Int32(9)),
445                Value::BasicValue(BasicValue::Uint64(10)),
446            ],
447            signature: Signature("(it)".to_string()),
448        };
449        let inner_struct_z = Struct {
450            objects: vec![],
451            signature: Signature("()".to_string()),
452        };
453        let expected_struct = Struct {
454            objects: vec![
455                Value::Struct(inner_struct_x),
456                Value::Struct(inner_struct_y),
457                Value::Struct(inner_struct_z),
458            ],
459            signature: Signature("((it)(it)())".to_string()),
460        };
461        assert_eq!(v, Value::Struct(expected_struct));
462    }
463}