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
// This Source Code Form is subject to the terms of
// the Mozilla Public License, v. 2.0. If a copy of
// the MPL was not distributed with this file, You
// can obtain one at http://mozilla.org/MPL/2.0/.

//! This module defines the generic `Value` AST as well as
//! several  other types to represent CBOR values.
//! A `Cursor` can be used to deconstruct and traverse
//! a `Value`.

use std::collections::{BTreeMap, LinkedList};
use std::i64;
use types::Tag;

/// The generic CBOR representation.
#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub enum Value {
    Array(Vec<Value>),
    Bool(bool),
    Break,
    Bytes(Bytes),
    F32(f32),
    F64(f64),
    I8(i8),
    I16(i16),
    I32(i32),
    I64(i64),
    Int(Int),
    Map(BTreeMap<Key, Value>),
    Null,
    Simple(Simple),
    Tagged(Tag, Box<Value>),
    Text(Text),
    U8(u8),
    U16(u16),
    U32(u32),
    U64(u64),
    Undefined
}

/// Type to represent all possible CBOR integer values.
///
/// Since the encoding of negative integers (major type 1) follows
/// unsigned integers (major type 0), mapping negative integers
/// to `i8`, `i16`, `i32` or `i64` can result in integer overflows.
/// If all possible values should be handled, this type can be used.
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum Int {
    Neg(u64),
    Pos(u64)
}

impl Int {
    pub fn from_u64(n: u64) -> Int {
        Int::Pos(n)
    }

    pub fn from_i64(n: i64) -> Int {
        if n < 0 {
            Int::Neg(i64::abs(n) as u64 - 1)
        } else {
            Int::Pos(n as u64)
        }
    }

    /// Map this value to an `i64`. If the value does not
    /// fit within `[i64::MIN, i64::MAX]`, `None` is returned instead.
    pub fn i64(&self) -> Option<i64> {
        match *self {
            Int::Neg(n) if n <= i64::MAX as u64 => Some(-1 - n as i64),
            Int::Pos(n) if n <= i64::MAX as u64 => Some(n as i64),
            _ => None
        }
    }

    /// Map this value to a `u64`. If the value is negative,
    /// `None` is returned instead.
    pub fn u64(&self) -> Option<u64> {
        match *self {
            Int::Pos(n) => Some(n),
            _           => None
        }
    }
}

/// A unification of plain and indefinitly sized strings.
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
pub enum Text {
    Text(String),
    Chunks(LinkedList<String>)
}

/// A unification of plain an indefinitly sized byte strings.
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
pub enum Bytes {
    Bytes(Vec<u8>),
    Chunks(LinkedList<Vec<u8>>)
}

/// Most simple types (e.g. `bool` are covered elsewhere) but this
/// value captures those value ranges of CBOR type `Simple` (major 7)
/// which are either not assigned or reserved.
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
pub enum Simple {
    Unassigned(u8),
    Reserved(u8)
}

/// CBOR allows heterogenous keys in objects. This enum unifies
/// all currently allowed key types.
#[derive(Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub enum Key {
    Bool(bool),
    Bytes(Bytes),
    Int(Int),
    Text(Text)
}

impl Key {
    pub fn u64(n: u64) -> Key {
        Key::Int(Int::from_u64(n))
    }

    pub fn i64(n: i64) -> Key {
        Key::Int(Int::from_i64(n))
    }
}

/// A `Cursor` allows conventient navigation in a `Value` AST.
/// `Value`s can be converted to native Rust types if possible and
/// collections can be traversed using `at` or `get`.
pub struct Cursor<'r> {
    value: Option<&'r Value>
}

impl<'r> Cursor<'r> {
    pub fn new(v: &'r Value) -> Cursor<'r> {
        Cursor { value: Some(v) }
    }

    fn of(v: Option<&'r Value>) -> Cursor<'r> {
        Cursor { value: v }
    }

    pub fn at(&self, i: usize) -> Cursor<'r> {
        match self.value {
            Some(&Value::Array(ref a)) => Cursor::of(a.get(i)),
            _                          => Cursor::of(None)
        }
    }

    pub fn get(&self, k: Key) -> Cursor<'r> {
        match self.value {
            Some(&Value::Map(ref m)) => Cursor::of(m.get(&k)),
            _                        => Cursor::of(None)
        }
    }

