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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
use super::data_type::{decode_field_for_data_type, DataType, DataTypeDecodeError};
use crate::record::{Record, Value};
use minicbor::{
    data::{Tag, Type},
    decode::Probe,
    Decoder,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use thiserror::Error;
use uuid::Uuid;

/// The SchemaField enum combines both the primitive data types with a "nested" type that indicates
/// a nested map in the schema.
///
/// The type is separate from [`DataType`] to support Serde's untagged unions.
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
#[serde(untagged)]
pub enum SchemaField {
    DataType(DataType),
    Nested(HashMap<String, SchemaField>),
}

impl From<DataType> for SchemaField {
    fn from(t: DataType) -> Self {
        Self::DataType(t)
    }
}

impl SchemaField {
    /// Indicate that a certain type can't be decoded in to the current SchemaField
    fn as_decode_not_supported<V>(&self, from: Type) -> Result<V, RecordDecoderError> {
        Err(RecordDecoderError::DecodeNotSupported {
            from,
            to: self.clone(),
        })
    }
}

#[derive(Error, Debug)]
pub enum RecordDecoderError {
    #[error("{0}")]
    CborDecode(minicbor::decode::Error),
    #[error("Type {from} cannot be decoded into {:?}", .to)]
    DecodeNotSupported { from: Type, to: SchemaField },
    #[error("Failed to decode field: {0}")]
    FieldDecode(#[from] DataTypeDecodeError),
    #[error("Unable to parse ID '{0}'")]
    InvalidID(String),
    #[error("{0}")]
    Other(String),
}

impl From<minicbor::decode::Error> for RecordDecoderError {
    fn from(val: minicbor::decode::Error) -> Self {
        Self::CborDecode(val)
    }
}

/// The RecordSchema is the `types` section of CipherStash's [collection schema].
/// It indicates the correct shape for records that are stored in CipherStash.
///
/// [collection schema]: https://docs.cipherstash.com/reference/schema-definition.html
#[derive(Debug, Serialize, Deserialize)]
pub struct RecordSchema {
    #[serde(flatten)]
    pub map: HashMap<String, SchemaField>,
}

impl RecordSchema {
    /// Get a specific schema field from the [`RecordSchema`]
    pub fn get(&self, key: &str) -> Option<&SchemaField> {
        self.map.get(key)
    }
}

/// A RecordDecoder can decode a record from a CBOR byte buffer based on the supplied schema.
///
/// Because not all languages have every datatype, it will perform a best-effort conversion from
/// the values inside the CBOR payload into the expected values, bailing whenever a conversion is impossible.
#[derive(Debug)]
pub struct RecordDecoder {
    pub(crate) schema: RecordSchema,
}

/// Iterate through a Minicbor map and decode the value at the current position.
///
/// The callback passed to this method must decode a value or call `skip` otherwise the map won't
/// be parsed correctly.
fn decoder_map_iter(
    d: &mut Decoder,
    mut callback: impl FnMut(&mut Decoder, &str) -> Result<(), RecordDecoderError>,
) -> Result<(), RecordDecoderError> {
    let mut len = d.map()?;

    loop {
        if let Some(0) = len {
            break;
        }

        if let Type::Break = d.datatype()? {
            d.skip()?;
            break;
        }

        len = len.map(|x| x - 1);

        if let Type::String = d.datatype()? {
            let key = d.str()?;
            callback(d, key)?;
        } else {
            // If the current type wasn't a string then the map has non-string keys.
            // In this case, just consume the current item and continue the loop.
            //
            // Skip the key:
            d.skip()?;
            // Skip the value:
            d.skip()?;
        }
    }

    Ok(())
}

impl RecordDecoder {
    /// Decode a map based on a schema from a CBOR decoder.
    ///
    /// Only call this method when the next item in the CBOR decoder is a map. Calling this when
    /// that isn't the case will return Err.
    fn decode_map_for_schema(
        schema: &HashMap<String, SchemaField>,
        d: &mut Decoder,
    ) -> Result<HashMap<String, Value>, RecordDecoderError> {
        let mut output = HashMap::new();

        decoder_map_iter(d, |d, key| {
            let key = String::from(key);

            if let Some(expected) = schema.get(&key) {
                if let Some(value) = Self::decode_for_field_type(expected, d)? {
                    output.insert(key, value);
                }
            } else {
                match d.datatype()? {
                    Type::String => {
                        // If the value wasn't in the schema, but was a string - include it anyway.
                        // This is to support field dynamic match and dynamic match since they include all
                        // string fields in the record.
                        output.insert(key, Value::String(d.str()?.into()));
                    }
                    Type::Map | Type::MapIndef => {
                        let empty_schema = HashMap::with_capacity(0);
                        // If there is a nested map that wasn't specified in the schema, traverse
                        // it to look for strings. As mentioned above, strings need to be included
                        // regardless of the schema to support (field) dynamic match.
                        output.insert(
                            key,
                            Value::Map(Self::decode_map_for_schema(&empty_schema, d)?),
                        );
                    }
                    _ => {
                        // If the value isn't inside the schema and isn't a string, don't bother trying to decode it.
                        d.skip()?;
                    }
                }
            }

            Ok(())
        })?;

        Ok(output)
    }

    fn decode_for_field_type(
        field_type: &SchemaField,
        d: &mut Decoder,
    ) -> Result<Option<Value>, RecordDecoderError> {
        // It's common in languages like JavaScript to set values to `null` or `undefined` rather than
        // omitting them. Just ignore these fields.
        if let Type::Null | Type::Undefined = d.datatype()? {
            d.skip()?;
            return Ok(None);
        }

        Ok(Some(match field_type {
            SchemaField::DataType(data_type) => decode_field_for_data_type(data_type, d)?,
            SchemaField::Nested(schema) => Value::Map(match d.datatype()? {
                Type::Map | Type::MapIndef => Self::decode_map_for_schema(schema, d)?,
                t => {
                    return field_type.as_decode_not_supported(t);
                }
            }),
        }))
    }

    /// Consume a decoder probe to extract the records id
    ///
    /// If the record doesn't have an id this method will return an error
    fn extract_id_from_probe(mut probe: Probe) -> Result<Uuid, RecordDecoderError> {
        let mut result: Option<[u8; 16]> = None;

        decoder_map_iter(&mut probe, |d, key| {
            if key == "id" {
                match d.datatype()? {
                    Type::Tag => {
                        match d.tag()? {
                            // Uint8Array (see https://www.npmjs.com/package/cbor)
                            Tag::Unassigned(64) => result.replace(
                                d.bytes()
                                    .map_err(|e| RecordDecoderError::InvalidID(format!("{}", e)))?
                                    .try_into()
                                    .map_err(|_| {
                                        RecordDecoderError::Other("ID Vector too large".into())
                                    })?,
                            ),
                            t => {
                                return Err(RecordDecoderError::Other(format!(
                                    "Unsupported ID tag type: {:?}",
                                    t
                                )))
                            }
                        }
                    }
                    Type::Array => result.replace(
                        d.array_iter::<u8>()?
                            .collect::<Result<Vec<u8>, _>>()
                            .map_err(|e| RecordDecoderError::InvalidID(e.to_string()))?
                            .as_slice()
                            .try_into()
                            .map_err(|e| {
                                RecordDecoderError::InvalidID(format!(
                                    "Array does not fit into uuid: {}",
                                    e
                                ))
                            })?,
                    ),
                    Type::Bytes => result.replace(
                        d.bytes()
                            .map_err(|e| RecordDecoderError::InvalidID(format!("{}", e)))?
                            .try_into()
                            .map_err(|e| {
                                RecordDecoderError::InvalidID(format!(
                                    "Byte buffer does not fit into uuid: {}",
                                    e
                                ))
                            })?,
                    ),
                    t => {
                        return Err(RecordDecoderError::InvalidID(format!(
                            "Unsupported id encoding: {}",
                            t
                        )))
                    }
                };
            } else {
                d.skip()?;
            }

            Ok(())
        })?;

        result
            .ok_or_else(|| RecordDecoderError::Other("Could not find id in top level map".into()))
            .map(Uuid::from_bytes)
    }

    /// Try and decode the provided bytes into a Record, based on the RecordDecoder's schema.
    pub fn decode(&self, bytes: &[u8]) -> Result<Record, RecordDecoderError> {
        let mut decoder = Decoder::new(bytes);

        let id = Self::extract_id_from_probe(decoder.probe())?;
        let fields = Self::decode_map_for_schema(&self.schema.map, &mut decoder)?;

        Ok(Record { id, fields })
    }
}

#[cfg(test)]
mod tests {
    use super::{DataType, RecordDecoder, Value};
    use ciborium::cbor;
    use ciborium::de::from_reader;

    use crate::{
        decoder::{RecordSchema, SchemaField},
        utils::{cbor_buffer, collection, record},
    };

    use serde_bytes::ByteBuf;

    fn generate_id() -> ByteBuf {
        ByteBuf::from([0; 16])
    }

    #[test]
    fn test_simple_decode_record() {
        let test_buffer = cbor_buffer!({
            "id" => generate_id(),
            "title" => "Great Movie",
            "runningTime" => 160,
            "year" => 1960
        });

        let decoder = RecordDecoder {
            schema: RecordSchema {
                map: collection! {
                    "title" => SchemaField::DataType(DataType::String),
                    "runningTime" => SchemaField::DataType(DataType::Float64),
                    "year" => SchemaField::DataType(DataType::Uint64)
                },
            },
        };

        let record = decoder
            .decode(&test_buffer)
            .expect("Failed to decode record");

        assert_eq!(
            record.get("title"),
            Some(&Value::String(String::from("Great Movie")))
        );

        assert_eq!(record.get("runningTime"), Some(&Value::Float64(160.)));

        assert_eq!(record.get("year"), Some(&Value::Uint64(1960)));
    }

    #[test]
    fn test_skip_irrelevant_schema() {
        let test_buffer = cbor_buffer!({
            "id" => generate_id(),
            "title" => "Great Movie",
            "runningTime" => 160,
            "unused" => {
                "another" => 1000,
                "field" => "wow"
            },
            "year" => 1960,
        });

        let decoder = RecordDecoder {
            schema: RecordSchema {
                map: collection! {
                    "title" => SchemaField::DataType(DataType::String),
                    "runningTime" => SchemaField::DataType(DataType::Float64),
                    "year" => SchemaField::DataType(DataType::Uint64),

                },
            },
        };

        let record = decoder
            .decode(&test_buffer)
            .expect("Failed to decode record");

        assert_eq!(
            record.get("title"),
            Some(&Value::String(String::from("Great Movie")))
        );

        assert_eq!(record.get("runningTime"), Some(&Value::Float64(160.)));

        assert_eq!(record.get("year"), Some(&Value::Uint64(1960)));

        assert_eq!(
            record.get("unused"),
            Some(&Value::Map(collection! {
                "field" => "wow"
            }))
        );
    }

    #[test]
    fn test_passes_on_missing_field() {
        let test_buffer = cbor_buffer!({

            "id" => generate_id(),
        "title" => "Great Movie",
            });

        let decoder = RecordDecoder {
            schema: RecordSchema {
                map: collection! {
                    "title" => SchemaField::DataType(DataType::String),
                    "runningTime" => SchemaField::DataType(DataType::Float64),
                    "year" => SchemaField::DataType(DataType::Uint64)
                },
            },
        };

        let record = decoder
            .decode(&test_buffer)
            .expect("Failed to decode record");

        assert_eq!(
            record.get("title"),
            Some(&Value::String(String::from("Great Movie")))
        );

        assert_eq!(record.get("runningTime"), None);

        assert_eq!(record.get("year"), None);
    }

    #[test]
    fn test_convert_float_to_int() {
        let test_buffer = cbor_buffer!({
            "id" => generate_id(),
            "float_val" => 10_f32,
        });

        let decoder = RecordDecoder {
            schema: RecordSchema {
                map: collection! {
                    "float_val" => SchemaField::DataType(DataType::Uint64)
                },
            },
        };

        let record = decoder
            .decode(&test_buffer)
            .expect("Failed to decode buffer");

        assert_eq!(record.get("float_val"), Some(&Value::Uint64(10)));
    }

    #[test]
    fn test_convert_large_int_to_float() {
        let test_buffer = cbor_buffer!({
            "id" => generate_id(),
            "float_val" => u64::MAX,
        });

        let decoder = RecordDecoder {
            schema: RecordSchema {
                map: collection! {
                    "float_val" => SchemaField::DataType(DataType::Float64)
                },
            },
        };

        let err = decoder
            .decode(&test_buffer)
            .expect_err("Conversion should fail");

        assert_eq!(
            err.to_string(),
            "Failed to decode field: Conversion failed: conversion resulted in positive overflow"
        );
    }

    #[test]
    fn test_convert_large_float_to_int() {
        let test_buffer = cbor_buffer!({
            "id" => generate_id(),
            "float_val" => 1000000000000000000000_f64,
        });

        let decoder = RecordDecoder {
            schema: RecordSchema {
                map: collection! {
                    "float_val" => SchemaField::DataType(DataType::Uint64)
                },
            },
        };

        let err = decoder
            .decode(&test_buffer)
            .expect_err("Conversion should fail");

        assert_eq!(
            err.to_string(),
            "Failed to decode field: Conversion failed: f64 doesn\'t correctly fit into u64"
        );
    }

    #[test]
    fn test_convert_fract_to_int() {
        let test_buffer = cbor_buffer!({
            "id" => generate_id(),
            "float_val" => 10.5,
        });

        let decoder = RecordDecoder {
            schema: RecordSchema {
                map: collection! {
                    "float_val" => SchemaField::DataType(DataType::Uint64)
                },
            },
        };

        let err = decoder
            .decode(&test_buffer)
            .expect_err("Conversion should fail");

        assert_eq!(
            err.to_string(),
            "Failed to decode field: Conversion failed: f64 doesn\'t correctly fit into u64"
        );
    }

    #[test]
    fn test_convert_negative_int_to_uint() {
        let test_buffer = cbor_buffer!({
            "id" => generate_id(),
            "int_val" => -1000,
        });

        let decoder = RecordDecoder {
            schema: RecordSchema {
                map: collection! {
                    "int_val" => SchemaField::DataType(DataType::Uint64)
                },
            },
        };

        let err = decoder
            .decode(&test_buffer)
            .expect_err("Conversion should fail");

        assert_eq!(
            err.to_string(),
            "Failed to decode field: Conversion failed: conversion resulted in negative overflow"
        );
    }

    #[test]
    fn test_convert_f16_to_float() {
        let mut test_buffer = vec![];

        let mut encoder = minicbor::Encoder::new(&mut test_buffer);

        encoder
            .map(2)
            .unwrap()
            .str("float_val")
            .unwrap()
            .f16(10.)
            .unwrap()
            .str("id")
            .unwrap()
            .bytes(&[0; 16])
            .unwrap();

        let decoder = RecordDecoder {
            schema: RecordSchema {
                map: collection! {
                    "float_val" => SchemaField::DataType(DataType::Float64)
                },
            },
        };

        let val = decoder
            .decode(&test_buffer)
            .expect("Failed to decode record");

        assert_eq!(val.get("float_val"), Some(&Value::Float64(10.)));
    }

    #[test]
    fn test_non_string_keys() {
        let test_buffer = cbor_buffer!({
            "id" => generate_id(),
            10_f32 => "float",
            10_u32 => "int",
            false => "bool",
            "string" => "string",
        });

        let decoder = RecordDecoder {
            schema: RecordSchema {
                map: collection! {
                    "string" => SchemaField::DataType(DataType::String)
                },
            },
        };

        let record = decoder
            .decode(&test_buffer)
            .expect("Failed to decode buffer");

        assert_eq!(record.get("string"), Some(&Value::String("string".into())));
    }

    #[test]
    fn test_include_non_specified_strings() {
        let id = generate_id();

        let test_buffer = cbor_buffer!({
            "id" => &id,
            "expected" => "first",
            "unexpected" => "second",
            "nested" => {
                "unexpected" => "third",
            }
        });

        let decoder = RecordDecoder {
            schema: RecordSchema {
                map: collection! {
                    "expected" => SchemaField::DataType(DataType::String)
                },
            },
        };

        let record = decoder
            .decode(&test_buffer)
            .expect("Failed to decode buffer");

        assert_eq!(
            record,
            record! {
                "id" => uuid::Uuid::from_bytes(id.as_slice().try_into().unwrap()),
                "expected" => "first",
                "unexpected" => "second",
                "nested" => collection! {
                    "unexpected" => "third"
                }
            }
        );
    }

    #[test]
    fn test_decode_null() {
        let mut test_buffer = vec![];

        let mut encoder = minicbor::Encoder::new(&mut test_buffer);

        encoder
            .map(3)
            .unwrap()
            .str("null")
            .unwrap()
            .null()
            .unwrap()
            .str("undefined")
            .unwrap()
            .undefined()
            .unwrap()
            .str("id")
            .unwrap()
            .bytes(&[0; 16])
            .unwrap();

        let decoder = RecordDecoder {
            schema: RecordSchema {
                map: collection! {
                    "null" => SchemaField::DataType(DataType::Float64),
                    "undefined" => SchemaField::DataType(DataType::Float64)
                },
            },
        };

        let val = decoder
            .decode(&test_buffer)
            .expect("Failed to decode record");

        assert_eq!(val.get("null"), None);
        assert_eq!(val.get("undefined"), None);
    }

    #[test]
    fn test_decode_indef_map() {
        let mut test_buffer = vec![];

        let mut encoder = minicbor::Encoder::new(&mut test_buffer);

        encoder
            .begin_map()
            .unwrap()
            .str("first")
            .unwrap()
            .str("a")
            .unwrap()
            .str("second")
            .unwrap()
            .str("b")
            .unwrap()
            .str("id")
            .unwrap()
            .bytes(&[0; 16])
            .unwrap()
            .end()
            .unwrap();

        let decoder = RecordDecoder {
            schema: RecordSchema {
                map: collection! {
                    "first" => SchemaField::DataType(DataType::String),
                    "second" => SchemaField::DataType(DataType::String)
                },
            },
        };

        let val = decoder
            .decode(&test_buffer)
            .expect("Failed to decode record");

        assert_eq!(val.get("first"), Some(&Value::String("a".into())));
        assert_eq!(val.get("second"), Some(&Value::String("b".into())));
    }

    fn create_date_decoder() -> RecordDecoder {
        RecordDecoder {
            schema: RecordSchema {
                map: collection! {
                    "date" => SchemaField::DataType(DataType::Date)
                },
            },
        }
    }

    fn create_bigint_decoder() -> RecordDecoder {
        RecordDecoder {
            schema: RecordSchema {
                map: collection! {
                    "bigint" => SchemaField::DataType(DataType::Uint64)
                },
            },
        }
    }

    #[test]
    fn test_decode_js_date() {
        // JS: { id: ArrayBuffer(16), date: new Date(2022, 0) }
        let buf =
            hex_literal::hex!("a262696450000000000000000000000000000000006464617465c11a61cdbb60");

        let decoder = create_date_decoder();

        let val = decoder.decode(&buf).unwrap();

        assert_eq!(
            val.get("date"),
            Some(&Value::date_from_millis(1640872800000))
        );
    }

    #[test]
    fn test_decode_js_date_float() {
        // JS: { id: ArrayBuffer(16), date: new Date(2022, 0, 0, 0, 0, 0, 100) }
        let buf = hex_literal::hex!(
            "a262696450000000000000000000000000000000006464617465c1fb41d8736ed8066666"
        );

        let decoder = create_date_decoder();

        let val = decoder.decode(&buf).unwrap();

        assert_eq!(
            val.get("date"),
            Some(&Value::date_from_millis(1640872800100))
        );
    }

    #[test]
    fn test_decode_js_date_neg_float() {
        // JS: { id: ArrayBuffer(16), date: new Date(0, 0, 0, 0, 0, 0, 1) }
        let buf = hex_literal::hex!(
            "a262696450000000000000000000000000000000006464617465c1fbc1e0758b93fff7cf"
        );

        let decoder = create_date_decoder();

        let val = decoder.decode(&buf).unwrap();

        assert_eq!(
            val.get("date"),
            Some(&Value::date_from_millis(-2209111199999))
        );
    }

    #[test]
    fn test_decode_js_date_neg_int() {
        // JS: { id: ArrayBuffer(16), date: new Date(0, 0, 0, 0, 0, 0, 0) }
        let buf =
            hex_literal::hex!("a262696450000000000000000000000000000000006464617465c13a83ac5c9f");

        let decoder = create_date_decoder();

        let val = decoder.decode(&buf).unwrap();

        assert_eq!(
            val.get("date"),
            Some(&Value::date_from_millis(-2209111200000))
        );
    }

    #[test]
    fn test_decode_js_bignum() {
        // JS: { id: ArrayBuffer(16), bigint: 123n }
        let buf =
            hex_literal::hex!("a2626964500000000000000000000000000000000066626967696e74c2417b");

        let decoder = create_bigint_decoder();

        let val = decoder.decode(&buf).unwrap();

        assert_eq!(val.get("bigint"), Some(&Value::Uint64(123)));
    }

    #[test]
    fn test_decode_schema() {
        let buffer = cbor_buffer!({
            "int" => "uint64",
            "float" => "float64",
            "str" => "string",
            "bool" => "boolean",
            "date" => "date",
            "nested" => { "test" => "uint64" }
        });

        let schema: RecordSchema = from_reader(&buffer[..]).expect("Failed to decode");

        assert_eq!(
            schema.get("int").unwrap(),
            &SchemaField::DataType(DataType::Uint64)
        );
        assert_eq!(
            schema.get("float").unwrap(),
            &SchemaField::DataType(DataType::Float64)
        );
        assert_eq!(
            schema.get("str").unwrap(),
            &SchemaField::DataType(DataType::String)
        );
        assert_eq!(
            schema.get("bool").unwrap(),
            &SchemaField::DataType(DataType::Boolean)
        );
        assert_eq!(
            schema.get("date").unwrap(),
            &SchemaField::DataType(DataType::Date)
        );
        assert_eq!(
            schema.get("nested").unwrap(),
            &SchemaField::Nested(collection! {
                "test" => SchemaField::DataType(DataType::Uint64)
            })
        );
    }
}