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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! A module defining serde dserialize for the format described in ser.rs
//!
//! TL;DR: How to Use
//! ================================================================================
//!
//! ```rust,ignore
//! #[derive(Deserialize)]
//! struct ExampleStruct {
//!     a: (),
//!     b: bool,
//!     c: u8,
//!     ...,
//! }
//!
//! let bytes = ...;
//! let s: ExampleStruct = pythnet_sdk::de::from_slice::<LittleEndian, _>(&bytes)?;
//! ```
//!
//! The deserialization mechanism is a bit more complex than the serialization mechanism as it
//! employs a visitor pattern. Rather than describe it here, the serde documentation on how to
//! implement a deserializer can be found here:
//!
//! https://serde.rs/impl-deserializer.html

use {
    crate::require,
    byteorder::{
        ByteOrder,
        ReadBytesExt,
    },
    serde::{
        de::{
            EnumAccess,
            MapAccess,
            SeqAccess,
            VariantAccess,
        },
        Deserialize,
    },
    std::{
        io::{
            Cursor,
            Seek,
            SeekFrom,
        },
        mem::size_of,
    },
    thiserror::Error,
};

/// Deserialize a Pyth wire-format buffer into a type.
///
/// Note that this method will not consume left-over bytes ore report errors. This is due to the
/// fact that the Pyth wire formatted is intended to allow for appending of new fields without
/// breaking backwards compatibility. As such, it is possible that a newer version of the format
/// will contain fields that are not known to the deserializer. This is not an error, and the
/// deserializer will simply ignore these fields.
pub fn from_slice<'de, B, T>(bytes: &'de [u8]) -> Result<T, DeserializerError>
where
    T: Deserialize<'de>,
    B: ByteOrder,
{
    let mut deserializer = Deserializer::<B>::new(bytes);
    T::deserialize(&mut deserializer)
}

#[derive(Debug, Error)]
pub enum DeserializerError {
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),

    #[error("invalid utf8: {0}")]
    Utf8(#[from] std::str::Utf8Error),

    #[error("this type is not supported")]
    Unsupported,

    #[error("sequence too large ({0} elements), max supported is 255")]
    SequenceTooLarge(usize),

    #[error("message: {0}")]
    Message(Box<str>),

    #[error("invalid enum variant, higher than expected variant range")]
    InvalidEnumVariant,

    #[error("eof")]
    Eof,
}

pub struct Deserializer<'de, B>
where
    B: ByteOrder,
{
    cursor: Cursor<&'de [u8]>,
    endian: std::marker::PhantomData<B>,
}

impl serde::de::Error for DeserializerError {
    fn custom<T: std::fmt::Display>(msg: T) -> Self {
        DeserializerError::Message(msg.to_string().into_boxed_str())
    }
}

impl<'de, B> Deserializer<'de, B>
where
    B: ByteOrder,
{
    pub fn new(buffer: &'de [u8]) -> Self {
        Self {
            cursor: Cursor::new(buffer),
            endian: std::marker::PhantomData,
        }
    }
}

