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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
use serde::de::{self, Deserialize, Deserializer, IntoDeserializer, Visitor};
use std::fmt::Display;
use std::str::Split;
// use std::iter::Peekable;

use data_encoding::{self, base64};

error_chain!{
    errors { Custom(msg: String) }

    foreign_links {
        Decoding(data_encoding::decode::Error);
    }
}

impl de::Error for Error {
    fn custom<T>(msg: T) -> Self
        where T: Display
    {
        ErrorKind::Custom(msg.to_string()).into()
    }
}

/// Deserializer for the MCF format.
pub struct McfDeserializer<'de, I: Iterator<Item = &'de str>>(I);

impl<'de> McfDeserializer<'de, Split<'de, char>> {
    /// Create a new deserializer from a string ref.
    pub fn new(input: &'de str) -> Self {
        let mut iter = input.split('$');
        iter.next();
        McfDeserializer(iter)
    }
}

/// Deserialize the generic type V from a string.
pub fn from_str<'de, V: Deserialize<'de>>(input: &'de str) -> Result<V> {
    V::deserialize(&mut McfDeserializer::new(input))
}

// Macro which will attempt to parse the input value (either self.0 or
// self.0.next()) into whichever type is used. The parsed value can then be
// deserialized by the visitor.
macro_rules! forward_parsable_to_deserialize_any {
    ($($ty:ident => $meth:ident,)*) => {
        $(
            fn $meth<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de> {
                match self.0.parse::<$ty>() {
                    Ok(val) => val.into_deserializer().$meth(visitor),
                    Err(e) => Err(de::Error::custom(e))
                }
            }
        )*
    };
    ($(iter $ty:ident => $meth:ident,)*) => {
        $(
            fn $meth<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de> {
                if let Some(v) = self.0.next() {
                    match v.parse::<$ty>() {
                        Ok(val) => val.into_deserializer().$meth(visitor),
                        Err(e) => Err(de::Error::custom(e))
                    }
                } else {

                    Err("no value found".into())
                }
            }
        )*
    }
}


impl<'a, 'de, I: Iterator<Item = &'de str>> Deserializer<'de> for &'a mut McfDeserializer<'de, I> {
    type Error = Error;

    // By default attempt to visit a string.
    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
        where V: Visitor<'de>
    {
        if let Some(k) = self.0.next() {
            visitor.visit_borrowed_str(k)
        } else {
            Err("No field to deserialize".into())
        }
    }

    // A struct is deserialized by iterating through the expected fields, and
    // returning each value one-by-one.
    fn deserialize_struct<V>(self,
                             _name: &'static str,
                             fields: &'static [&'static str],
                             visitor: V)
                             -> Result<V::Value>
        where V: Visitor<'de>
    {
        // TODO: could change this to visit_seq?
        visitor.visit_map(McfWithFields(self, fields.to_vec().into_iter()))
    }

    // Attempt to deserialize the enum by simply checking the next field for a
    // variant name.
    fn deserialize_enum<V>(self,
                           _name: &'static str,
                           _variants: &'static [&'static str],
                           visitor: V)
                           -> Result<V::Value>
        where V: Visitor<'de>
    {
        visitor.visit_enum(self)
    }

    // Deserialize the next value as an identifer.
    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value>
        where V: Visitor<'de>
    {
        if let Some(k) = self.0.next() {
            visitor.visit_borrowed_str(k)
        } else {
            Err("No field to deserialize".into())
        }
    }

    // Deserialize a byte buf by first converting the field from base64.
    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
        where V: Visitor<'de>
    {
        if let Some(v) = self.0.next() {
            visitor.visit_byte_buf(base64::decode_nopad(v.as_bytes())?)
        } else {
            Err("no value found".into())
        }
    }

    // A sequence is defined as a list of comma-separated values val1,val2,...
    // We construct a new deserializer which has already split these.
    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
        where V: Visitor<'de>
    {
        if let Some(v) = self.0.next() {
            let iter = v.split(',');
            visitor.visit_seq(&mut McfDeserializer(iter))
        } else {
            Err("no value found".into())
        }
    }

    // Deserializer a tuple by treating it as a sequence.
    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value>
        where V: Visitor<'de>
    {
        if let Some(v) = self.0.next() {
            let iter = v.split(',');
            visitor.visit_seq(&mut McfDeserializer(iter))
        } else {
            Err("no value found".into())
        }
    }

    // Deserialize a map by splitting on '=' and ',', returning each value one-
    // by-one.
    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
        where V: Visitor<'de>
    {
        if let Some(v) = self.0.next() {
            let iter = v.split(|c| c == '=' || c == ',');
            visitor.visit_map(&mut McfDeserializer(iter))
        } else {
            Err("no value found".into())
        }
    }

    // We consider a None value to be a missing value between two delimiters.
    // Anything else is deserializer as a Some value.
    //
    // This currently only works for flat options.
    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
        where V: Visitor<'de>
    {
        if let Some(v) = self.0.next() {
            match v {
                "" => visitor.visit_none(),
                v => visitor.visit_some(&mut McfDeserializer([v].iter().cloned())),
            }
        } else {
            Err("no value found".into())
        }
    }

    forward_to_deserialize_any! {
        char str
        string bytes unit unit_struct newtype_struct
        tuple_struct ignored_any
    }

    forward_parsable_to_deserialize_any! {
        iter bool => deserialize_bool,
        iter u8 => deserialize_u8,
        iter u16 => deserialize_u16,
        iter u32 => deserialize_u32,
        iter u64 => deserialize_u64,
        iter i8 => deserialize_i8,
        iter i16 => deserialize_i16,
        iter i32 => deserialize_i32,
        iter i64 => deserialize_i64,
        iter f32 => deserialize_f32,
        iter f64 => deserialize_f64,
    }
}

