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
//! CBOR decoding.
use std::{
    cmp::Ordering,
    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
    convert::TryInto,
};

use impl_trait_for_tuples::impl_for_tuples;

use crate::{DecodeError, SimpleValue, Value};

/// Trait for types that can be decoded from CBOR.
pub trait Decode {
    /// Try to decode from a missing/null/undefined value.
    fn try_default() -> Result<Self, DecodeError>
    where
        Self: Sized,
    {
        Err(DecodeError::MissingField)
    }

    /// Try to decode from a given CBOR value.
    fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError>
    where
        Self: Sized;

    /// Try to decode from a given CBOR value, calling `try_default` in case the value is null or
    /// undefined.
    fn try_from_cbor_value_default(value: Value) -> Result<Self, DecodeError>
    where
        Self: Sized,
    {
        match value {
            // In case of explicit null / undefined values, try to use the default value if one is
            // available (may still fail if one is not available).
            Value::Simple(SimpleValue::NullValue | SimpleValue::Undefined) => Self::try_default(),
            _ => Self::try_from_cbor_value(value),
        }
    }
}

#[impl_for_tuples(1, 10)]
impl Decode for Tuple {
    fn try_default() -> Result<Self, DecodeError> {
        Ok((for_tuples!( #( Tuple::try_default()? ),* )))
    }

    fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
        match value {
            Value::Array(mut values) => {
                Ok((for_tuples!( #( Tuple::try_from_cbor_value(values.remove(0))? ),* )))
            }
            _ => Err(DecodeError::UnexpectedType),
        }
    }
}

macro_rules! impl_uint {
    ($name:ty) => {
        impl Decode for $name {
            fn try_default() -> Result<Self, DecodeError> {
                Ok(Default::default())
            }

            fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
                match value {
                    Value::Unsigned(v) => {
                        v.try_into().map_err(|_| DecodeError::UnexpectedIntegerSize)
                    }
                    _ => Err(DecodeError::UnexpectedType),
                }
            }
        }
    };
}

macro_rules! impl_int {
    ($name:ty) => {
        impl Decode for $name {
            fn try_default() -> Result<Self, DecodeError> {
                Ok(Default::default())
            }

            fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
                match value {
                    Value::Unsigned(v) => {
                        v.try_into().map_err(|_| DecodeError::UnexpectedIntegerSize)
                    }
                    Value::Negative(v) => {
                        v.try_into().map_err(|_| DecodeError::UnexpectedIntegerSize)
                    }
                    _ => Err(DecodeError::UnexpectedType),
                }
            }
        }
    };
}

impl_uint!(u8);
impl_uint!(u16);
impl_uint!(u32);
impl_uint!(u64);
impl_int!(i8);
impl_int!(i16);
impl_int!(i32);
impl_int!(i64);

impl Decode for u128 {
    fn try_default() -> Result<Self, DecodeError> {
        Ok(Default::default())
    }

    fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
        match value {
            Value::ByteString(v) => {
                const SIZE: usize = std::mem::size_of::<u128>();

                match v.len().cmp(&SIZE) {
                    Ordering::Greater => {
                        // We only support what can be represented in u128. For all practical cases,
                        // this should be fine.
                        Err(DecodeError::UnexpectedIntegerSize)
                    }
                    Ordering::Less => {
                        // Fill any leading bytes with zeros.
                        let mut data = [0u8; SIZE];
                        data[SIZE - v.len()..].copy_from_slice(&v);
                        Ok(u128::from_be_bytes(data))
                    }
                    Ordering::Equal => {
                        // Exactly the right size.
                        Ok(u128::from_be_bytes(v.try_into().unwrap()))
                    }
                }
            }
            _ => Err(DecodeError::UnexpectedType),
        }
    }
}

impl Decode for bool {
    fn try_default() -> Result<Self, DecodeError> {
        Ok(Default::default())
    }

    fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
        match value {
            Value::Simple(SimpleValue::FalseValue) => Ok(false),
            Value::Simple(SimpleValue::TrueValue) => Ok(true),
            _ => Err(DecodeError::UnexpectedType),
        }
    }
}

impl Decode for String {
    fn try_default() -> Result<Self, DecodeError> {
        Ok(Default::default())
    }

    fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
        match value {
            Value::TextString(v) => Ok(v),
            _ => Err(DecodeError::UnexpectedType),
        }
    }
}

impl Decode for char {
    fn try_default() -> Result<Self, DecodeError> {
        Ok(Default::default())
    }

    fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
        match value {
            Value::Unsigned(n) if n <= (u32::MAX as u64) => {
                char::from_u32(n as u32).ok_or(DecodeError::UnexpectedType)
            }
            _ => Err(DecodeError::UnexpectedType),
        }
    }
}

impl<T: Decode> Decode for Vec<T> {
    default fn try_default() -> Result<Self, DecodeError> {
        Ok(Default::default())
    }

    default fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
        match value {
            Value::Array(v) => v.into_iter().map(T::try_from_cbor_value).collect(),
            _ => Err(DecodeError::UnexpectedType),
        }
    }
}

impl Decode for Vec<u8> {
    fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
        match value {
            Value::ByteString(v) => Ok(v),
            _ => Err(DecodeError::UnexpectedType),
        }
    }
}

impl<T: Decode, const N: usize> Decode for [T; N] {
    default fn try_default() -> Result<Self, DecodeError> {
        Err(DecodeError::MissingField)
    }

    default fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
        match value {
            Value::Array(v) => v
                .into_iter()
                .map(T::try_from_cbor_value)
                .collect::<Result<Vec<_>, _>>()?
                .try_into()
                .map_err(|_| DecodeError::UnexpectedType),
            _ => Err(DecodeError::UnexpectedType),
        }
    }
}

impl<const N: usize> Decode for [u8; N] {
    fn try_default() -> Result<Self, DecodeError> {
        Ok([0u8; N])
    }

    fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
        match value {
            Value::ByteString(v) => v.try_into().map_err(|_| DecodeError::UnexpectedType),
            _ => Err(DecodeError::UnexpectedType),
        }
    }
}

impl<T: Decode> Decode for Option<T> {
    fn try_default() -> Result<Self, DecodeError> {
        Ok(Default::default())
    }

    fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
        match value {
            Value::Simple(SimpleValue::NullValue) => Ok(None),
            _ => Ok(Some(T::try_from_cbor_value(value)?)),
        }
    }
}

impl Decode for Value {
    fn try_default() -> Result<Self, DecodeError> {
        Ok(Value::Simple(SimpleValue::NullValue))
    }

    fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
        Ok(value)
    }
}

impl<K: Decode + Ord, V: Decode> Decode for BTreeMap<K, V> {
    fn try_default() -> Result<Self, DecodeError> {
        Ok(Default::default())
    }

    fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
        match value {
            Value::Map(v) => {
                let result: Result<Vec<_>, DecodeError> = v
                    .into_iter()
                    .map(|(k, v)| Ok((K::try_from_cbor_value(k)?, V::try_from_cbor_value(v)?)))
                    .collect();
                Ok(result?.into_iter().collect())
            }
            _ => Err(DecodeError::UnexpectedType),
        }
    }
}

impl<T: Decode + Ord> Decode for BTreeSet<T> {
    fn try_default() -> Result<Self, DecodeError> {
        Ok(Default::default())
    }

    fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
        match value {
            Value::Array(v) => v.into_iter().map(T::try_from_cbor_value).collect(),
            _ => Err(DecodeError::UnexpectedType),
        }
    }
}

impl<K: Decode + Eq + std::hash::Hash, V: Decode> Decode for HashMap<K, V> {
    fn try_default() -> Result<Self, DecodeError> {
        Ok(Default::default())
    }

    fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
        match value {
            Value::Map(v) => {
                let result: Result<Vec<_>, DecodeError> = v
                    .into_iter()
                    .map(|(k, v)| Ok((K::try_from_cbor_value(k)?, V::try_from_cbor_value(v)?)))
                    .collect();
                Ok(result?.into_iter().collect())
            }
            _ => Err(DecodeError::UnexpectedType),
        }
    }
}

impl<T: Decode + Eq + std::hash::Hash> Decode for HashSet<T> {
    fn try_default() -> Result<Self, DecodeError> {
        Ok(Default::default())
    }

    fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
        match value {
            Value::Array(v) => v.into_iter().map(T::try_from_cbor_value).collect(),
            _ => Err(DecodeError::UnexpectedType),
        }
    }
}

impl Decode for () {
    fn try_default() -> Result<Self, DecodeError> {
        Ok(())
    }

    fn try_from_cbor_value(value: Value) -> Result<Self, DecodeError> {
        match value {
            Value::Simple(SimpleValue::NullValue) => Ok(()),
            Value::Simple(SimpleValue::Undefined) => Ok(()),
            _ => Err(DecodeError::UnexpectedType),
        }
    }
}