impl<'de, B> serde::de::Deserializer<'de> for &'_ mut Deserializer<'de, B>
where
    B: ByteOrder,
{
    type Error = DeserializerError;

    fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        Err(DeserializerError::Unsupported)
    }

    fn deserialize_ignored_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        Err(DeserializerError::Unsupported)
    }

    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let value = self.cursor.read_u8().map_err(DeserializerError::from)?;
        visitor.visit_bool(value != 0)
    }

    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let value = self.cursor.read_i8().map_err(DeserializerError::from)?;
        visitor.visit_i8(value)
    }

    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let value = self
            .cursor
            .read_i16::<B>()
            .map_err(DeserializerError::from)?;

        visitor.visit_i16(value)
    }

    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let value = self
            .cursor
            .read_i32::<B>()
            .map_err(DeserializerError::from)?;

        visitor.visit_i32(value)
    }

    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let value = self
            .cursor
            .read_i64::<B>()
            .map_err(DeserializerError::from)?;

        visitor.visit_i64(value)
    }

    fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let value = self
            .cursor
            .read_i128::<B>()
            .map_err(DeserializerError::from)?;

        visitor.visit_i128(value)
    }

    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let value = self.cursor.read_u8().map_err(DeserializerError::from)?;
        visitor.visit_u8(value)
    }

    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let value = self
            .cursor
            .read_u16::<B>()
            .map_err(DeserializerError::from)?;

        visitor.visit_u16(value)
    }

    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let value = self
            .cursor
            .read_u32::<B>()
            .map_err(DeserializerError::from)?;

        visitor.visit_u32(value)
    }

    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let value = self
            .cursor
            .read_u64::<B>()
            .map_err(DeserializerError::from)?;

        visitor.visit_u64(value)
    }

    fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let value = self
            .cursor
            .read_u128::<B>()
            .map_err(DeserializerError::from)?;

        visitor.visit_u128(value)
    }

    fn deserialize_f32<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        Err(DeserializerError::Unsupported)
    }

    fn deserialize_f64<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        Err(DeserializerError::Unsupported)
    }

    fn deserialize_char<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        Err(DeserializerError::Unsupported)
    }

    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let len = self.cursor.read_u8().map_err(DeserializerError::from)? as u64;

        // We cannot use cursor read methods as they copy the data out of the internal buffer,
        // where we actually want a pointer into that buffer. So instead, we take the internal
        // representation (the underlying &[u8]) and slice it to get the data we want. We then
        // advance the cursor to simulate the read.
        //
        // Note that we do the advance first because otherwise we run into a immutable->mutable
        // borrow issue, but the reverse is fine.
        self.cursor
            .seek(SeekFrom::Current(len as i64))
            .map_err(DeserializerError::from)?;

        let buf = {
            let buf = self.cursor.get_ref();
            buf[(self.cursor.position() - len) as usize..]
                .get(..len as usize)
                .ok_or(DeserializerError::Eof)?
        };

        visitor.visit_borrowed_str(std::str::from_utf8(buf).map_err(DeserializerError::from)?)
    }

    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        self.deserialize_str(visitor)
    }

    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let len = self.cursor.read_u8().map_err(DeserializerError::from)? as u64;

        // See comment in deserialize_str for an explanation of this code.
        self.cursor
            .seek(SeekFrom::Current(len as i64))
            .map_err(DeserializerError::from)?;

        let buf = {
            let buf = self.cursor.get_ref();
            buf[(self.cursor.position() - len) as usize..]
                .get(..len as usize)
                .ok_or(DeserializerError::Eof)?
        };

        visitor.visit_borrowed_bytes(buf)
    }

    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        self.deserialize_bytes(visitor)
    }

    fn deserialize_option<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        Err(DeserializerError::Unsupported)
    }

    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_unit()
    }

    fn deserialize_unit_struct<V>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_unit()
    }

    fn deserialize_newtype_struct<V>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_newtype_struct(self)
    }

    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let len = self.cursor.read_u8().map_err(DeserializerError::from)? as usize;
        visitor.visit_seq(SequenceIterator::new(self, len))
    }

    fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_seq(SequenceIterator::new(self, len))
    }

    fn deserialize_tuple_struct<V>(
        self,
        _name: &'static str,
        len: usize,
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_seq(SequenceIterator::new(self, len))
    }

    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let len = self.cursor.read_u8().map_err(DeserializerError::from)? as usize;
        visitor.visit_map(SequenceIterator::new(self, len))
    }

    fn deserialize_struct<V>(
        self,
        _name: &'static str,
        fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_seq(SequenceIterator::new(self, fields.len()))
    }

    fn deserialize_enum<V>(
        self,
        _name: &'static str,
        variants: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        // We read the discriminator here so that we can make the expected enum variant available
        // to the `visit_enum` call.
        let variant = self.cursor.read_u8().map_err(DeserializerError::from)?;
        if variant >= variants.len() as u8 {
            return Err(DeserializerError::InvalidEnumVariant);
        }

        visitor.visit_enum(Enum { de: self, variant })
    }

    fn deserialize_identifier<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        Err(DeserializerError::Unsupported)
    }
}

