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
use cbor::{Encoder};
use cbor::{Decoder};
use cbor::skip::{Skip};
use byteorder::{WriteBytesExt, ReadBytesExt};
use {EncodeError, DecodeError};
pub trait Output: WriteBytesExt {}
pub trait Input: ReadBytesExt + Skip {}
impl<T:WriteBytesExt> Output for T {}
impl<T:ReadBytesExt + Skip> Input for T {}
pub trait Encodable {
fn encode<W: Output>(&self, e: &mut Encoder<W>)
-> Result<(), EncodeError>;
}
pub trait Decodable: Sized {
fn decode_opt<R: Input>(d: &mut Decoder<R>)
-> Result<Option<Self>, DecodeError>;
}
pub trait Decode: Sized {
fn decode_elem<R:Input>(d: &mut Decoder<R>, n: usize)
-> Result<Self, DecodeError>;
fn decode_field<R:Input>(d: &mut Decoder<R>, name: &'static str)
-> Result<Self, DecodeError>;
}
impl<T:Decodable> Decode for T {
fn decode_elem<R:Input>(d: &mut Decoder<R>, n: usize)
-> Result<Self, DecodeError>
{
match T::decode_opt(d) {
Ok(Some(x)) => Ok(x),
Ok(None) => Err(DecodeError::BadArrayElement(n,
Box::new(DecodeError::UnexpectedNull))),
Err(e) => Err(DecodeError::BadArrayElement(n, Box::new(e))),
}
}
fn decode_field<R:Input>(d: &mut Decoder<R>, name: &'static str)
-> Result<Self, DecodeError>
{
match T::decode_opt(d) {
Ok(Some(x)) => Ok(x),
Ok(None) => Err(DecodeError::BadFieldValue(name,
Box::new(DecodeError::UnexpectedNull))),
Err(e) => Err(DecodeError::BadFieldValue(name, Box::new(e))),
}
}
}
pub fn decode<R:Input, T:Decodable>(d: &mut Decoder<R>) -> Result<T, DecodeError>
{
match T::decode_opt(d) {
Ok(Some(x)) => Ok(x),
Ok(None) => Err(DecodeError::UnexpectedNull),
Err(e) => Err(e)
}
}