    pub fn field(&self, s: &str) -> Cursor<'r> {
        self.get(Key::Text(Text::Text(String::from(s))))
    }

    pub fn value(&self) -> Option<&Value> {
        self.value
    }

    pub fn opt(&self) -> Option<Cursor<'r>> {
        match self.value {
            Some(&Value::Null) => None,
            Some(ref v)        => Some(Cursor::new(v)),
            _                  => None
        }
    }

    pub fn maybe(&self) -> Option<Cursor<'r>> {
        match self.value {
            Some(&Value::Undefined) => None,
            Some(ref v)             => Some(Cursor::new(v)),
            _                       => None
        }
    }

    pub fn bool(&self) -> Option<bool> {
        match self.value {
            Some(&Value::Bool(x)) => Some(x),
            _                     => None
        }
    }

    pub fn bytes(&self) -> Option<&Bytes> {
        match self.value {
            Some(&Value::Bytes(ref x)) => Some(x),
            _                          => None
        }
    }

    pub fn bytes_plain(&self) -> Option<&Vec<u8>> {
        match self.value {
            Some(&Value::Bytes(Bytes::Bytes(ref x))) => Some(x),
            _                                        => None
        }
    }

    pub fn bytes_chunked(&self) -> Option<&LinkedList<Vec<u8>>> {
        match self.value {
            Some(&Value::Bytes(Bytes::Chunks(ref x))) => Some(x),
            _                                         => None
        }
    }

    pub fn text(&self) -> Option<&Text> {
        match self.value {
            Some(&Value::Text(ref x)) => Some(x),
            _                         => None
        }
    }

    pub fn text_plain(&self) -> Option<&String> {
        match self.value {
            Some(&Value::Text(Text::Text(ref x))) => Some(x),
            _                                     => None
        }
    }

    pub fn text_chunked(&self) -> Option<&LinkedList<String>> {
        match self.value {
            Some(&Value::Text(Text::Chunks(ref x))) => Some(x),
            _                                       => None
        }
    }

    pub fn float32(&self) -> Option<f32> {
        match self.value {
            Some(&Value::F32(x)) => Some(x),
            _                    => None
        }
    }

    pub fn float64(&self) -> Option<f64> {
        match self.value {
            Some(&Value::F64(x)) => Some(x),
            _                    => None
        }
    }

    pub fn u8(&self) -> Option<u8> {
        match self.value {
            Some(&Value::U8(x)) => Some(x),
            _                   => None
        }
    }

    pub fn u16(&self) -> Option<u16> {
        match self.value {
            Some(&Value::U16(x)) => Some(x),
            _                    => None
        }
    }

    pub fn u32(&self) -> Option<u32> {
        match self.value {
            Some(&Value::U32(x)) => Some(x),
            _                    => None
        }
    }

    pub fn u64(&self) -> Option<u64> {
        match self.value {
            Some(&Value::U64(x)) => Some(x),
            _                    => None
        }
    }

    pub fn i8(&self) -> Option<i8> {
        match self.value {
            Some(&Value::I8(x)) => Some(x),
            _                   => None
        }
    }

    pub fn i16(&self) -> Option<i16> {
        match self.value {
            Some(&Value::I16(x)) => Some(x),
            _                    => None
        }
    }

    pub fn i32(&self) -> Option<i32> {
        match self.value {
            Some(&Value::I32(x)) => Some(x),
            _                    => None
        }
    }

    pub fn i64(&self) -> Option<i64> {
        match self.value {
            Some(&Value::I64(x)) => Some(x),
            _                    => None
        }
    }
}

/// Inspect the given `Value` which must be a `Value::Tagged` and
/// ensure that the `Tag` and type of value match according to
/// RFC 7049 section 2.4
pub fn check(value: &Value) -> bool {
    fn fun(t: Tag, b: &Value) -> bool {
        match (t, b) {
            (Tag::DateTime, &Value::Text(_))        => true,
            (Tag::Timestamp, &Value::U8(_))         => true,
            (Tag::Timestamp, &Value::U16(_))        => true,
            (Tag::Timestamp, &Value::U32(_))        => true,
            (Tag::Timestamp, &Value::U64(_))        => true,
            (Tag::Timestamp, &Value::I8(_))         => true,
            (Tag::Timestamp, &Value::I16(_))        => true,
            (Tag::Timestamp, &Value::I32(_))        => true,
            (Tag::Timestamp, &Value::I64(_))        => true,
            (Tag::Timestamp, &Value::F32(_))        => true,
            (Tag::Timestamp, &Value::F64(_))        => true,
            (Tag::Bignum, &Value::Bytes(_))         => true,
            (Tag::NegativeBignum, &Value::Bytes(_)) => true,
            (Tag::ToBase64, _)                      => true,
            (Tag::ToBase64Url, _)                   => true,
            (Tag::ToBase16, _)                      => true,
            (Tag::Cbor, &Value::Bytes(_))           => true,
            (Tag::Uri, &Value::Text(_))             => true,
            (Tag::Base64, &Value::Text(_))          => true,
            (Tag::Base64Url, &Value::Text(_))       => true,
            (Tag::Regex, &Value::Text(_))           => true,
            (Tag::Mime, &Value::Text(_))            => true,
            (Tag::CborSelf, _)                      => true,
            (Tag::Decimal, &Value::Array(ref a))
            | (Tag::Bigfloat, &Value::Array(ref a)) => {
                if a.len() != 2 {
                    return false
                }
                let is_integral = |v: &Value| {
                    match *v {
                        Value::U8(_) | Value::U16(_) | Value::U32(_) | Value::U64(_) => true,
                        Value::I8(_) | Value::I16(_) | Value::I32(_) | Value::I64(_) => true,
                        _                                                            => false
                    }
                };
                let is_bignum = |v: &Value| {
                    fun(Tag::Bignum, v) || fun(Tag::NegativeBignum, v)
                };
                let ref e = a[0];
                let ref m = a[1];
                is_integral(e) && (is_integral(m) || is_bignum(m))
            }
            (Tag::Unassigned(_), _) => true,
            _                       => false
        }
    }

    match *value {
        Value::Tagged(t, ref b) => fun(t, &*b),
        _                       => false
    }
}