impl<'de, 'a, B: ByteOrder> VariantAccess<'de> for &'a mut Deserializer<'de, B> {
    type Error = DeserializerError;

    fn unit_variant(self) -> Result<(), Self::Error> {
        Ok(())
    }

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

    fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_seq(SequenceIterator::new(self, len))
    }

    fn struct_variant<V>(
        self,
        fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_seq(SequenceIterator::new(self, fields.len()))
    }
}

struct SequenceIterator<'de, 'a, B: ByteOrder> {
    de:  &'a mut Deserializer<'de, B>,
    len: usize,
}

impl<'de, 'a, B: ByteOrder> SequenceIterator<'de, 'a, B> {
    fn new(de: &'a mut Deserializer<'de, B>, len: usize) -> Self {
        Self { de, len }
    }
}

impl<'de, 'a, B: ByteOrder> SeqAccess<'de> for SequenceIterator<'de, 'a, B> {
    type Error = DeserializerError;

    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
    where
        T: serde::de::DeserializeSeed<'de>,
    {
        if self.len == 0 {
            return Ok(None);
        }

        self.len -= 1;
        seed.deserialize(&mut *self.de).map(Some)
    }

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

impl<'de, 'a, B: ByteOrder> MapAccess<'de> for SequenceIterator<'de, 'a, B> {
    type Error = DeserializerError;

    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
    where
        K: serde::de::DeserializeSeed<'de>,
    {
        if self.len == 0 {
            return Ok(None);
        }

        self.len -= 1;
        seed.deserialize(&mut *self.de).map(Some)
    }

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

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

struct Enum<'de, 'a, B: ByteOrder> {
    de:      &'a mut Deserializer<'de, B>,
    variant: u8,
}

impl<'de, 'a, B: ByteOrder> EnumAccess<'de> for Enum<'de, 'a, B> {
    type Error = DeserializerError;
    type Variant = &'a mut Deserializer<'de, B>;

    fn variant_seed<V>(self, _: V) -> Result<(V::Value, Self::Variant), Self::Error>
    where
        V: serde::de::DeserializeSeed<'de>,
    {
        // When serializing/deserializing, serde passes a variant_index into the handlers. We
        // currently write these as u8's and have already parsed' them during deserialize_enum
        // before we reach this point.
        //
        // Normally, when deserializing enum tags from a wire format that does not match the
        // expected size, we would use a u*.into_deserializer() to feed the already parsed
        // result into the visit_u64 visitor method during `__Field` deserialize.
        //
        // The problem with this however is during `visit_u64`, there is a possibility the
        // enum variant is not valid, which triggers Serde to return an `Unexpected` error.
        // These errors have the unfortunate side effect of triggering Rust including float
        // operations in the resulting binary, which breaks WASM environments.
        //
        // To work around this, we rely on the following facts:
        //
        // - variant_index in Serde is always 0 indexed and contiguous
        // - transmute_copy into a 0 sized type is safe
        // - transmute_copy is safe to cast into __Field as long as u8 >= size_of::<__Field>()
        //
        // This behaviour relies on serde not changing its enum deserializer generation, but
        // this would be a major backwards compatibility break for them so we should be safe.
        require!(
            size_of::<u8>() >= size_of::<V::Value>(),
            DeserializerError::InvalidEnumVariant
        );

        Ok((
            unsafe { std::mem::transmute_copy::<u8, V::Value>(&self.variant) },
            self.de,
        ))
    }
}