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
//! Traits and types for decoding CBOR.
//!
//! This module defines the trait [`Decode`] and the actual [`Decoder`].

mod decoder;
mod error;

pub use decoder::{Decoder, Probe};
pub use decoder::{ArrayIter, BytesIter, MapIter, StrIter};
pub use error::Error;

/// A type that can be decoded from CBOR.
pub trait Decode<'b>: Sized {
    /// Decode a value using the given `Decoder`.
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error>;
}

#[cfg(feature = "std")]
impl<'b, T: Decode<'b>> Decode<'b> for Box<T> {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        T::decode(d).map(Box::new)
    }
}

impl<'a, 'b: 'a> Decode<'b> for &'a [u8] {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        d.bytes()
    }
}

impl<'a, 'b: 'a> Decode<'b> for &'a str {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        d.str()
    }
}

#[cfg(feature = "std")]
impl<'b, T> Decode<'b> for std::borrow::Cow<'_, T>
where
    T: std::borrow::ToOwned + ?Sized,
    T::Owned: Decode<'b>
{
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        d.decode().map(std::borrow::Cow::Owned)
    }
}

#[cfg(feature = "std")]
impl<'b> Decode<'b> for String {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        d.str().map(String::from)
    }
}

impl<'b, T: Decode<'b>> Decode<'b> for Option<T> {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        if crate::data::Type::Null == d.datatype()? {
            d.skip()?;
            return Ok(None)
        }
        T::decode(d).map(Some)
    }
}

#[cfg(feature = "std")]
impl<'b, T> Decode<'b> for std::collections::BinaryHeap<T>
where
    T: Decode<'b> + Ord
{
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        let iter: ArrayIter<T> = d.array_iter()?;
        let mut v = std::collections::BinaryHeap::new();
        for x in iter {
            v.push(x?)
        }
        Ok(v)
    }
}

#[cfg(feature = "std")]
impl<'b, T> Decode<'b> for std::collections::HashSet<T>
where
    T: Decode<'b> + Eq + std::hash::Hash
{
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        let iter: ArrayIter<T> = d.array_iter()?;
        let mut v = std::collections::HashSet::new();
        for x in iter {
            v.insert(x?);
        }
        Ok(v)
    }
}

#[cfg(feature = "std")]
impl<'b, T> Decode<'b> for std::collections::BTreeSet<T>
where
    T: Decode<'b> + Ord
{
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        let iter: ArrayIter<T> = d.array_iter()?;
        let mut v = std::collections::BTreeSet::new();
        for x in iter {
            v.insert(x?);
        }
        Ok(v)
    }
}

#[cfg(feature = "std")]
impl<'b, K, V> Decode<'b> for std::collections::HashMap<K, V>
where
    K: Decode<'b> + Eq + std::hash::Hash,
    V: Decode<'b>
{
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        let mut m = std::collections::HashMap::new();
        let iter: MapIter<K, V> = d.map_iter()?;
        for x in iter {
            let (k, v) = x?;
            m.insert(k, v);
        }
        Ok(m)
    }
}

#[cfg(feature = "std")]
impl<'b, K, V> Decode<'b> for std::collections::BTreeMap<K, V>
where
    K: Decode<'b> + Eq + Ord,
    V: Decode<'b>
{
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        let mut m = std::collections::BTreeMap::new();
        let iter: MapIter<K, V> = d.map_iter()?;
        for x in iter {
            let (k, v) = x?;
            m.insert(k, v);
        }
        Ok(m)
    }
}

impl<'b, T> Decode<'b> for core::marker::PhantomData<T> {
    fn decode(_: &mut Decoder<'b>) -> Result<Self, Error> {
        Ok(core::marker::PhantomData)
    }
}

impl<'b> Decode<'b> for () {
    fn decode(_: &mut Decoder<'b>) -> Result<Self, Error> {
        Ok(())
    }
}

#[cfg(target_pointer_width = "32")]
impl<'b> Decode<'b> for usize {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        d.u32().map(|n| n as usize)
    }
}

#[cfg(target_pointer_width = "64")]
impl<'b> Decode<'b> for usize {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        d.u64().map(|n| n as usize)
    }
}

#[cfg(target_pointer_width = "32")]
impl<'b> Decode<'b> for isize {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        d.i32().map(|n| n as isize)
    }
}

#[cfg(target_pointer_width = "64")]
impl<'b> Decode<'b> for isize {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        d.i64().map(|n| n as isize)
    }
}

macro_rules! decode_basic {
    ($($t:ident)*) => {
        $(
            impl<'b> Decode<'b> for $t {
                fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
                    d.$t()
                }
            }
        )*
    }
}

decode_basic!(u8 i8 u16 i16 u32 i32 u64 i64 bool f32 f64 char);

macro_rules! decode_nonzero {
    ($($t:ty, $msg:expr)*) => {
        $(
            impl<'b> Decode<'b> for $t {
                fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
                    Ok(<$t>::new(Decode::decode(d)?).ok_or(Error::Message($msg))?)
                }
            }
        )*
    }
}

decode_nonzero! {
    core::num::NonZeroU8,  "unexpected 0 when decoding a `NonZeroU8`"
    core::num::NonZeroU16, "unexpected 0 when decoding a `NonZeroU16`"
    core::num::NonZeroU32, "unexpected 0 when decoding a `NonZeroU32`"
    core::num::NonZeroU64, "unexpected 0 when decoding a `NonZeroU64`"
    core::num::NonZeroI8,  "unexpected 0 when decoding a `NonZeroI8`"
    core::num::NonZeroI16, "unexpected 0 when decoding a `NonZeroI16`"
    core::num::NonZeroI32, "unexpected 0 when decoding a `NonZeroI32`"
    core::num::NonZeroI64, "unexpected 0 when decoding a `NonZeroI64`"
}

