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
use self::{CborValue::*, Number::*};
use crate::{constants::*, Cbor, CborOwned, ItemKind, TaggedItem};
use std::{
borrow::Cow,
collections::{btree_map::Entry, BTreeMap},
fmt::Debug,
};
mod number;
mod timestamp;
pub use number::{Exponential, Number};
pub use timestamp::{Precision, Timestamp};
#[derive(Debug, Clone, PartialEq)]
pub enum CborValue<'a> {
Array(Vec<Cow<'a, Cbor>>),
Dict(BTreeMap<Cow<'a, Cbor>, Cow<'a, Cbor>>),
Undefined,
Null,
Bool(bool),
Number(Number<'a>),
Timestamp(Timestamp),
Str(Cow<'a, str>),
Bytes(Cow<'a, [u8]>),
Invalid,
Unknown,
}
impl<'a> CborValue<'a> {
pub fn new(item: TaggedItem<'a>) -> Self {
Self::from_item(item).unwrap_or(Invalid)
}
fn from_item(item: TaggedItem<'a>) -> Option<Self> {
match item.tags().single() {
#[cfg(feature = "rfc3339")]
Some(TAG_ISO8601) => Timestamp::from_string(item).map(Timestamp),
Some(TAG_EPOCH) => Timestamp::from_epoch(item).map(Timestamp),
Some(TAG_BIGNUM_POS | TAG_BIGNUM_NEG) => {
Some(Number(Decimal(Exponential::from_bytes(item)?)))
}
Some(TAG_BIGDECIMAL | TAG_BIGFLOAT) => Number::from_bignum(item).map(CborValue::Number),
Some(TAG_CBOR_ITEM) => {
if let ItemKind::Bytes(b) = item.kind() {
if let Some(b) = b.as_slice() {
Some(Cbor::unchecked(b).decode())
} else {
Some(CborOwned::unchecked(b.to_vec()).decode().make_static())
}
} else {
None
}
}
Some(t @ (TAG_BASE64 | TAG_BASE64URL)) => {
if let ItemKind::Str(s) = item.kind() {
let s = s.as_cow();
let b = if t == TAG_BASE64 {
base64::decode(s.as_bytes())
} else {
base64::decode_config(s.as_bytes(), base64::URL_SAFE_NO_PAD)
};
b.map(|bytes| Bytes(Cow::Owned(bytes))).ok()
} else {
None
}
}
None => Some(match item.kind() {
ItemKind::Pos(x) => Number(Int(x.into())),
ItemKind::Neg(x) => Number(Int(-1_i128 - i128::from(x))),
ItemKind::Float(f) => Number(IEEE754(f)),
ItemKind::Str(s) => Str(s.as_cow()),
ItemKind::Bytes(b) => Bytes(b.as_cow()),
ItemKind::Bool(b) => Bool(b),
ItemKind::Null => Null,
ItemKind::Undefined => Undefined,
ItemKind::Simple(_) => Unknown,
ItemKind::Array(a) => Array(a.map(Cow::Borrowed).collect()),
ItemKind::Dict(d) => Dict(d.fold(BTreeMap::new(), |mut acc, (k, v)| {
if let Entry::Vacant(e) = acc.entry(Cow::Borrowed(k)) {
e.insert(Cow::Borrowed(v));
}
acc
})),
}),
_ => Some(Unknown),
}
}
pub fn is_undefined(&self) -> bool {
matches!(self, Undefined)
}
pub fn is_null(&self) -> bool {
matches!(self, Null)
}
pub fn is_unknown(&self) -> bool {
matches!(self, Unknown)
}
pub fn is_invalid(&self) -> bool {
matches!(self, Invalid)
}
pub fn as_bool(&self) -> Option<bool> {
if let Bool(b) = self {
Some(*b)
} else {
None
}
}
pub fn as_number(&self) -> Option<&Number> {
if let Number(n) = self {
Some(n)
} else {
None
}
}
pub fn to_number(self) -> Option<Number<'a>> {
if let Number(n) = self {
Some(n)
} else {
None
}
}
pub fn as_timestamp(&self) -> Option<Timestamp> {
if let Timestamp(t) = self {
Some(*t)
} else {
None
}
}
pub fn as_str(&self) -> Option<&Cow<str>> {
if let Str(s) = self {
Some(s)
} else {
None
}
}
pub fn to_str(self) -> Option<Cow<'a, str>> {
if let Str(s) = self {
Some(s)
} else {
None
}
}
pub fn as_bytes(&self) -> Option<&Cow<[u8]>> {
if let Bytes(b) = self {
Some(b)
} else {
None
}
}
pub fn to_bytes(self) -> Option<Cow<'a, [u8]>> {
if let Bytes(b) = self {
Some(b)
} else {
None
}
}
pub fn as_array(&self) -> Option<&[Cow<'a, Cbor>]> {
if let Array(a) = self {
Some(a.as_slice())
} else {
None
}
}
pub fn to_array(self) -> Option<Vec<Cow<'a, Cbor>>> {
if let Array(a) = self {
Some(a)
} else {
None
}
}
pub fn as_dict(&self) -> Option<&BTreeMap<Cow<'a, Cbor>, Cow<'a, Cbor>>> {
if let Dict(a) = self {
Some(a)
} else {
None
}
}
pub fn to_dict(self) -> Option<BTreeMap<Cow<'a, Cbor>, Cow<'a, Cbor>>> {
if let Dict(a) = self {
Some(a)
} else {
None
}
}
pub fn make_static(self) -> CborValue<'static> {
match self {
Array(a) => Array(a.into_iter().map(ms).collect()),
Dict(d) => Dict(d.into_iter().map(|(k, v)| (ms(k), ms(v))).collect()),
Undefined => Undefined,
Null => Null,
Bool(b) => Bool(b),
Number(n) => Number(n.make_static()),
Timestamp(t) => Timestamp(t),
Str(s) => Str(ms(s)),
Bytes(b) => Bytes(ms(b)),
Invalid => Invalid,
Unknown => Unknown,
}
}
}
fn ms<'a, T: ToOwned + ?Sized + 'a>(c: Cow<'a, T>) -> Cow<'static, T> {
match c {
Cow::Borrowed(b) => Cow::Owned(b.to_owned()),
Cow::Owned(o) => Cow::Owned(o),
}
}
#[cfg(test)]
mod tests {
use crate::{
constants::*,
value::{number::Exponential, Number, Timestamp},
CborBuilder, CborOwned, CborValue, Encoder, Literal, Writer,
};
#[test]
fn display() {
fn to_cbor_str(f: f64) -> String {
format!("{}", CborBuilder::new().encode_f64(f))
}
assert_eq!(to_cbor_str(1.0), "1.0");
assert_eq!(to_cbor_str(-1.1), "-1.1");
assert_eq!(to_cbor_str(0.0), "0.0");
assert_eq!(to_cbor_str(-0.0), "-0.0");
}
#[test]
fn base64string() {
fn to_cbor(s: &str, tag: u64) -> CborOwned {
let mut v = vec![0xd8u8, tag as u8, 0x60 | (s.len() as u8)];
v.extend_from_slice(s.as_bytes());
CborOwned::unchecked(v)
}
fn b(bytes: &CborOwned) -> Vec<u8> {
if let CborValue::Bytes(bytes) = bytes.decode() {
bytes.into_owned()
} else {
panic!("no bytes: {}", bytes)
}
}
let bytes = to_cbor("a346_-0=", TAG_BASE64URL);
assert_eq!(b(&bytes), vec![107, 126, 58, 255, 237]);
let bytes = to_cbor("a346_-0", TAG_BASE64URL);
assert_eq!(b(&bytes), vec![107, 126, 58, 255, 237]);
let bytes = to_cbor("a346/+0=", TAG_BASE64);
assert_eq!(b(&bytes), vec![107, 126, 58, 255, 237]);
let bytes = to_cbor("a346/+0", TAG_BASE64);
assert_eq!(b(&bytes), vec![107, 126, 58, 255, 237]);
}
#[test]
fn tags() {
let cbor = CborBuilder::new().write_null([1, 2, 3]);
assert_eq!(cbor.tags().last(), Some(3));
assert_eq!(cbor.tags().first(), Some(1));
assert_eq!(cbor.tags().single(), None);
let cbor = CborBuilder::new().write_null([4]);
assert_eq!(cbor.tags().last(), Some(4));
assert_eq!(cbor.tags().first(), Some(4));
assert_eq!(cbor.tags().single(), Some(4));
}
#[test]
#[cfg(feature = "rfc3339")]
fn rfc3339() {
let cbor = CborBuilder::new().write_str("1983-03-22T12:17:05.345+02:00", [TAG_ISO8601]);
assert_eq!(
cbor.decode(),
CborValue::Timestamp(Timestamp::new(417176225, 345_000_000, 7200))
);
let cbor = CborBuilder::new().write_str("2183-03-22T12:17:05.345-03:00", [TAG_ISO8601]);
assert_eq!(
cbor.decode(),
CborValue::Timestamp(Timestamp::new(6728627825, 345_000_000, -10800))
);
let cbor = CborBuilder::new().write_str("1833-03-22T02:17:05.345-13:00", [TAG_ISO8601]);
assert_eq!(
cbor.decode(),
CborValue::Timestamp(Timestamp::new(-4316316175, 345_000_000, -46800))
);
}
#[test]
fn epoch() {
let cbor = CborBuilder::new().write_pos(1234567, [TAG_EPOCH]);
assert_eq!(
cbor.decode(),
CborValue::Timestamp(Timestamp::new(1234567, 0, 0))
);
let cbor = CborBuilder::new().write_neg(1234566, [TAG_EPOCH]);
assert_eq!(
cbor.decode(),
CborValue::Timestamp(Timestamp::new(-1234567, 0, 0))
);
let cbor = CborBuilder::new()
.write_lit(Literal::L8(2_345.900_000_014_5_f64.to_bits()), [TAG_EPOCH]);
assert_eq!(
cbor.decode(),
CborValue::Timestamp(Timestamp::new(2345, 900_000_015, 0))
);
let cbor = CborBuilder::new()
.write_lit(Literal::L8(2_345.900_000_015_5_f64.to_bits()), [TAG_EPOCH]);
assert_eq!(
cbor.decode(),
CborValue::Timestamp(Timestamp::new(2345, 900_000_016, 0))
);
}
#[test]
fn bignum() {
let cbor = CborBuilder::new().write_array([TAG_BIGFLOAT], |b| {
b.write_neg(2, []);
b.write_pos(13, []);
});
assert_eq!(
cbor.decode(),
CborValue::Number(Number::Float(Exponential::new(
-3,
[13_u8][..].into(),
false,
)))
);
let cbor = CborBuilder::new().write_array([TAG_BIGFLOAT], |b| {
b.write_neg(2, []);
b.write_neg(12, []);
});
assert_eq!(
cbor.decode(),
CborValue::Number(Number::Float(Exponential::new(
-3,
[12_u8][..].into(),
true,
)))
);
let cbor = CborBuilder::new().write_array([TAG_BIGFLOAT], |b| {
b.write_neg(2, []);
b.write_pos(0x010203, []);
});
assert_eq!(
cbor.decode(),
CborValue::Number(Number::Float(Exponential::new(
-3,
[1, 2, 3][..].into(),
false,
)))
);
let cbor = CborBuilder::new().write_array([TAG_BIGFLOAT], |b| {
b.write_neg(2, []);
b.write_bytes([1, 2, 3].as_ref(), [TAG_BIGNUM_POS]);
});
assert_eq!(
cbor.decode(),
CborValue::Number(Number::Float(Exponential::new(
-3,
[1, 2, 3][..].into(),
false,
)))
);
let cbor = CborBuilder::new().write_array([TAG_BIGFLOAT], |b| {
b.write_neg(2, []);
b.write_neg(0x010203, []);
});
assert_eq!(
cbor.decode(),
CborValue::Number(Number::Float(Exponential::new(
-3,
[1, 2, 3][..].into(),
true,
)))
);
let cbor = CborBuilder::new().write_array([TAG_BIGFLOAT], |b| {
b.write_neg(2, []);
b.write_bytes([1, 2, 3].as_ref(), [TAG_BIGNUM_NEG]);
});
assert_eq!(
cbor.decode(),
CborValue::Number(Number::Float(Exponential::new(
-3,
[1, 2, 3][..].into(),
true,
)))
);
let cbor = CborBuilder::new().write_array([TAG_BIGDECIMAL], |b| {
b.write_pos(2, []);
b.write_pos(0xff01020304, []);
});
assert_eq!(
cbor.decode(),
CborValue::Number(Number::Decimal(Exponential::new(
2,
[255, 1, 2, 3, 4][..].into(),
false,
)))
);
}
}