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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
use crate::{Error, RESPType, Result};

use serde::de::{self, DeserializeOwned, DeserializeSeed, SeqAccess, Visitor};
use serde::Deserialize;

use std::fmt;
use std::io::{BufRead, BufReader, Cursor, Read};

/// Deserializer for RESP format
pub struct Deserializer<'de, R: BufRead> {
    reader: &'de mut R,
}

impl<'de, R: BufRead> Deserializer<'de, R> {
    /// Method for building Deserializer
    pub fn from_buf_reader(reader: &'de mut R) -> Deserializer<'de, R> {
        Deserializer { reader }
    }
}

/// Deserialize from str.
///
/// This function simple wraps the `&str` with `Cursor` and calls [from_buf_reader](from_buf_reader).
///
/// # Errors
/// Please refer to [Error](Error)
pub fn from_str<T>(s: &str) -> Result<T>
where
    T: DeserializeOwned,
{
    let mut reader = Cursor::new(s);
    from_buf_reader(&mut reader)
}

/// Deserialize from reader with `Read` trait.
///
/// This function simply wraps the reader with a `BufReader` and calls [from_buf_reader](from_buf_reader).
/// If your reader has `BufRead` trait, use [from_buf_reader](from_buf_reader) instead.
///
/// # Errors
/// Please refer to [Error](Error)
pub fn from_reader<T, R>(reader: &mut R) -> Result<T>
where
    T: DeserializeOwned,
    R: Read,
{
    let mut reader = BufReader::new(reader);
    from_buf_reader(&mut reader)
}

/// Deserialize from reader with `BufRead` trait.
///
/// # Errors
/// Please refer to [Error](Error)
pub fn from_buf_reader<T, R>(reader: &mut R) -> Result<T>
where
    T: DeserializeOwned,
    R: BufRead,
{
    let mut deserializer = Deserializer::from_buf_reader(reader);
    let t = T::deserialize(&mut deserializer)?;
    Ok(t)
}

impl<'de, R: BufRead> Deserializer<'de, R> {
    // read until LF, trim end, and parse to isize.
    fn read_isize(&mut self) -> Result<isize> {
        let mut buffer = String::new();
        self.reader.read_line(&mut buffer)?;
        let trimmed = buffer.trim_end();
        match trimmed.parse::<isize>() {
            Ok(x) => Ok(x),
            Err(_) => Err(Error::Syntax),
        }
    }
}

impl<'de, 'a, R: BufRead> de::Deserializer<'de> for &'a mut Deserializer<'de, R> {
    type Error = Error;

    // You see, this is a bit hacky...
    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        let mut buf = [0u8; 1];
        self.reader.read_exact(&mut buf)?;
        match buf[0] {
            b'+' => self.deserialize_str(visitor),      // SimpleString
            b'-' => self.deserialize_string(visitor),   // Error
            b':' => self.deserialize_i64(visitor),      // Integer
            b'$' => self.deserialize_byte_buf(visitor), // BulkString
            b'*' => self.deserialize_seq(visitor),      // Array
            _ => return Err(Error::Syntax),
        }
    }

    fn deserialize_bool<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_i8<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_i16<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_i32<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        let mut buffer = String::new();
        self.reader.read_line(&mut buffer)?;
        match buffer.trim_end().parse::<i64>() {
            Ok(x) => visitor.visit_i64(x),
            Err(_) => Err(Error::Syntax),
        }
    }

    fn deserialize_u8<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_u16<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_u32<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_u64<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_f32<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_f64<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_char<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    // SimpleString
    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        let mut buffer = String::new();
        self.reader.read_line(&mut buffer)?;
        visitor.visit_str(buffer.trim_end())
    }

    // Error
    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        let mut buffer = String::new();
        self.reader.read_line(&mut buffer)?;
        visitor.visit_string(buffer.trim_end().to_string())
    }

    fn deserialize_bytes<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    // BulkString
    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        let x = self.read_isize()?;
        if x < 0 {
            return visitor.visit_none();
        }
        let mut buffer = vec![0u8; (x + 2) as usize]; // also read CRLF
        self.reader.read_exact(&mut buffer)?;
        if buffer.split_off(x as usize) != b"\r\n" {
            return Err(Error::Syntax); // Not CRLF
        }
        visitor.visit_byte_buf(buffer)
    }

    fn deserialize_option<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_unit<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_unit_struct<V>(self, _name: &'static str, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_newtype_struct<V>(self, _name: &'static str, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    // Deserialization of compound types like sequences and maps happens by
    // passing the visitor an "Access" object that gives it the ability to
    // iterate through the data contained in the sequence.
    fn deserialize_seq<V>(mut self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        let x = self.read_isize()?;
        if x < 0 {
            return visitor.visit_unit();
        }
        visitor.visit_seq(RESPArray::new(&mut self, x as usize))
    }

    fn deserialize_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_tuple_struct<V>(
        self,
        _name: &'static str,
        _len: usize,
        _visitor: V,
    ) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_map<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_struct<V>(
        self,
        _name: &'static str,
        _fields: &'static [&'static str],
        _visitor: V,
    ) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_enum<V>(
        self,
        _name: &'static str,
        _variants: &'static [&'static str],
        _visitor: V,
    ) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_identifier<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_ignored_any<V>(self, _visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }
}