#[cfg(feature = "std")]
macro_rules! decode_sequential {
    ($($t:ty, $push:ident)*) => {
        $(
            impl<'b, T: Decode<'b>> Decode<'b> for $t {
                fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
                    let iter: ArrayIter<T> = d.array_iter()?;
                    let mut v = <$t>::new();
                    for x in iter {
                        v.$push(x?)
                    }
                    Ok(v)
                }
            }
        )*
    }
}

#[cfg(feature = "std")]
decode_sequential! {
    Vec<T>, push
    std::collections::VecDeque<T>, push_back
    std::collections::LinkedList<T>, push_back
}

macro_rules! decode_arrays {
    ($($n:expr)*) => {
        $(
            impl<'b, T: Decode<'b> + Default> Decode<'b> for [T; $n] {
                fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
                    let iter: ArrayIter<T> = d.array_iter()?;
                    let mut a: [T; $n] = Default::default();
                    let mut i = 0;
                    for x in iter {
                        if i >= a.len() {
                            let msg = concat!("array has more than ", $n, " elements");
                            return Err(Error::Message(msg))
                        }
                        a[i] = x?;
                        i += 1;
                    }
                    if i < a.len() {
                        let msg = concat!("array has less than ", $n, " elements");
                        return Err(Error::Message(msg))
                    }
                    Ok(a)
                }
            }
        )*
    }
}

decode_arrays!(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16);

macro_rules! decode_tuples {
    ($( $len:expr => { $($T:ident)+ } )+) => {
        $(
            impl<'b, $($T: Decode<'b>),+> Decode<'b> for ($($T,)+) {
                fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
                    let n = d.array()?;
                    if n != Some($len) {
                        return Err(Error::Message(concat!("invalid ", $len, "-tuple length")))
                    }
                    Ok(($($T::decode(d)?,)+))
                }
            }
        )+
    }
}

decode_tuples! {
    1  => { A }
    2  => { A B }
    3  => { A B C }
    4  => { A B C D }
    5  => { A B C D E }
    6  => { A B C D E F }
    7  => { A B C D E F G }
    8  => { A B C D E F G H }
    9  => { A B C D E F G H I }
    10 => { A B C D E F G H I J }
    11 => { A B C D E F G H I J K }
    12 => { A B C D E F G H I J K L }
    13 => { A B C D E F G H I J K L M }
    14 => { A B C D E F G H I J K L M N }
    15 => { A B C D E F G H I J K L M N O }
    16 => { A B C D E F G H I J K L M N O P }
}

macro_rules! decode_fields {
    ($d:ident | $($n:literal $x:ident => $t:ty ; $msg:literal)*) => {
        $(let mut $x = None;)*

        match $d.array()? {
            Some(n) => for i in 0 .. n {
                match i {
                    $($n => $x = Some(Decode::decode($d)?),)*
                    _    => $d.skip()?
                }
            }
            None => {
                let mut i = 0;
                while $d.datatype()? != crate::data::Type::Break {
                    match i {
                        $($n => $x = Some(Decode::decode($d)?),)*
                        _    => $d.skip()?
                    }
                    i += 1
                }
                $d.skip()?
            }
        }

        $(let $x = if let Some(x) = $x {
            x
        } else {
            return Err(Error::MissingValue($n, $msg))
        };)*
    }
}

impl<'b> Decode<'b> for core::time::Duration {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        decode_fields! { d |
            0 secs  => u64 ; "Duration::secs"
            1 nanos => u32 ; "Duration::nanos"
        }
        Ok(core::time::Duration::new(secs, nanos))
    }
}

#[cfg(feature = "std")]
impl<'b> Decode<'b> for std::net::IpAddr {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        if Some(2) != d.array()? {
            return Err(Error::Message("expected enum (2-element array)"))
        }
        match d.u32()? {
            0 => Ok(std::net::Ipv4Addr::decode(d)?.into()),
            1 => Ok(std::net::Ipv6Addr::decode(d)?.into()),
            n => Err(Error::UnknownVariant(n))
        }
    }
}

#[cfg(feature = "std")]
impl<'b> Decode<'b> for std::net::Ipv4Addr {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        let octets: [u8; 4] = Decode::decode(d)?;
        Ok(octets.into())
    }
}

#[cfg(feature = "std")]
impl<'b> Decode<'b> for std::net::Ipv6Addr {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        let octets: [u8; 16] = Decode::decode(d)?;
        Ok(octets.into())
    }
}

#[cfg(feature = "std")]
impl<'b> Decode<'b> for std::net::SocketAddr {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        if Some(2) != d.array()? {
            return Err(Error::Message("expected enum (2-element array)"))
        }
        match d.u32()? {
            0 => Ok(std::net::SocketAddrV4::decode(d)?.into()),
            1 => Ok(std::net::SocketAddrV6::decode(d)?.into()),
            n => Err(Error::UnknownVariant(n))
        }
    }
}

#[cfg(feature = "std")]
impl<'b> Decode<'b> for std::net::SocketAddrV4 {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        decode_fields! { d |
            0 ip   => std::net::Ipv4Addr ; "SocketAddrV4::ip"
            1 port => u16                ; "SocketAddrV4::port"
        }
        Ok(std::net::SocketAddrV4::new(ip, port))
    }
}

#[cfg(feature = "std")]
impl<'b> Decode<'b> for std::net::SocketAddrV6 {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Error> {
        decode_fields! { d |
            0 ip   => std::net::Ipv6Addr ; "SocketAddrV6::ip"
            1 port => u16                ; "SocketAddrV6::port"
        }
        Ok(std::net::SocketAddrV6::new(ip, port, 0, 0))
    }
}