// This is used to deserialize any map-like object by forcing the keys to be
// whatever is returned from the iterator J.
struct McfWithFields<'a, 'de: 'a, I: 'a + Iterator<Item=&'de str>, J: Iterator<Item=&'de str>>(&'a mut McfDeserializer<'de, I>, J);

impl<'a, 'de, I: Iterator<Item = &'de str>, J: Iterator<Item = &'de str>> de::MapAccess<'de>
    for
    McfWithFields<'a, 'de, I, J> {
    type Error = Error;
    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
        where K: de::DeserializeSeed<'de>
    {
        // Take the next field from the iterator and deserialize it.
        if let Some(field) = self.1.next() {
            seed.deserialize(&mut McfDeserializer([field].iter().cloned())).map(Some)
        } else {
            Ok(None)
        }
    }

    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
        where V: de::DeserializeSeed<'de>
    {
        // Continue to deserialize from the McfDeserializer
        seed.deserialize(&mut *self.0)
    }
}

impl<'a, 'de, I: Iterator<Item = &'de str>> de::MapAccess<'de> for &'a mut McfDeserializer<'de, I> {
    type Error = Error;

    // Similar to the above, but assumes all values are being returned from a
    // single iterator/deserializer.
    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
        where K: de::DeserializeSeed<'de>
    {
        if let Some(field) = self.0.next() {
            seed.deserialize(&mut McfDeserializer([field].iter().cloned())).map(Some)
        } else {
            Ok(None)
        }
    }

    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
        where V: de::DeserializeSeed<'de>
    {
        seed.deserialize(&mut **self)
    }
}


impl<'a, 'de, I: Iterator<Item = &'de str>> de::EnumAccess<'de>
    for &'a mut McfDeserializer<'de, I> {
    type Error = Error;
    type Variant = &'a mut McfDeserializer<'de, I>;

    // Take the next value from the iterator and attept to deserialize it.
    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
        where V: de::DeserializeSeed<'de>
    {
        if let Some(value) = self.0.next() {
            let val = seed.deserialize(&mut McfDeserializer([value].iter().cloned()))?;
            Ok((val, self))
        } else {
            Err(de::Error::custom("Not enough fields"))
        }
    }
}


// `VariantAccess` is provided to the `Visitor` to give it the ability to see
// the content of the single variant that it decided to deserialize.
impl<'a, 'de, I: Iterator<Item = &'de str>> de::VariantAccess<'de>
    for
    &'a mut McfDeserializer<'de, I> {
    type Error = Error;

    fn unit_variant(self) -> Result<()> {
        // Err("expected a string".into())
        Ok(())
    }

    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>
        where T: de::DeserializeSeed<'de>
    {
        seed.deserialize(self)
    }

    // Tuple variants are represented in JSON as `{ NAME: [DATA...] }` so
    // deserialize the sequence of data here.
    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value>
        where V: Visitor<'de>
    {
        de::Deserializer::deserialize_seq(self, visitor)
    }

    // Struct variants are represented in JSON as `{ NAME: { K: V, ... } }` so
    // deserialize the inner map here.
    fn struct_variant<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value>
        where V: Visitor<'de>
    {
        de::Deserializer::deserialize_struct(self, "", fields, visitor)
    }
}

impl<'a, 'de, I: Iterator<Item = &'de str>> de::SeqAccess<'de> for &'a mut McfDeserializer<'de, I> {
    type Error = Error;
    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
        where T: de::DeserializeSeed<'de>
    {
        if let Some(v) = self.0.next() {
            seed.deserialize(&mut McfDeserializer::new(v)).map(Some)
        } else {
            Ok(None)
        }
    }
}

#[cfg(test)]
mod test {
    use serde_bytes;
    use std::collections::HashMap;

    #[test]
    fn test_deserialize() {
        #[derive(Debug, Deserialize, PartialEq)]
        struct TestStruct {
            p: u8,
            r: Option<u8>,
            params: HashMap<String, String>,
            #[serde(with="serde_bytes")]
            hash: Vec<u8>,
        }

        let mut map = HashMap::new();
        map.insert("x".to_string(), "xylo".to_string());
        map.insert("y".to_string(), "yell".to_string());
        let t = TestStruct {
            p: 12,
            r: Some(5),
            params: map,
            hash: vec![0x12, 0x23, 0x34],
        };

        let ts = "$12$5$x=xylo,y=yell$EiM0";
        assert_eq!(super::from_str::<TestStruct>(ts).unwrap(), t);

        #[derive(Debug, PartialEq, Deserialize)]
        enum TestEnum {
            First { a: u8, b: u8 },
        }

        let t = TestEnum::First { a: 38, b: 128 };

        let ts = "$First$38$128";
        assert_eq!(super::from_str::<TestEnum>(ts).unwrap(), t);
    }
}