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
#[macro_export]
macro_rules! _probor_enum_pattern {
    ($name:ident $variant:ident) => {
        $name::$variant
    };
    ($name:ident $variant:ident $($fname:ident)* ) => {
        $name::$variant ( $(ref $fname),*)
    };
}

#[macro_export]
macro_rules! _probor_pattern {
    ($x:pat) => { $x }
}

#[macro_export]
macro_rules! _probor_encode_pos_enum_field {
    ($encoder:expr, $idx:expr, $field:ident, $n:tt) => {
        _probor_skip_to!($encoder, $idx, $n);
        try!($crate::Encodable::encode($field, $encoder));
    };
}

#[macro_export]
macro_rules! _probor_decode_variant {
   ($typ:ident, $dec:expr, $len:expr, $variant:ident) => {{
        // Must read the array so that cbor data is not broken
        // also help backward compatibility of data
        for _ in 1..$len {
            try!($dec.skip().map_err(|e|
                    $crate::DecodeError::SkippingError(e)));
        }
        $typ::$variant
   }};
   ($typ:ident, $dec:expr, $len: expr, $variant:ident,
    $( $fname:ident $fnum:tt ),+) => {{
        $(
            let mut $fname = None;
        )*
        for idx in 1..$len {
            match idx {
                $(
                    _probor_pattern!($fnum) => {
                        // TODO(tailhook) may be we need to support
                        //                decoding Option as well
                        $fname = Some(try!(
                            $crate::Decode::decode_elem($dec, idx)));
                    }
                )*
                _ => try!($dec.skip().map_err(|e|
                    $crate::DecodeError::SkippingError(e))),
            }
        }
        $(
            let $fname = try!($fname.ok_or(
                $crate::DecodeError::AbsentField(
                    stringify!(#$fnum))));
        )*
        $typ::$variant( $( $fname ),* )
    }};
}

#[macro_export]
macro_rules! _probor_decode_enum {
    ($dec:expr, $len:expr, $name:ident { $(
        #$n:tt $variant:ident ( $($fname:ident #$fnum:tt),* ),
    )* }) => {{
        if $len < 1 {
            return Err($crate::DecodeError::WrongValue("array too short"));
        }
        enum Kind {
            $( $variant, )*
        }
        let variant = match $dec.u64() {
            $(
                Ok(_probor_pattern!($n)) => Kind::$variant,
            )*
            Ok(_) => return Err($crate::DecodeError::WrongValue(
                "unknown enum variant")),
            Err($crate::_cbor::DecodeError::UnexpectedType {
                datatype: $crate::_cbor::types::Type::Text, info: inf }) => {
                let txt = try!(String::from_utf8(
                    // TODO(tailhook) use limit from config
                    try!($dec.kernel().raw_data(inf, 1 << 31)
                    .map_err(|e| $crate::DecodeError::WrongType(
                        "int or text expected as enum kind", e))))
                    .map_err(|_| $crate::DecodeError::WrongValue(
                        "enum variant is not correct utf8")));
                match &txt[..] {
                    $(
                        stringify!($variant) => Kind::$variant,
                    )*
                    _ => return Err($crate::DecodeError::WrongValue(
                        "unknown enum variant")),
                }
            }
            Err(e) => {
                return Err($crate::DecodeError::WrongType(
                    "array expected", e));
            }
        };
        match variant {
            $(
                Kind::$variant => {
                    Ok(Some(
                        _probor_decode_variant!($name, $dec, $len, $variant
                            $(, $fname $fnum)*)
                    ))
                }
            )*
        }
    }}
}

#[macro_export]
macro_rules! probor_enum_encoder_decoder {
    ($name:ident { $(
        #$n:tt $variant:ident ( $($fname:ident #$fnum:tt),* ),
    )* }) => {
        impl $crate::Encodable for $name {
            fn encode<W: $crate::Output>(&self,
                e: &mut $crate::_cbor::Encoder<W>)
                -> Result<(), $crate::_cbor::EncodeError>
            {
                match self {
                    $(
                        &_probor_enum_pattern!($name $variant $($fname)* ) => {
                            try!(e.array(_probor_max!( $($fnum,)* ) + 1));
                            let mut idx = 0; // hope this can be optimized out
                            try!(e.u64($n));
                            $(
                                _probor_encode_pos_enum_field!(
                                    e, idx, $fname, $fnum);
                            )*
                            (idx += 1, idx); // silence warnings
                        },
                    )*
                }
                Ok(())
            }
        }
        impl $crate::Decodable for $name {
            fn decode_opt<R: $crate::Input>(
                d: &mut $crate::_cbor::Decoder<R>)
                -> Result<Option<Self>, $crate::DecodeError>
            {
                match d.array() {
                    Ok(array_len) => {
                        _probor_decode_enum!(d, array_len, $name { $(
                            #$n $variant ( $($fname #$fnum),* ),
                        )* })
                    }
                    Err($crate::_cbor::DecodeError::UnexpectedType {
                        datatype: $crate::_cbor::types::Type::Null, .. }) => {
                        return Ok(None);
                    }
                    Err(e) => {
                        return Err($crate::DecodeError::WrongType(
                            "array or object expected (e5)", e));
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod test_enum {
    use {Encodable, Decodable, Encoder, Decoder, Config};
    use std::io::Cursor;
    use {decode};

    fn roundtrip<A:Encodable, B:Decodable>(v: &A) -> B {
        let mut e = Encoder::new(Vec::new());
        v.encode(&mut e).unwrap();
        let v = e.into_writer();
        println!("Data {:?} {:?}", String::from_utf8_lossy(&v), v);
        let mut d = &mut Decoder::new(Config::default(), Cursor::new(&v[..]));
        decode(d).unwrap()
    }

    #[derive(Debug, PartialEq)]
    enum Multi {
        One,
        Two(u32),
        Three(String, u32),
    }

    probor_enum_encoder_decoder!(Multi {
        #0 One(),
        #1 Two(x #1),
        #5 Three(x #1, y #2),
    });

    #[test]
    fn test() {
        use self::Multi::*;
        assert_eq!(roundtrip::<_, Multi>(&One), One);
        assert_eq!(roundtrip::<_, Multi>(&Two(158)), Two(158));
        assert_eq!(roundtrip::<_, Multi>(&Three("test".to_string(), 22)),
                              Three("test".to_string(), 22));
    }
}