dbus_serialize/
decoder.rs

1//! Implements the rustc_serialize::Decoder trait
2use std;
3
4use rustc_serialize::{Decoder,Decodable};
5
6use types::{BasicValue,Value};
7
8#[derive(Debug,PartialEq)]
9pub enum DecodeError {
10    BadSignature,
11    NotSupported,
12    IntTooNarrow
13}
14
15pub struct DBusDecoder {
16    value: Value,
17    map_val: Option<Value>
18}
19
20impl DBusDecoder {
21    fn get_unsigned_int (v: &BasicValue) -> Result<u64,DecodeError> {
22        let val = match v {
23            &BasicValue::Byte(x) => x as u64,
24            &BasicValue::Uint16(x) => x as u64,
25            &BasicValue::Uint32(x) => x as u64,
26            &BasicValue::Uint64(x) => x,
27            _ => return Err(DecodeError::BadSignature)
28        };
29	Ok(val)
30    }
31
32    fn get_signed_int (v: &BasicValue) -> Result<i64,DecodeError> {
33        let val = match v {
34            &BasicValue::Int16(x) => x as i64,
35            &BasicValue::Int32(x) => x as i64,
36            &BasicValue::Int64(x) => x as i64,
37            _ => return Err(DecodeError::BadSignature)
38        };
39	Ok(val)
40    }
41
42    fn read_unsigned_int (v: &Value, max: usize) -> Result<u64,DecodeError> {
43        let basic_val = match v {
44            &Value::BasicValue(ref x) => x,
45            _ => return Err(DecodeError::BadSignature)
46        };
47
48        // Make sure the value will fit
49	let x = try!(DBusDecoder::get_unsigned_int(basic_val));
50	if x > (max as u64) {
51            return Err(DecodeError::IntTooNarrow);
52	}
53        Ok(x)
54    }
55
56    fn read_signed_int (v: &Value, max: isize, min: isize) -> Result<i64,DecodeError> {
57        let basic_val = match v {
58            &Value::BasicValue(ref x) => x,
59            _ => return Err(DecodeError::BadSignature)
60        };
61	let x = try!(DBusDecoder::get_signed_int(basic_val));
62
63        // Make sure the value will fit
64	if x > (max as i64) {
65            return Err(DecodeError::IntTooNarrow);
66	}
67	if x < (min as i64) {
68            return Err(DecodeError::IntTooNarrow);
69	}
70        Ok(x)
71    }
72
73    pub fn new (v: Value) -> DBusDecoder {
74        DBusDecoder{
75            value: v,
76            map_val: None
77        }
78    }
79
80    pub fn decode<T: Decodable>(v: Value) -> Result<T,DecodeError> {
81        let mut decoder = DBusDecoder::new(v);
82        T::decode(&mut decoder)
83    }
84}
85
86impl Decoder for DBusDecoder {
87    type Error = DecodeError;
88    
89    fn read_usize(&mut self) -> Result<usize, Self::Error> {
90        let basic_val = match &self.value {
91            &Value::BasicValue(ref x) => x,
92            _ => return Err(DecodeError::BadSignature)
93        };
94	let x = try!(DBusDecoder::get_unsigned_int(basic_val));
95        Ok(x as usize)
96    }
97    fn read_u64(&mut self) -> Result<u64, Self::Error> {
98        let val = try!(self.read_usize());
99        Ok(val as u64)
100    }
101    fn read_u32(&mut self) -> Result<u32, Self::Error> {
102        Ok(try!(DBusDecoder::read_unsigned_int(&self.value, std::u32::MAX as usize)) as u32)
103    }
104    fn read_u16(&mut self) -> Result<u16, Self::Error> {
105        Ok(try!(DBusDecoder::read_unsigned_int(&self.value, std::u16::MAX as usize)) as u16)
106    }
107    fn read_u8(&mut self) -> Result<u8, Self::Error> {
108        Ok(try!(DBusDecoder::read_unsigned_int(&self.value, std::u8::MAX as usize)) as u8)
109    }
110
111    fn read_isize(&mut self) -> Result<isize, Self::Error> {
112        let basic_val = match &self.value {
113            &Value::BasicValue(ref x) => x,
114            _ => return Err(DecodeError::BadSignature)
115        };
116	let x = try!(DBusDecoder::get_signed_int(basic_val));
117        Ok(x as isize)
118    }
119    fn read_i64(&mut self) -> Result<i64, Self::Error> {
120        let val = try!(self.read_isize());
121        Ok(val as i64)
122    }
123    fn read_i32(&mut self) -> Result<i32, Self::Error> {
124        Ok(try!(DBusDecoder::read_signed_int(&self.value, std::i32::MAX as isize, std::i32::MIN as isize)) as i32)
125    }
126    fn read_i16(&mut self) -> Result<i16, Self::Error> {
127        Ok(try!(DBusDecoder::read_signed_int(&self.value, std::i16::MAX as isize, std::i16::MIN as isize)) as i16)
128    }
129    fn read_i8(&mut self) -> Result<i8, Self::Error> {
130        Ok(try!(DBusDecoder::read_signed_int(&self.value, std::i8::MAX as isize, std::i8::MIN as isize)) as i8)
131    }
132    fn read_bool(&mut self) -> Result<bool, Self::Error> {
133        let basic_val = match &self.value {
134            &Value::BasicValue(ref x) => x,
135            _ => return Err(DecodeError::BadSignature)
136        };
137        let x = match basic_val {
138            &BasicValue::Boolean(x) => x,
139            _ => return Err(DecodeError::BadSignature)
140        };
141        Ok(x)
142    }
143    fn read_f64(&mut self) -> Result<f64, Self::Error> {
144        match &self.value {
145            &Value::Double(x) => Ok(x),
146            _ => return Err(DecodeError::BadSignature)
147        }
148    }
149    fn read_char(&mut self) -> Result<char, Self::Error> {
150        let val = try!(self.read_u8());
151        Ok(val as char)
152    }
153    fn read_str(&mut self) -> Result<String, Self::Error> {
154        let basic_val = match &self.value {
155            &Value::BasicValue(ref x) => x,
156            _ => return Err(DecodeError::BadSignature)
157        };
158        let x = match basic_val {
159            &BasicValue::String(ref x) => x.to_string(),
160            &BasicValue::ObjectPath(ref x) => x.0.to_string(),
161            &BasicValue::Signature(ref x) => x.0.to_string(),
162            _ => return Err(DecodeError::BadSignature)
163        };
164        Ok(x)
165    }
166
167    fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error> {
168        let len = match self.value {
169            Value::Array(ref x) => x.objects.len(),
170            _ => return Err(DecodeError::BadSignature)
171        };
172        f(self, len)
173    }
174    fn read_seq_elt<T, F>(&mut self, idx: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
175        let val = match self.value {
176            Value::Array(ref mut x) => {
177                x.objects.push(Value::BasicValue(BasicValue::Byte(0)));
178                x.objects.swap_remove(idx)
179            },
180            _ => return Err(DecodeError::BadSignature)
181        };
182        let mut subdecoder = DBusDecoder::new(val);
183        f(&mut subdecoder)
184    }
185
186    fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error> {
187        let len = match self.value {
188            Value::Dictionary(ref x) => x.map.keys().len(),
189            _ => return Err(DecodeError::BadSignature)
190        };
191        f(self, len)
192    }
193    fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
194        let dict = match self.value {
195            Value::Dictionary(ref mut x) => x,
196            _ => return Err(DecodeError::BadSignature)
197        };
198        let key = {
199            dict.map.keys().next().unwrap().clone()
200        };
201        self.map_val = Some(dict.map.remove(&key).unwrap());
202
203        let mut subdecoder = DBusDecoder::new(Value::BasicValue(key));
204        f(&mut subdecoder)
205    }
206    fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
207        let val = self.map_val.take().unwrap();
208        let mut subdecoder = DBusDecoder::new(val);
209        f(&mut subdecoder)
210    }
211
212    fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
213        match self.value {
214            Value::Struct(_) => (),
215            _ => return Err(DecodeError::BadSignature)
216        };
217        f(self)
218    }
219    fn read_struct_field<T, F>(&mut self, _f_name: &str, f_idx: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
220        let val = match self.value {
221            Value::Struct(ref mut x) => {
222                x.objects.push(Value::BasicValue(BasicValue::Byte(0)));
223                x.objects.swap_remove(f_idx)
224            },
225            _ => return Err(DecodeError::BadSignature)
226        };
227        let mut subdecoder = DBusDecoder::new(val);
228        f(&mut subdecoder)
229    }
230
231    fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
232        Err(DecodeError::NotSupported)
233    }
234    fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Self::Error> where F: FnMut(&mut Self, usize) -> Result<T, Self::Error> {
235        Err(DecodeError::NotSupported)
236    }
237    fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
238        Err(DecodeError::NotSupported)
239    }
240    fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Self::Error> where F: FnMut(&mut Self, usize) -> Result<T, Self::Error> {
241        Err(DecodeError::NotSupported)
242    }
243    fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
244        Err(DecodeError::NotSupported)
245    }
246    fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
247        Err(DecodeError::NotSupported)
248    }
249    fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
250        Err(DecodeError::NotSupported)
251    }
252    fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
253        Err(DecodeError::NotSupported)
254    }
255    fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> {
256        Err(DecodeError::NotSupported)
257    }
258    fn read_option<T, F>(&mut self, _f: F) -> Result<T, Self::Error> where F: FnMut(&mut Self, bool) -> Result<T, Self::Error> {
259        Err(DecodeError::NotSupported)
260    }
261    fn read_nil(&mut self) -> Result<(), Self::Error> {
262        Err(DecodeError::NotSupported)
263    }
264    fn read_f32(&mut self) -> Result<f32, Self::Error> {
265        Err(DecodeError::NotSupported)
266    }
267    fn error(&mut self, _err: &str) -> Self::Error {
268        DecodeError::NotSupported
269    }
270}
271
272#[cfg(test)]
273mod test {
274    use rustc_serialize::{Decoder,Decodable};
275    use types::{BasicValue,Value,Path,Struct,Signature,Array};
276    use decoder::*;
277
278    #[test]
279    fn test_array () {
280        let vec = vec![
281            Value::BasicValue(BasicValue::Uint32(1)),
282            Value::BasicValue(BasicValue::Uint32(2)),
283            Value::BasicValue(BasicValue::Uint32(3)),
284        ];
285        let val = Value::Array(Array::new(vec));
286        let arr : Vec<u32> = DBusDecoder::decode(val).ok().unwrap();
287        assert_eq!(vec![1,2,3], arr);
288    }
289
290    #[test]
291    fn test_int () {
292        let v = Value::BasicValue(BasicValue::Uint32(1024));
293        let i : u32 = DBusDecoder::decode(v).ok().unwrap();
294        assert_eq!(i, 1024);
295
296        let x = Value::BasicValue(BasicValue::Uint32(1024));
297        let err = DBusDecoder::decode::<u8>(x).err().unwrap();
298        assert_eq!(err, DecodeError::IntTooNarrow);
299    }
300
301    #[test]
302    fn test_string () {
303        let v = Value::BasicValue(BasicValue::String("foo".to_string()));
304        let i : String = DBusDecoder::decode(v).ok().unwrap();
305        assert_eq!(i, "foo");
306
307        let v = Value::BasicValue(BasicValue::Signature(Signature("foo".to_string())));
308        let i : String = DBusDecoder::decode(v).ok().unwrap();
309        assert_eq!(i, "foo");
310
311        let v = Value::BasicValue(BasicValue::ObjectPath(Path("foo".to_string())));
312        let i : String = DBusDecoder::decode(v).ok().unwrap();
313        assert_eq!(i, "foo");
314    }
315
316    #[derive(PartialEq,Debug)]
317    struct TestStruct {
318        foo: u8,
319        bar: u32,
320        baz: String,
321    }
322
323    impl Decodable for TestStruct {
324        fn decode<S: Decoder>(s: &mut S) -> Result<Self, S::Error> {
325            s.read_struct("TestStruct", 3, |s: &mut S| {
326                let foo = try!(s.read_struct_field("foo", 0, |s: &mut S| {
327                    s.read_u8()
328                }));
329                let bar = try!(s.read_struct_field("bar", 1, |s: &mut S| {
330                    s.read_u32()
331                }));
332                let baz = try!(s.read_struct_field("baz", 2, |s: &mut S| {
333                    s.read_str()
334                }));
335                Ok(TestStruct {
336                    foo: foo,
337                    bar: bar,
338                    baz: baz
339                })
340            })
341        }
342    }
343
344    #[test]
345    fn test_struct () {
346        let objects = vec![
347            Value::BasicValue(BasicValue::Byte(1)),
348            Value::BasicValue(BasicValue::Uint32(10)),
349            Value::BasicValue(BasicValue::String("baz".to_string()))
350        ];
351        let s = Struct {
352            objects: objects,
353            signature: Signature("(yus)".to_string())
354        };
355        let v = Value::Struct(s);
356
357        let x : TestStruct = DBusDecoder::decode(v).unwrap();
358        assert_eq!(x, TestStruct {
359            foo: 1,
360            bar: 10,
361            baz: "baz".to_string()
362        });
363    }
364}
365