struct RESPArray<'a, 'de: 'a, R: BufRead> {
    de: &'a mut Deserializer<'de, R>,
    remain_len: usize,
}

impl<'a, 'de, R: BufRead> RESPArray<'a, 'de, R> {
    fn new(de: &'a mut Deserializer<'de, R>, len: usize) -> Self {
        RESPArray {
            de,
            remain_len: len,
        }
    }
}

// `SeqAccess` is provided to the `Visitor` to give it the ability to iterate
// through elements of the sequence.
impl<'de, 'a, R: BufRead> SeqAccess<'de> for RESPArray<'a, 'de, R> {
    type Error = Error;

    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
    where
        T: DeserializeSeed<'de>,
    {
        if self.remain_len == 0 {
            return Ok(None);
        }
        self.remain_len -= 1;
        seed.deserialize(&mut *self.de).map(Some)
    }

    fn size_hint(&self) -> Option<usize> {
        Some(self.remain_len)
    }
}

struct RESPTypeVisitor;

impl<'de> Visitor<'de> for RESPTypeVisitor {
    type Value = RESPType;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("A RESP value")
    }

    fn visit_i64<E>(self, v: i64) -> std::result::Result<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(RESPType::Integer(v))
    }

    // SimpleString
    fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(RESPType::SimpleString(v.to_string()))
    }

    // Error
    fn visit_string<E>(self, v: String) -> std::result::Result<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(RESPType::Error(v))
    }

    // BulkString
    fn visit_byte_buf<E>(self, v: Vec<u8>) -> std::result::Result<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(RESPType::BulkString(Some(v)))
    }

    // null BulkString
    fn visit_none<E>(self) -> std::result::Result<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(RESPType::BulkString(None))
    }

    // null Array
    fn visit_unit<E>(self) -> std::result::Result<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(RESPType::Array(None))
    }

    fn visit_seq<A>(
        self,
        mut seq: A,
    ) -> std::result::Result<Self::Value, <A as SeqAccess<'de>>::Error>
    where
        A: SeqAccess<'de>,
    {
        let mut arr: Vec<RESPType> = Vec::with_capacity(seq.size_hint().unwrap_or_default());
        loop {
            match seq.next_element()? {
                None => break,
                Some(elem) => arr.push(elem),
            };
        }
        Ok(RESPType::Array(Some(arr)))
    }
}

impl<'de> Deserialize<'de> for RESPType {
    fn deserialize<D>(
        deserializer: D,
    ) -> std::result::Result<Self, <D as de::Deserializer<'de>>::Error>
    where
        D: de::Deserializer<'de>,
    {
        deserializer.deserialize_any(RESPTypeVisitor)
    }
}