rawbson 0.2.1

Blazing fast zero-copy BSON handling
Documentation
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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
/*!
A rawbson document can be created from a `Vec<u8>` containing raw BSON data, and elements
accessed via methods similar to those in the [bson-rust](https://crates.io/crate/bson-rust)
crate.  Note that rawbson returns a Result<Option<T>>, since the bytes contained in the
document are not fully validated until trying to access the contained data.

```rust
use rawbson::{
    DocBuf,
    elem,
};

// \x13\x00\x00\x00           // total document size
// \x02                       // 0x02 = type String
// hi\x00                     // field name
// \x06\x00\x00\x00y'all\x00  // field value
// \x00                       // document terminating NUL

let doc = DocBuf::new(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00".to_vec())?;
let elem: Option<elem::Element> = doc.get("hi")?;
assert_eq!(
    elem.unwrap().as_str()?,
    "y'all",
);
# Ok::<(), rawbson::RawError>(())
```

### bson-rust interop

This crate is designed to interoperate smoothly with the bson crate.

A [`DocBuf`] can be created from a [`bson::document::Document`].  Internally, this
serializes the `Document` to a `Vec<u8>`, and then includes those bytes in the [`DocBuf`].

```rust
use bson::doc;
use rawbson::{
    DocBuf,
};

let document = doc!{"goodbye": {"cruel": "world"}};
let raw = DocBuf::from_document(&document);
let value: Option<&str> = raw.get_document("goodbye")?
    .map(|doc| doc.get_str("cruel"))
    .transpose()?
    .flatten();

assert_eq!(
    value,
    Some("world"),
);
# Ok::<(), rawbson::RawError>(())
```

### Reference types

A BSON document can also be accessed with the [`Doc`] reference type,
which is an unsized type that represents the BSON payload as a `[u8]`.
This allows accessing nested documents without reallocation.  [Doc]
must always be accessed via a pointer type, similarly to `[T]` and `str`.

This type will coexist with the now deprecated [DocRef] type for at
least one minor release.

The below example constructs a bson document in a stack-based array,
and extracts a &str from it, performing no heap allocation.

```rust
use rawbson::Doc;

let bytes = b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00";
assert_eq!(Doc::new(bytes)?.get_str("hi")?, Some("y'all"));
# Ok::<(), rawbson::RawError>(())
```

### Iteration

[`Doc`] implements [`IntoIterator`](std::iter::IntoIterator), which can also
be accessed via [`DocBuf::iter`].

```rust
use bson::doc;
use rawbson::{DocBuf, elem::Element};

let doc = DocBuf::from_document(&doc! {"crate": "rawbson", "license": "MIT"});
let mut dociter = doc.iter();

let (key, value): (&str, Element) = dociter.next().unwrap()?;
assert_eq!(key, "crate");
assert_eq!(value.as_str()?, "rawbson");

let (key, value): (&str, Element) = dociter.next().unwrap()?;
assert_eq!(key, "license");
assert_eq!(value.as_str()?, "MIT");
# Ok::<(), rawbson::RawError>(())
```

### serde support

There is also serde deserialization support.

Serde serialization support is not yet provided.  For now, use
[`bson::to_document`] instead, and then serialize it out using
[`bson::Document::to_writer`] or [`DocBuf::from_document`].

```rust
use serde::Deserialize;
use bson::{doc, Document, oid::ObjectId, DateTime};
use rawbson::{DocBuf, de::from_docbuf};

#[derive(Deserialize)]
#[serde(rename_all="camelCase")]
struct User {
    #[serde(rename = "_id")]
    id: ObjectId,
    first_name: String,
    last_name: String,
    birthdate: Option<chrono::DateTime<chrono::Utc>>,
    #[serde(flatten)]
    extra: Document,
}

let doc = DocBuf::from_document(&doc!{
    "_id": ObjectId::with_string("543254325432543254325432")?,
    "firstName": "John",
    "lastName": "Doe",
    "birthdate": null,
    "luckyNumbers": [3, 60, 2147483647],
    "nickname": "Red",
});

let user: User = from_docbuf(&doc)?;
assert_eq!(user.id.to_hex(), "543254325432543254325432");
assert_eq!(user.first_name, "John");
assert_eq!(user.last_name, "Doe");
assert_eq!(user.extra.get_str("nickname")?, "Red");
assert!(user.birthdate.is_none());
# Ok::<(), Box<dyn std::error::Error>>(())
```
*/

use std::{
    borrow::Borrow,
    convert::{TryFrom, TryInto},
    ops::Deref,
};

use chrono::{DateTime, Utc};

use bson::{decimal128::Decimal128, document::ValueAccessError, oid, spec::ElementType, Bson};

pub mod de;
pub mod elem;

#[cfg(test)]
mod props;

/// Error to indicate that either a value was empty or it contained an unexpected
/// type, for use with the direct getters.
#[derive(Debug, PartialEq)]
pub enum RawError {
    /// Found a Bson value with the specified key, but not with the expected type
    UnexpectedType,

    /// The found value was not well-formed
    MalformedValue(String),

    /// Found a value where a utf-8 string was expected, but it was not valid
    /// utf-8.  The error value contains the malformed data as a string.
    Utf8EncodingError(Vec<u8>),
}

impl std::fmt::Display for RawError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        use RawError::*;
        match self {
            UnexpectedType => write!(f, "unexpected type"),
            MalformedValue(s) => write!(f, "malformed value: {:?}", s),
            Utf8EncodingError(_) => write!(f, "utf-8 encoding error"),
        }
    }
}

impl std::error::Error for RawError {}

pub type RawResult<T> = Result<T, RawError>;
type OptResult<T> = RawResult<Option<T>>;

impl<'a> From<RawError> for ValueAccessError {
    fn from(src: RawError) -> ValueAccessError {
        match src {
            RawError::UnexpectedType => ValueAccessError::UnexpectedType,
            RawError::MalformedValue(_) => ValueAccessError::UnexpectedType,
            RawError::Utf8EncodingError(_) => ValueAccessError::UnexpectedType,
        }
    }
}

impl<'a> From<ValueAccessError> for RawError {
    fn from(src: ValueAccessError) -> RawError {
        match src {
            ValueAccessError::NotPresent => unreachable!("This should be converted to an Option"),
            ValueAccessError::UnexpectedType => RawError::UnexpectedType,
            _ => RawError::UnexpectedType,
        }
    }
}

/// A BSON document, stored as raw binary data on the heap.  This can be created from
/// a `Vec<u8>` or a [`bson::Document`].
///
/// Accessing elements within the `DocBuf` is similar to element access in [bson::Document],
/// but as the contents are parsed during iteration, instead of at creation time, format
/// errors can happen at any time during use, instead of at creation time.
///
/// DocBuf can be iterated over, yielding a Result containing key-value pairs that
/// borrow from the DocBuf instead of allocating, when necessary.
///
/// ```
/// # use rawbson::{DocBuf, RawError};
/// let docbuf = DocBuf::new(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00".to_vec())?;
/// let mut iter = docbuf.iter();
/// let (key, value) = iter.next().unwrap()?;
/// assert_eq!(key, "hi");
/// assert_eq!(value.as_str(), Ok("y'all"));
/// assert!(iter.next().is_none());
/// # Ok::<(), RawError>(())
/// ```
///
/// Individual elements can be accessed using [`docbuf.get(&key)`](Doc::get), or any of
/// the `get_*` methods, like [`docbuf.get_object_id(&key)`](Doc::get_object_id), and
/// [`docbuf.get_str(&str)`](Doc::get_str).  Accessing elements is an O(N) operation,
/// as it requires iterating through the document from the beginning to find the requested
/// key.
///
/// ```
/// # use rawbson::{DocBuf, RawError};
/// let docbuf = DocBuf::new(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00".to_vec())?;
/// assert_eq!(docbuf.get_str("hi")?, Some("y'all"));
/// # Ok::<(), RawError>(())
/// ```
#[derive(Clone, Debug)]
pub struct DocBuf {
    data: Box<[u8]>,
}

impl DocBuf {
    /// Create a new `DocBuf` from the provided `Vec`.
    ///
    /// The data is checked for a declared length equal to the length of the Vec,
    /// and a trailing NUL byte.  Other validation is deferred to access time.
    ///
    /// ```
    /// # use rawbson::{DocBuf, RawError};
    /// let docbuf: DocBuf = DocBuf::new(b"\x05\0\0\0\0".to_vec())?;
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn new(data: Vec<u8>) -> RawResult<DocBuf> {
        if data.len() < 5 {
            return Err(RawError::MalformedValue("document too short".into()));
        }
        let length = i32_from_slice(&data[..4]);
        if data.len() as i32 != length {
            return Err(RawError::MalformedValue("document length incorrect".into()));
        }
        if data[data.len() - 1] != 0 {
            return Err(RawError::MalformedValue(
                "document not null-terminated".into(),
            ));
        }
        Ok(unsafe { DocBuf::new_unchecked(data) })
    }

    /// Create a DocBuf from a [bson::Document].
    ///
    /// ```
    /// # use rawbson::{DocBuf, RawError};
    /// use bson::{doc, oid};
    /// let document = doc! {
    ///     "_id": oid::ObjectId::new(),
    ///     "name": "Herman Melville",
    ///     "title": "Moby-Dick",
    /// };
    /// let docbuf: DocBuf = DocBuf::from_document(&document);
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn from_document(doc: &bson::Document) -> DocBuf {
        let mut data = Vec::new();
        doc.to_writer(&mut data).unwrap();
        unsafe { DocBuf::new_unchecked(data) }
    }

    /// Create a DocBuf from an owned Vec<u8> without performing any checks on the provided data.
    ///
    /// ```
    /// # use rawbson::{DocBuf, RawError};
    /// let docbuf: DocBuf = unsafe {
    ///     DocBuf::new_unchecked(b"\x05\0\0\0\0".to_vec())
    /// };
    /// # Ok::<(), RawError>(())
    /// ```
    ///
    /// # Safety
    ///
    /// The provided bytes must have a valid length marker, and be NUL terminated.
    pub unsafe fn new_unchecked(data: Vec<u8>) -> DocBuf {
        DocBuf {
            data: data.into_boxed_slice(),
        }
    }

    /// Return a [`&Doc`](Doc) borrowing from the data contained in self.
    ///
    /// # Deprecation
    ///
    /// DocRef is now a deprecated type alias for [Doc].  DocBuf can
    /// dereference to &Doc directly, or be converted using [AsRef::as_ref],
    /// so this function is unnecessary.
    ///
    /// ```
    /// # use rawbson::{DocBuf, DocRef, RawError};
    /// let docbuf = DocBuf::new(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00".to_vec())?;
    /// let docref: DocRef = docbuf.as_docref();
    /// # Ok::<(), RawError>(())
    /// ```
    #[deprecated(since = "0.2.0", note = "use docbuf.as_ref() instead")]
    pub fn as_docref(&self) -> &Doc {
        self.as_ref()
    }

    /// Return an iterator over the elements in the `DocBuf`, borrowing data.
    ///
    /// The associated item type is `Result<&str, Element<'_>>`.  An error is
    /// returned if data is malformed.
    ///
    /// ```
    /// # use rawbson::{elem, DocBuf, RawError};
    /// use bson::doc;
    /// let docbuf = DocBuf::from_document(&doc! { "ferris": true });
    /// for element in docbuf.iter() {
    ///     let (key, value): (&str, elem::Element) = element?;
    ///     assert_eq!(key, "ferris");
    ///     assert_eq!(value.as_bool()?, true);
    /// }
    /// # Ok::<(), RawError>(())
    /// ```
    ///
    /// # Note:
    ///
    /// There is no owning iterator for DocBuf.  If you need ownership over
    /// elements that might need to allocate, you must explicitly convert
    /// them to owned types yourself.
    pub fn iter(&self) -> DocIter<'_> {
        self.into_iter()
    }

    /// Return the contained data as a `Vec<u8>`
    ///
    /// ```
    /// # use rawbson::DocBuf;
    /// use bson::doc;
    /// let docbuf = DocBuf::from_document(&doc!{});
    /// assert_eq!(docbuf.into_inner(), b"\x05\x00\x00\x00\x00".to_vec());
    /// ```
    pub fn into_inner(self) -> Vec<u8> {
        self.data.to_vec()
    }
}

impl TryFrom<DocBuf> for bson::Document {
    type Error = RawError;

    fn try_from(rawdoc: DocBuf) -> RawResult<bson::Document> {
        bson::Document::try_from(rawdoc.as_ref())
    }
}

impl<'a> IntoIterator for &'a DocBuf {
    type IntoIter = DocIter<'a>;
    type Item = RawResult<(&'a str, elem::Element<'a>)>;

    fn into_iter(self) -> DocIter<'a> {
        DocIter {
            doc: &self,
            offset: 4,
        }
    }
}

impl AsRef<Doc> for DocBuf {
    fn as_ref(&self) -> &Doc {
        // SAFETY: Constructing the DocBuf checks the envelope validity of the BSON document.
        unsafe { Doc::new_unchecked(&self.data) }
    }
}

impl Borrow<Doc> for DocBuf {
    fn borrow(&self) -> &Doc {
        &*self
    }
}

impl ToOwned for Doc {
    type Owned = DocBuf;

    fn to_owned(&self) -> Self::Owned {
        self.to_docbuf()
    }
}

/// A BSON document, referencing raw binary data stored elsewhere.  This can be created from
/// a [DocBuf] or any type that contains valid BSON data, and can be referenced as a `[u8]`,
/// including static binary literals, [Vec<u8>](std::vec::Vec), or arrays.
///
/// Accessing elements within the `Doc` is similar to element access in [bson::Document],
/// but as the contents are parsed during iteration, instead of at creation time, format
/// errors can happen at any time during use, instead of at creation time.
///
/// Doc can be iterated over, yielding a Result containing key-value pairs that share the
/// borrow with the source bytes instead of allocating, when necessary.
///
/// ```
/// # use rawbson::{Doc, RawError};
/// let doc = Doc::new(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00")?;
/// let mut iter = doc.into_iter();
/// let (key, value) = iter.next().unwrap()?;
/// assert_eq!(key, "hi");
/// assert_eq!(value.as_str(), Ok("y'all"));
/// assert!(iter.next().is_none());
/// # Ok::<(), RawError>(())
/// ```
///
/// Individual elements can be accessed using [`doc.get(&key)`](Doc::get), or any of
/// the `get_*` methods, like [`doc.get_object_id(&key)`](Doc::get_object_id), and
/// [`doc.get_str(&str)`](Doc::get_str).  Accessing elements is an O(N) operation,
/// as it requires iterating through the document from the beginning to find the requested
/// key.
///
/// ```
/// # use rawbson::{DocBuf, RawError};
/// let docbuf = DocBuf::new(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00".to_vec())?;
/// assert_eq!(docbuf.get_str("hi")?, Some("y'all"));
/// # Ok::<(), RawError>(())
/// ```
#[derive(Debug)]
pub struct Doc {
    data: [u8],
}

impl Doc {
    pub fn new<D: AsRef<[u8]> + ?Sized>(data: &D) -> RawResult<&Doc> {
        let data = data.as_ref();
        if data.len() < 5 {
            return Err(RawError::MalformedValue("document too short".into()));
        }
        let length = i32_from_slice(&data[..4]);
        if data.len() as i32 != length {
            return Err(RawError::MalformedValue("document length incorrect".into()));
        }
        if data[data.len() - 1] != 0 {
            return Err(RawError::MalformedValue(
                "document not null-terminated".into(),
            ));
        }
        Ok(unsafe { Doc::new_unchecked(data) })
    }

    /// Create a new Doc referencing the provided data slice.
    ///
    /// # Safety
    ///
    /// The provided data must begin with a valid size
    /// and end with a NUL-terminator.
    ///
    /// ```
    /// # use rawbson::{Doc, RawError};
    /// let doc: &Doc = unsafe { Doc::new_unchecked(b"\x05\0\0\0\0") };
    /// ```
    pub unsafe fn new_unchecked<D: AsRef<[u8]> + ?Sized>(data: &D) -> &Doc {
        #[allow(unused_unsafe)]
        unsafe {
            &*(data.as_ref() as *const [u8] as *const Doc)
        }
    }

    /// Create a new DocBuf with an owned copy of the data in self.
    ///
    /// ```
    /// # use rawbson::{Doc, RawError};
    /// use rawbson::DocBuf;
    /// let data = b"\x05\0\0\0\0";
    /// let doc = Doc::new(data)?;
    /// let docbuf: DocBuf = doc.to_docbuf();
    /// # Ok::<(), RawError>(())
    pub fn to_docbuf(&self) -> DocBuf {
        // SAFETY: The validity of the data is checked by self.
        unsafe { DocBuf::new_unchecked(self.data.to_owned()) }
    }

    /// Get an element from the document.  Finding a particular key requires
    /// iterating over the document from the beginning, so this is an O(N)
    /// operation.
    ///
    /// Returns an error if the document is malformed.  Returns `Ok(None)`
    /// if the key is not found in the document.
    ///
    /// ```
    /// # use rawbson::{DocBuf, elem::Element, RawError};
    /// use bson::{doc, oid::ObjectId};
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "_id": ObjectId::new(),
    ///     "f64": 2.5,
    /// });
    /// let element = docbuf.get("f64")?.expect("finding key f64");
    /// assert_eq!(element.as_f64(), Ok(2.5));
    /// assert!(docbuf.get("unknown")?.is_none());
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get<'a>(&'a self, key: &str) -> OptResult<elem::Element<'a>> {
        for result in self.into_iter() {
            let (thiskey, bson) = result?;
            if thiskey == key {
                return Ok(Some(bson));
            }
        }
        Ok(None)
    }

    fn get_with<'a, T>(
        &'a self,
        key: &str,
        f: impl FnOnce(elem::Element<'a>) -> RawResult<T>,
    ) -> OptResult<T> {
        self.get(key)?.map(f).transpose()
    }

    /// Get an element from the document, and convert it to f64.
    ///
    /// Returns an error if the document is malformed, or if the retrieved value
    /// is not an f64.  Returns `Ok(None)` if the key is not found in the document.
    ///
    /// ```
    /// # use rawbson::{DocBuf, elem::Element, RawError};
    /// use bson::doc;
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "bool": true,
    ///     "f64": 2.5,
    /// });
    /// assert_eq!(docbuf.get_f64("f64"), Ok(Some(2.5)));
    /// assert_eq!(docbuf.get_f64("bool"), Err(RawError::UnexpectedType));
    /// assert_eq!(docbuf.get_f64("unknown"), Ok(None));
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get_f64(&self, key: &str) -> OptResult<f64> {
        self.get_with(key, elem::Element::as_f64)
    }

    /// Get an element from the document, and convert it to a &str.
    ///
    /// The returned &str is a borrowed reference into the DocBuf.  To use it
    /// beyond the lifetime of self, call to_docbuf() on it.
    ///
    /// Returns an error if the document is malformed or if the retrieved value
    /// is not a string.  Returns `Ok(None)` if the key is not found in the
    /// document.
    ///
    /// ```
    /// # use rawbson::{DocBuf, elem::Element, RawError};
    /// use bson::doc;
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "string": "hello",
    ///     "bool": true,
    /// });
    /// assert_eq!(docbuf.get_str("string"), Ok(Some("hello")));
    /// assert_eq!(docbuf.get_str("bool"), Err(RawError::UnexpectedType));
    /// assert_eq!(docbuf.get_str("unknown"), Ok(None));
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get_str<'a>(&'a self, key: &str) -> OptResult<&'a str> {
        self.get_with(key, elem::Element::as_str)
    }

    /// Get an element from the document, and convert it to a [Doc].
    ///
    /// The returned [Doc] is a borrowed reference into self.  To use it
    /// beyond the lifetime of self, call to_owned() on it.
    ///
    /// Returns an error if the document is malformed or if the retrieved value
    /// is not a document.  Returns `Ok(None)` if the key is not found in the
    /// document.
    ///
    /// ```
    /// # use rawbson::{DocBuf, elem::Element, RawError};
    /// use bson::doc;
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "doc": { "key": "value"},
    ///     "bool": true,
    /// });
    /// assert_eq!(docbuf.get_document("doc")?.expect("finding key doc").get_str("key"), Ok(Some("value")));
    /// assert_eq!(docbuf.get_document("bool").unwrap_err(), RawError::UnexpectedType);
    /// assert!(docbuf.get_document("unknown")?.is_none());
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get_document<'a>(&'a self, key: &str) -> OptResult<&'a Doc> {
        self.get_with(key, elem::Element::as_document)
    }

    /// Get an element from the document, and convert it to an [ArrayRef].
    ///
    /// The returned [ArrayRef] is a borrowed reference into the DocBuf.
    ///
    /// Returns an error if the document is malformed or if the retrieved value
    /// is not a document.  Returns `Ok(None)` if the key is not found in the
    /// document.
    ///
    /// ```
    /// # use rawbson::{DocBuf, elem::Element, RawError};
    /// use bson::doc;
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "array": [true, 3, null],
    ///     "bool": true,
    /// });
    /// let mut arriter = docbuf.get_array("array")?.expect("finding key array").into_iter();
    /// let _: bool = arriter.next().unwrap()?.as_bool()?;
    /// let _: i32 = arriter.next().unwrap()?.as_i32()?;
    /// let () = arriter.next().unwrap()?.as_null()?;
    /// assert!(arriter.next().is_none());
    /// assert!(docbuf.get_array("bool").is_err());
    /// assert!(docbuf.get_array("unknown")?.is_none());
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get_array<'a>(&'a self, key: &str) -> OptResult<&'a Array> {
        self.get_with(key, elem::Element::as_array)
    }

    /// Get an element from the document, and convert it to an [elem::RawBsonBinary].
    ///
    /// The returned [RawBsonBinary](elem::RawBsonBinary) is a borrowed reference into the DocBuf.
    ///
    /// Returns an error if the document is malformed or if the retrieved value
    /// is not binary data.  Returns `Ok(None)` if the key is not found in the
    /// document.
    ///
    /// ```
    /// # use rawbson::{DocBuf, elem, RawError};
    /// use bson::{doc, Binary, spec::BinarySubtype};
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "binary": Binary { subtype: BinarySubtype::Generic, bytes: vec![1, 2, 3] },
    ///     "bool": true,
    /// });
    /// assert_eq!(docbuf.get_binary("binary")?.map(elem::RawBsonBinary::as_bytes), Some(&[1, 2, 3][..]));
    /// assert_eq!(docbuf.get_binary("bool").unwrap_err(), RawError::UnexpectedType);
    /// assert!(docbuf.get_binary("unknown")?.is_none());
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get_binary<'a>(&'a self, key: &str) -> OptResult<elem::RawBsonBinary<'a>> {
        self.get_with(key, elem::Element::as_binary)
    }

    /// Get an element from the document, and convert it to a [bson::oid::ObjectId].
    ///
    /// Returns an error if the document is malformed or if the retrieved value
    /// is not an object ID.  Returns `Ok(None)` if the key is not found in the
    /// document.
    ///
    /// ```
    /// # use rawbson::{DocBuf, RawError};
    /// use bson::{doc, oid::ObjectId};
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "_id": ObjectId::new(),
    ///     "bool": true,
    /// });
    /// let _: ObjectId = docbuf.get_object_id("_id")?.unwrap();
    /// assert_eq!(docbuf.get_object_id("bool").unwrap_err(), RawError::UnexpectedType);
    /// assert!(docbuf.get_object_id("unknown")?.is_none());
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get_object_id(&self, key: &str) -> OptResult<oid::ObjectId> {
        self.get_with(key, elem::Element::as_object_id)
    }

    /// Get an element from the document, and convert it to a [bool].
    ///
    /// Returns an error if the document is malformed or if the retrieved value
    /// is not a boolean.  Returns `Ok(None)` if the key is not found in the
    /// document.
    ///
    /// ```
    /// # use rawbson::{DocBuf, RawError};
    /// use bson::{doc, oid::ObjectId};
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "_id": ObjectId::new(),
    ///     "bool": true,
    /// });
    /// assert!(docbuf.get_bool("bool")?.unwrap());
    /// assert_eq!(docbuf.get_bool("_id").unwrap_err(), RawError::UnexpectedType);
    /// assert!(docbuf.get_object_id("unknown")?.is_none());
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get_bool(&self, key: &str) -> OptResult<bool> {
        self.get_with(key, elem::Element::as_bool)
    }

    /// Get an element from the document, and convert it to a [chrono::DateTime].
    ///
    /// Returns an error if the document is malformed or if the retrieved value
    /// is not a boolean.  Returns `Ok(None)` if the key is not found in the
    /// document.
    ///
    /// ```
    /// # use rawbson::{DocBuf, RawError};
    /// use bson::doc;
    /// use chrono::{Utc, Datelike, TimeZone};
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "created_at": Utc.ymd(2020, 3, 15).and_hms(17, 0, 0),
    ///     "bool": true,
    /// });
    /// assert_eq!(docbuf.get_datetime("created_at")?.unwrap().year(), 2020);
    /// assert_eq!(docbuf.get_datetime("bool").unwrap_err(), RawError::UnexpectedType);
    /// assert!(docbuf.get_datetime("unknown")?.is_none());
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get_datetime(&self, key: &str) -> OptResult<DateTime<Utc>> {
        self.get_with(key, elem::Element::as_datetime)
    }

    /// Get an element from the document, and convert it to the `()` type.
    ///
    /// Returns an error if the document is malformed or if the retrieved value
    /// is not null.  Returns `Ok(None)` if the key is not found in the
    /// document.
    ///
    /// There is not much reason to use the () value, so this method mostly
    /// exists for consistency with other element types, and as a way to assert
    /// type of the element.
    /// ```
    /// # use rawbson::{DocBuf, RawError};
    /// use bson::doc;
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "null": null,
    ///     "bool": true,
    /// });
    /// docbuf.get_null("null")?.unwrap();
    /// assert_eq!(docbuf.get_null("bool").unwrap_err(), RawError::UnexpectedType);
    /// assert!(docbuf.get_null("unknown")?.is_none());
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get_null(&self, key: &str) -> OptResult<()> {
        self.get_with(key, elem::Element::as_null)
    }

    /// Get an element from the document, and convert it to an [elem::RawBsonRegex].
    ///
    /// The [RawBsonRegex](elem::RawBsonRegex) borrows data from the DocBuf.
    ///
    /// Returns an error if the document is malformed or if the retrieved value
    /// is not a regex.  Returns `Ok(None)` if the key is not found in the
    /// document.
    /// ```
    /// # use rawbson::{DocBuf, RawError, elem};
    /// use bson::{doc, Regex};
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "regex": Regex {
    ///         pattern: String::from(r"end\s*$"),
    ///         options: String::from("i"),
    ///     },
    ///     "bool": true,
    /// });
    /// assert_eq!(docbuf.get_regex("regex")?.unwrap().pattern(), r"end\s*$");
    /// assert_eq!(docbuf.get_regex("regex")?.unwrap().options(), "i");
    /// assert_eq!(docbuf.get_regex("bool").unwrap_err(), RawError::UnexpectedType);
    /// assert!(docbuf.get_regex("unknown")?.is_none());
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get_regex<'a>(&'a self, key: &str) -> OptResult<elem::RawBsonRegex<'a>> {
        self.get_with(key, elem::Element::as_regex)
    }

    /// Get an element from the document, and convert it to an &str representing the
    /// javascript element type.
    ///
    /// The &str borrows data from the DocBuf.  If you need an owned copy of the data,
    /// you should call .to_owned() on the result.
    ///
    /// Returns an error if the document is malformed or if the retrieved value
    /// is not a javascript code object.  Returns `Ok(None)` if the key is not found
    /// in the document.
    /// ```
    /// # use rawbson::{DocBuf, RawError, elem};
    /// use bson::{doc, Bson};
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "js": Bson::JavaScriptCode(String::from("console.log(\"hi y'all\");")),
    ///     "bool": true,
    /// });
    /// assert_eq!(docbuf.get_javascript("js")?, Some("console.log(\"hi y'all\");"));
    /// assert_eq!(docbuf.get_javascript("bool").unwrap_err(), RawError::UnexpectedType);
    /// assert!(docbuf.get_javascript("unknown")?.is_none());
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get_javascript<'a>(&'a self, key: &str) -> OptResult<&'a str> {
        self.get_with(key, elem::Element::as_javascript)
    }

    /// Get an element from the document, and convert it to an &str representing the
    /// symbol element type.
    ///
    /// The &str borrows data from the DocBuf.  If you need an owned copy of the data,
    /// you should call .to_owned() on the result.
    ///
    /// Returns an error if the document is malformed or if the retrieved value
    /// is not a symbol object.  Returns `Ok(None)` if the key is not found
    /// in the document.
    /// ```
    /// # use rawbson::{DocBuf, RawError, elem};
    /// use bson::{doc, Bson};
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "symbol": Bson::Symbol(String::from("internal")),
    ///     "bool": true,
    /// });
    /// assert_eq!(docbuf.get_symbol("symbol")?, Some("internal"));
    /// assert_eq!(docbuf.get_symbol("bool").unwrap_err(), RawError::UnexpectedType);
    /// assert!(docbuf.get_symbol("unknown")?.is_none());
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get_symbol<'a>(&'a self, key: &str) -> OptResult<&'a str> {
        self.get_with(key, elem::Element::as_symbol)
    }

    /// Get an element from the document, and extract the data as a javascript code with scope.
    ///
    /// The return value is a `(&str, &Doc)` where the &str represents the javascript code,
    /// and the [`&Doc`](Doc) represents the scope.  Both elements borrow data from the DocBuf.
    /// If you need an owned copy of the data, you should call [js.to_owned()](ToOwned::to_owned) on
    /// the code or [scope.to_docbuf()](Doc::to_docbuf) on the scope.
    ///
    /// Returns an error if the document is malformed or if the retrieved value
    /// is not a javascript code with scope object.  Returns `Ok(None)` if the key is not found
    /// in the document.
    /// ```
    /// # use rawbson::{DocBuf, RawError, elem};
    /// use bson::{doc, JavaScriptCodeWithScope};
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "js": JavaScriptCodeWithScope {
    ///         code: String::from("console.log(\"i:\", i);"),
    ///         scope: doc!{"i": 42},
    ///     },
    ///     "bool": true,
    /// });
    /// let (js, scope) = docbuf.get_javascript_with_scope("js")?.unwrap();
    /// assert_eq!(js, "console.log(\"i:\", i);");
    /// assert_eq!(scope.get_i32("i")?.unwrap(), 42);
    /// assert_eq!(docbuf.get_javascript_with_scope("bool").unwrap_err(), RawError::UnexpectedType);
    /// assert!(docbuf.get_javascript_with_scope("unknown")?.is_none());
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get_javascript_with_scope<'a>(&'a self, key: &str) -> OptResult<(&'a str, &'a Doc)> {
        self.get_with(key, elem::Element::as_javascript_with_scope)
    }

    /// Get an element from the document, and convert it to i32.
    ///
    /// Returns an error if the document is malformed, or if the retrieved value
    /// is not an i32.  Returns `Ok(None)` if the key is not found in the document.
    ///
    /// ```
    /// # use rawbson::{DocBuf, RawError};
    /// use bson::doc;
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "bool": true,
    ///     "i32": 1_000_000,
    /// });
    /// assert_eq!(docbuf.get_i32("i32"), Ok(Some(1_000_000)));
    /// assert_eq!(docbuf.get_i32("bool"), Err(RawError::UnexpectedType));
    /// assert_eq!(docbuf.get_i32("unknown"), Ok(None));
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get_i32(&self, key: &str) -> OptResult<i32> {
        self.get_with(key, elem::Element::as_i32)
    }

    /// Get an element from the document, and convert it to a timestamp.
    ///
    /// Returns an error if the document is malformed, or if the retrieved value
    /// is not an i32.  Returns `Ok(None)` if the key is not found in the document.
    ///
    /// ```
    /// # use rawbson::{DocBuf, elem, RawError};
    /// use bson::{doc, Timestamp};
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "bool": true,
    ///     "ts": Timestamp { time: 649876543, increment: 9 },
    /// });
    /// let timestamp = docbuf.get_timestamp("ts")?.unwrap();
    ///
    /// assert_eq!(timestamp.time(), 649876543);
    /// assert_eq!(timestamp.increment(), 9);
    /// assert_eq!(docbuf.get_timestamp("bool"), Err(RawError::UnexpectedType));
    /// assert_eq!(docbuf.get_timestamp("unknown"), Ok(None));
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get_timestamp<'a>(&'a self, key: &str) -> OptResult<elem::RawBsonTimestamp<'a>> {
        self.get_with(key, elem::Element::as_timestamp)
    }

    /// Get an element from the document, and convert it to i64.
    ///
    /// Returns an error if the document is malformed, or if the retrieved value
    /// is not an i64.  Returns `Ok(None)` if the key is not found in the document.
    ///
    /// ```
    /// # use rawbson::{DocBuf, elem::Element, RawError};
    /// use bson::doc;
    /// let docbuf = DocBuf::from_document(&doc! {
    ///     "bool": true,
    ///     "i64": 9223372036854775807_i64,
    /// });
    /// assert_eq!(docbuf.get_i64("i64"), Ok(Some(9223372036854775807)));
    /// assert_eq!(docbuf.get_i64("bool"), Err(RawError::UnexpectedType));
    /// assert_eq!(docbuf.get_i64("unknown"), Ok(None));
    /// # Ok::<(), RawError>(())
    /// ```
    pub fn get_i64(&self, key: &str) -> OptResult<i64> {
        self.get_with(key, elem::Element::as_i64)
    }

    /// Return a reference to the contained data as a `&[u8]`
    ///
    /// ```
    /// # use rawbson::DocBuf;
    /// use bson::doc;
    /// let docbuf = DocBuf::from_document(&doc!{});
    /// assert_eq!(docbuf.as_bytes(), b"\x05\x00\x00\x00\x00");
    /// ```
    pub fn as_bytes(&self) -> &[u8] {
        &self.data
    }
}

impl AsRef<Doc> for Doc {
    fn as_ref(&self) -> &Doc {
        self
    }
}

impl Deref for DocBuf {
    type Target = Doc;

    fn deref(&self) -> &Self::Target {
        // SAFETY: The validity of the data is checked when creating DocBuf.
        unsafe { Doc::new_unchecked(&self.data) }
    }
}

impl TryFrom<&Doc> for bson::Document {
    type Error = RawError;

    fn try_from(rawdoc: &Doc) -> RawResult<bson::Document> {
        rawdoc
            .into_iter()
            .map(|res| res.and_then(|(k, v)| Ok((k.to_owned(), v.try_into()?))))
            .collect()
    }
}

impl<'a> IntoIterator for &'a Doc {
    type IntoIter = DocIter<'a>;
    type Item = RawResult<(&'a str, elem::Element<'a>)>;

    fn into_iter(self) -> DocIter<'a> {
        DocIter {
            doc: self,
            offset: 4,
        }
    }
}

pub struct DocIter<'a> {
    doc: &'a Doc,
    offset: usize,
}

impl<'a> Iterator for DocIter<'a> {
    type Item = RawResult<(&'a str, elem::Element<'a>)>;

    fn next(&mut self) -> Option<RawResult<(&'a str, elem::Element<'a>)>> {
        if self.offset == self.doc.data.len() - 1 {
            if self.doc.data[self.offset] == 0 {
                // end of document marker
                return None;
            } else {
                return Some(Err(RawError::MalformedValue(
                    "document not null terminated".into(),
                )));
            }
        }
        let key = match read_nullterminated(&self.doc.data[self.offset + 1..]) {
            Ok(key) => key,
            Err(err) => return Some(Err(err)),
        };
        let valueoffset = self.offset + 1 + key.len() + 1; // type specifier + key + \0
        let element_type = match ElementType::from(self.doc.data[self.offset]) {
            Some(et) => et,
            None => {
                return Some(Err(RawError::MalformedValue(format!(
                    "invalid tag: {}",
                    self.doc.data[self.offset]
                ))))
            }
        };
        let element_size = match element_type {
            ElementType::Double => 8,
            ElementType::String => {
                let size =
                    4 + i32_from_slice(&self.doc.data[valueoffset..valueoffset + 4]) as usize;
                if self.doc.data[valueoffset + size - 1] != 0 {
                    return Some(Err(RawError::MalformedValue(
                        "string not null terminated".into(),
                    )));
                }
                size
            }
            ElementType::EmbeddedDocument => {
                let size = i32_from_slice(&self.doc.data[valueoffset..valueoffset + 4]) as usize;
                if self.doc.data[valueoffset + size - 1] != 0 {
                    return Some(Err(RawError::MalformedValue(
                        "document not null terminated".into(),
                    )));
                }
                size
            }
            ElementType::Array => {
                let size = i32_from_slice(&self.doc.data[valueoffset..valueoffset + 4]) as usize;
                if self.doc.data[valueoffset + size - 1] != 0 {
                    return Some(Err(RawError::MalformedValue(
                        "array not null terminated".into(),
                    )));
                }
                size
            }
            ElementType::Binary => {
                5 + i32_from_slice(&self.doc.data[valueoffset..valueoffset + 4]) as usize
            }
            ElementType::Undefined => 0,
            ElementType::ObjectId => 12,
            ElementType::Boolean => 1,
            ElementType::DateTime => 8,
            ElementType::Null => 0,
            ElementType::RegularExpression => {
                let regex = match read_nullterminated(&self.doc.data[valueoffset..]) {
                    Ok(regex) => regex,
                    Err(err) => return Some(Err(err)),
                };
                let options =
                    match read_nullterminated(&self.doc.data[valueoffset + regex.len() + 1..]) {
                        Ok(options) => options,
                        Err(err) => return Some(Err(err)),
                    };
                regex.len() + options.len() + 2
            }
            ElementType::DbPointer => {
                let string_size =
                    4 + i32_from_slice(&self.doc.data[valueoffset..valueoffset + 4]) as usize;
                let id_size = 12;
                if self.doc.data[valueoffset + string_size - 1] != 0 {
                    return Some(Err(RawError::MalformedValue(
                        "DBPointer string not null-terminated".into(),
                    )));
                }
                string_size + id_size
            }
            ElementType::JavaScriptCode => {
                let size =
                    4 + i32_from_slice(&self.doc.data[valueoffset..valueoffset + 4]) as usize;
                if self.doc.data[valueoffset + size - 1] != 0 {
                    return Some(Err(RawError::MalformedValue(
                        "javascript code not null-terminated".into(),
                    )));
                }
                size
            }
            ElementType::Symbol => {
                4 + i32_from_slice(&self.doc.data[valueoffset..valueoffset + 4]) as usize
            }
            ElementType::JavaScriptCodeWithScope => {
                let size = i32_from_slice(&self.doc.data[valueoffset..valueoffset + 4]) as usize;
                if self.doc.data[valueoffset + size - 1] != 0 {
                    return Some(Err(RawError::MalformedValue(
                        "javascript with scope not null-terminated".into(),
                    )));
                }
                size
            }
            ElementType::Int32 => 4,
            ElementType::Timestamp => 8,
            ElementType::Int64 => 8,
            ElementType::Decimal128 => 16,
            ElementType::MaxKey => 0,
            ElementType::MinKey => 0,
        };
        let nextoffset = valueoffset + element_size;
        self.offset = nextoffset;
        Some(Ok((
            key,
            elem::Element::new(element_type, &self.doc.data[valueoffset..nextoffset]),
        )))
    }
}

pub type ArrayRef<'a> = &'a Array;

pub struct Array {
    doc: Doc,
}

impl Array {
    pub fn new(data: &[u8]) -> RawResult<&Array> {
        Ok(Array::from_doc(Doc::new(data)?))
    }

    /// Return a new Array from the provided bytes.
    ///
    /// # Safety
    ///
    /// The provided bytes must start with a valid length indicator
    /// and end with a NUL terminator, as described in [the bson
    /// spec](http://bsonspec.org/spec.html).
    ///
    /// The following is valid:
    /// ```
    /// # use rawbson::Array;
    /// // Represents the array [null, 514i32], which is the same as the document
    /// // {"0": null, "1": 514}
    /// let bson = b"\x0f\0\0\0\x0A0\0\x101\0\x02\x02\0\0\0";
    /// let arr = unsafe { Array::new_unchecked(bson) };
    /// let mut arriter = arr.into_iter();
    /// assert!(arriter.next().unwrap().and_then(|b| b.as_null()).is_ok());
    /// assert_eq!(arriter.next().unwrap().and_then(|b| b.as_i32()).unwrap(), 514);
    /// ```
    ///
    /// And so is this, even though the provided document is not an array, because
    /// the errors will be caught during decode.
    ///
    /// ```
    /// # use rawbson::Array;
    /// // Represents the document {"0": null, "X": 514}
    /// let bson = b"\x0f\0\0\0\x0A0\0\x10X\0\x02\x02\0\0\0";
    /// let arr = unsafe { Array::new_unchecked(bson) };
    /// let mut arriter = arr.into_iter();
    /// assert!(arriter.next().unwrap().and_then(|b| b.as_null()).is_ok());
    /// assert!(arriter.next().unwrap().is_err());
    /// assert!(arriter.next().is_none());
    /// ```
    ///
    /// # Bad:
    ///
    /// The following, however, indicates the wrong size for the document, and is
    /// therefore unsound.
    ///
    /// ```
    /// # use rawbson::Array;
    /// // Contains a length indicator, that is longer than the array
    /// let invalid = b"\x06\0\0\0\0";
    /// let arr: &Array = unsafe { Array::new_unchecked(invalid) };
    /// ```
    pub unsafe fn new_unchecked(data: &[u8]) -> &Array {
        #[allow(unused_unsafe)]
        let doc = unsafe { Doc::new_unchecked(data) };
        Array::from_doc(doc)
    }

    pub fn from_doc(doc: &Doc) -> &Array {
        // SAFETY: Array layout matches Doc layout
        unsafe { &*(doc as *const Doc as *const Array) }
    }

    pub fn get(&self, index: usize) -> OptResult<elem::Element<'_>> {
        self.into_iter().nth(index).transpose()
    }

    fn get_with<'a, T>(
        &'a self,
        index: usize,
        f: impl FnOnce(elem::Element<'a>) -> RawResult<T>,
    ) -> OptResult<T> {
        self.get(index)?.map(f).transpose()
    }

    pub fn get_f64(&self, index: usize) -> OptResult<f64> {
        self.get_with(index, elem::Element::as_f64)
    }

    pub fn get_str(&self, index: usize) -> OptResult<&str> {
        self.get_with(index, elem::Element::as_str)
    }

    pub fn get_document(&self, index: usize) -> OptResult<&Doc> {
        self.get_with(index, elem::Element::as_document)
    }

    pub fn get_array(&self, index: usize) -> OptResult<&Array> {
        self.get_with(index, elem::Element::as_array)
    }

    pub fn get_binary(&self, index: usize) -> OptResult<elem::RawBsonBinary<'_>> {
        self.get_with(index, elem::Element::as_binary)
    }

    pub fn get_object_id(&self, index: usize) -> OptResult<oid::ObjectId> {
        self.get_with(index, elem::Element::as_object_id)
    }

    pub fn get_bool(&self, index: usize) -> OptResult<bool> {
        self.get_with(index, elem::Element::as_bool)
    }

    pub fn get_datetime(&self, index: usize) -> OptResult<DateTime<Utc>> {
        self.get_with(index, elem::Element::as_datetime)
    }

    pub fn get_null(&self, index: usize) -> OptResult<()> {
        self.get_with(index, elem::Element::as_null)
    }

    pub fn get_regex(&self, index: usize) -> OptResult<elem::RawBsonRegex<'_>> {
        self.get_with(index, elem::Element::as_regex)
    }

    pub fn get_javascript(&self, index: usize) -> OptResult<&str> {
        self.get_with(index, elem::Element::as_javascript)
    }

    pub fn get_symbol(&self, index: usize) -> OptResult<&str> {
        self.get_with(index, elem::Element::as_symbol)
    }

    pub fn get_javascript_with_scope(&self, index: usize) -> OptResult<(&str, &Doc)> {
        self.get_with(index, elem::Element::as_javascript_with_scope)
    }

    pub fn get_i32(&self, index: usize) -> OptResult<i32> {
        self.get_with(index, elem::Element::as_i32)
    }

    pub fn get_timestamp(&self, index: usize) -> OptResult<elem::RawBsonTimestamp<'_>> {
        self.get_with(index, elem::Element::as_timestamp)
    }

    pub fn get_i64(&self, index: usize) -> OptResult<i64> {
        self.get_with(index, elem::Element::as_i64)
    }

    pub fn to_vec(&self) -> RawResult<Vec<elem::Element<'_>>> {
        self.into_iter().collect()
    }

    pub fn as_bytes(&self) -> &[u8] {
        self.doc.as_bytes()
    }
}

impl TryFrom<&Array> for Vec<Bson> {
    type Error = RawError;

    fn try_from(arr: &Array) -> RawResult<Vec<Bson>> {
        arr.into_iter()
            .map(|result| {
                let rawbson = result?;
                Bson::try_from(rawbson)
            })
            .collect()
    }
}

impl<'a> IntoIterator for &'a Array {
    type IntoIter = ArrayIter<'a>;
    type Item = RawResult<elem::Element<'a>>;

    fn into_iter(self) -> ArrayIter<'a> {
        ArrayIter {
            dociter: self.doc.into_iter(),
            index: 0,
        }
    }
}

pub struct ArrayIter<'a> {
    dociter: DocIter<'a>,
    index: usize,
}

impl<'a> Iterator for ArrayIter<'a> {
    type Item = RawResult<elem::Element<'a>>;

    fn next(&mut self) -> Option<RawResult<elem::Element<'a>>> {
        let value = self.dociter.next().map(|result| {
            let (key, bson) = match result {
                Ok(value) => value,
                Err(err) => return Err(err),
            };

            let index: usize = key
                .parse()
                .map_err(|_| RawError::MalformedValue("non-integer array index found".into()))?;

            if index == self.index {
                Ok(bson)
            } else {
                Err(RawError::MalformedValue("wrong array index found".into()))
            }
        });
        self.index += 1;
        value
    }
}
/// Given a 4 byte u8 slice, return an i32 calculated from the bytes in
/// little endian order
///
/// # Panics
///
/// This function panics if given a slice that is not four bytes long.
fn i32_from_slice(val: &[u8]) -> i32 {
    i32::from_le_bytes(val.try_into().expect("i32 is four bytes"))
}

/// Given an 8 byte u8 slice, return an i64 calculated from the bytes in
/// little endian order
///
/// # Panics
///
/// This function panics if given a slice that is not eight bytes long.
fn i64_from_slice(val: &[u8]) -> i64 {
    i64::from_le_bytes(val.try_into().expect("i64 is eight bytes"))
}

/// Given a 4 byte u8 slice, return a u32 calculated from the bytes in
/// little endian order
///
/// # Panics
///
/// This function panics if given a slice that is not four bytes long.
fn u32_from_slice(val: &[u8]) -> u32 {
    u32::from_le_bytes(val.try_into().expect("u32 is four bytes"))
}

fn d128_from_slice(val: &[u8]) -> Decimal128 {
    // TODO: Handle Big Endian platforms
    let d =
        unsafe { decimal::d128::from_raw_bytes(val.try_into().expect("d128 is sixteen bytes")) };
    Decimal128::from(d)
}

fn read_nullterminated(buf: &[u8]) -> RawResult<&str> {
    let mut splits = buf.splitn(2, |x| *x == 0);
    let value = splits
        .next()
        .ok_or_else(|| RawError::MalformedValue("no value".into()))?;
    if splits.next().is_some() {
        Ok(try_to_str(value)?)
    } else {
        Err(RawError::MalformedValue("expected null terminator".into()))
    }
}

fn read_lenencoded(buf: &[u8]) -> RawResult<&str> {
    let length = i32_from_slice(&buf[..4]);
    assert!(buf.len() as i32 >= length + 4);
    try_to_str(&buf[4..4 + length as usize - 1])
}

fn try_to_str(data: &[u8]) -> RawResult<&str> {
    match std::str::from_utf8(data) {
        Ok(s) => Ok(s),
        Err(_) => Err(RawError::Utf8EncodingError(data.into())),
    }
}

pub type DocRef<'a> = &'a Doc;

#[cfg(test)]
mod tests {
    use super::*;
    use bson::{doc, spec::BinarySubtype, Binary, Bson, JavaScriptCodeWithScope, Regex, Timestamp};
    use chrono::TimeZone;

    fn to_bytes(doc: &bson::Document) -> Vec<u8> {
        let mut docbytes = Vec::new();
        doc.to_writer(&mut docbytes).unwrap();
        docbytes
    }

    #[test]
    fn string_from_document() {
        let docbytes = to_bytes(&doc! {
            "this": "first",
            "that": "second",
            "something": "else",
        });
        let rawdoc = Doc::new(&docbytes).unwrap();
        assert_eq!(
            rawdoc.get("that").unwrap().unwrap().as_str().unwrap(),
            "second",
        );
    }

    #[test]
    fn nested_document() {
        let docbytes = to_bytes(&doc! {
            "outer": {
                "inner": "surprise",
            },
        });
        let rawdoc = Doc::new(&docbytes).unwrap();
        assert_eq!(
            rawdoc
                .get("outer")
                .expect("get doc result")
                .expect("get doc option")
                .as_document()
                .expect("as doc")
                .get("inner")
                .expect("get str result")
                .expect("get str option")
                .as_str()
                .expect("as str"),
            "surprise",
        );
    }

    #[test]
    fn iterate() {
        let docbytes = to_bytes(&doc! {
            "apples": "oranges",
            "peanut butter": "chocolate",
            "easy as": {"do": 1, "re": 2, "mi": 3},
        });
        let rawdoc = Doc::new(&docbytes).expect("malformed bson document");
        let mut dociter = rawdoc.into_iter();
        let next = dociter.next().expect("no result").expect("invalid bson");
        assert_eq!(next.0, "apples");
        assert_eq!(next.1.as_str().expect("result was not a str"), "oranges");
        let next = dociter.next().expect("no result").expect("invalid bson");
        assert_eq!(next.0, "peanut butter");
        assert_eq!(next.1.as_str().expect("result was not a str"), "chocolate");
        let next = dociter.next().expect("no result").expect("invalid bson");
        assert_eq!(next.0, "easy as");
        let _doc = next.1.as_document().expect("result was a not a document");
        let next = dociter.next();
        assert!(next.is_none());
    }

    #[test]
    fn rawdoc_to_doc() {
        let docbytes = to_bytes(&doc! {
            "f64": 2.5,
            "string": "hello",
            "document": {},
            "array": ["binary", "serialized", "object", "notation"],
            "binary": Binary { subtype: BinarySubtype::Generic, bytes: vec![1, 2, 3] },
            "object_id": oid::ObjectId::with_bytes([1, 2, 3, 4, 5,6,7,8,9,10, 11,12]),
            "boolean": true,
            "datetime": Utc::now(),
            "null": Bson::Null,
            "regex": Bson::RegularExpression(Regex { pattern: String::from(r"end\s*$"), options: String::from("i")}),
            "javascript": Bson::JavaScriptCode(String::from("console.log(console);")),
            "symbol": Bson::Symbol(String::from("artist-formerly-known-as")),
            "javascript_with_scope": Bson::JavaScriptCodeWithScope(JavaScriptCodeWithScope{ code: String::from("console.log(msg);"), scope: doc!{"ok": true}}),
            "int32": 23i32,
            "timestamp": Bson::Timestamp(Timestamp { time: 3542578, increment: 0 }),
            "int64": 46i64,
            "end": "END",
        });

        let rawdoc = Doc::new(&docbytes).expect("invalid document");
        let _doc: bson::Document = rawdoc.try_into().expect("invalid bson");
    }

    #[test]
    fn f64() {
        #![allow(clippy::float_cmp)]

        let rawdoc = DocBuf::from_document(&doc! {"f64": 2.5});
        assert_eq!(
            rawdoc
                .get("f64")
                .expect("error finding key f64")
                .expect("no key f64")
                .as_f64()
                .expect("result was not a f64"),
            2.5,
        );
    }

    #[test]
    fn string() {
        let rawdoc = DocBuf::from_document(&doc! {"string": "hello"});

        assert_eq!(
            rawdoc
                .get("string")
                .expect("error finding key string")
                .expect("no key string")
                .as_str()
                .expect("result was not a string"),
            "hello",
        );
    }
    #[test]
    fn document() {
        let rawdoc = DocBuf::from_document(&doc! {"document": {}});

        let doc = rawdoc
            .get("document")
            .expect("error finding key document")
            .expect("no key document")
            .as_document()
            .expect("result was not a document");
        assert_eq!(&doc.data, [5, 0, 0, 0, 0].as_ref()); // Empty document
    }

    #[test]
    fn array() {
        let rawdoc =
            DocBuf::from_document(&doc! { "array": ["binary", "serialized", "object", "notation"]});

        let array = rawdoc
            .get("array")
            .expect("error finding key array")
            .expect("no key array")
            .as_array()
            .expect("result was not an array");
        assert_eq!(array.get_str(0), Ok(Some("binary")));
        assert_eq!(array.get_str(3), Ok(Some("notation")));
        assert_eq!(array.get_str(4), Ok(None));
    }

    #[test]
    fn binary() {
        let rawdoc = DocBuf::from_document(&doc! {
            "binary": Binary { subtype: BinarySubtype::Generic, bytes: vec![1u8, 2, 3] }
        });
        let binary: elem::RawBsonBinary<'_> = rawdoc
            .get("binary")
            .expect("error finding key binary")
            .expect("no key binary")
            .as_binary()
            .expect("result was not a binary object");
        assert_eq!(binary.subtype, BinarySubtype::Generic);
        assert_eq!(binary.data, &[1, 2, 3]);
    }

    #[test]
    fn object_id() {
        let rawdoc = DocBuf::from_document(&doc! {
            "object_id": oid::ObjectId::with_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),
        });
        let oid = rawdoc
            .get("object_id")
            .expect("error finding key object_id")
            .expect("no key object_id")
            .as_object_id()
            .expect("result was not an object id");
        assert_eq!(oid.to_hex(), "0102030405060708090a0b0c");
    }

    #[test]
    fn boolean() {
        let rawdoc = DocBuf::from_document(&doc! {
            "boolean": true,
        });

        let boolean = rawdoc
            .get("boolean")
            .expect("error finding key boolean")
            .expect("no key boolean")
            .as_bool()
            .expect("result was not boolean");

        assert_eq!(boolean, true);
    }

    #[test]
    fn datetime() {
        let rawdoc = DocBuf::from_document(&doc! {
            "boolean": true,
            "datetime": Utc.ymd(2000,10,31).and_hms(12, 30, 45),
        });
        let datetime = rawdoc
            .get("datetime")
            .expect("error finding key datetime")
            .expect("no key datetime")
            .as_datetime()
            .expect("result was not datetime");
        assert_eq!(datetime.to_rfc3339(), "2000-10-31T12:30:45+00:00");
    }

    #[test]
    fn null() {
        let rawdoc = DocBuf::from_document(&doc! {
            "null": null,
        });
        let () = rawdoc
            .get("null")
            .expect("error finding key null")
            .expect("no key null")
            .as_null()
            .expect("was not null");
    }

    #[test]
    fn regex() {
        let rawdoc = DocBuf::from_document(&doc! {
            "regex": Bson::RegularExpression(Regex { pattern: String::from(r"end\s*$"), options: String::from("i")}),
        });
        let regex = rawdoc
            .get("regex")
            .expect("error finding key regex")
            .expect("no key regex")
            .as_regex()
            .expect("was not regex");
        assert_eq!(regex.pattern, r"end\s*$");
        assert_eq!(regex.options, "i");
    }
    #[test]
    fn javascript() {
        let rawdoc = DocBuf::from_document(&doc! {
            "javascript": Bson::JavaScriptCode(String::from("console.log(console);")),
        });
        let js = rawdoc
            .get("javascript")
            .expect("error finding key javascript")
            .expect("no key javascript")
            .as_javascript()
            .expect("was not javascript");
        assert_eq!(js, "console.log(console);");
    }

    #[test]
    fn symbol() {
        let rawdoc = DocBuf::from_document(&doc! {
            "symbol": Bson::Symbol(String::from("artist-formerly-known-as")),
        });

        let symbol = rawdoc
            .get("symbol")
            .expect("error finding key symbol")
            .expect("no key symbol")
            .as_symbol()
            .expect("was not symbol");
        assert_eq!(symbol, "artist-formerly-known-as");
    }

    #[test]
    fn javascript_with_scope() {
        let rawdoc = DocBuf::from_document(&doc! {
            "javascript_with_scope": Bson::JavaScriptCodeWithScope(JavaScriptCodeWithScope{ code: String::from("console.log(msg);"), scope: doc!{"ok": true}}),
        });
        let (js, scopedoc) = rawdoc
            .get("javascript_with_scope")
            .expect("error finding key javascript_with_scope")
            .expect("no key javascript_with_scope")
            .as_javascript_with_scope()
            .expect("was not javascript with scope");
        assert_eq!(js, "console.log(msg);");
        let (scope_key, scope_value_bson) = scopedoc
            .into_iter()
            .next()
            .expect("no next value in scope")
            .expect("invalid element");
        assert_eq!(scope_key, "ok");
        let scope_value = scope_value_bson.as_bool().expect("not a boolean");
        assert_eq!(scope_value, true);
    }

    #[test]
    fn int32() {
        let rawdoc = DocBuf::from_document(&doc! {
            "int32": 23i32,
        });
        let int32 = rawdoc
            .get("int32")
            .expect("error finding key int32")
            .expect("no key int32")
            .as_i32()
            .expect("was not int32");
        assert_eq!(int32, 23i32);
    }

    #[test]
    fn timestamp() {
        let rawdoc = DocBuf::from_document(&doc! {
            "timestamp": Bson::Timestamp(Timestamp { time: 3542578, increment: 7 }),
        });
        let ts = rawdoc
            .get("timestamp")
            .expect("error finding key timestamp")
            .expect("no key timestamp")
            .as_timestamp()
            .expect("was not a timestamp");

        assert_eq!(ts.increment(), 7);
        assert_eq!(ts.time(), 3542578);
    }

    #[test]
    fn int64() {
        let rawdoc = DocBuf::from_document(&doc! {
            "int64": 46i64,
        });
        let int64 = rawdoc
            .get("int64")
            .expect("error finding key int64")
            .expect("no key int64")
            .as_i64()
            .expect("was not int64");
        assert_eq!(int64, 46i64);
    }
    #[test]
    fn document_iteration() {
        let docbytes = to_bytes(&doc! {
            "f64": 2.5,
            "string": "hello",
            "document": {},
            "array": ["binary", "serialized", "object", "notation"],
            "binary": Binary { subtype: BinarySubtype::Generic, bytes: vec![1u8, 2, 3] },
            "object_id": oid::ObjectId::with_bytes([1, 2, 3, 4, 5,6,7,8,9,10, 11,12]),
            "boolean": true,
            "datetime": Utc::now(),
            "null": Bson::Null,
            "regex": Bson::RegularExpression(Regex { pattern: String::from(r"end\s*$"), options: String::from("i")}),
            "javascript": Bson::JavaScriptCode(String::from("console.log(console);")),
            "symbol": Bson::Symbol(String::from("artist-formerly-known-as")),
            "javascript_with_scope": Bson::JavaScriptCodeWithScope(JavaScriptCodeWithScope{ code: String::from("console.log(msg);"), scope: doc!{"ok": true}}),
            "int32": 23i32,
            "timestamp": Bson::Timestamp(Timestamp { time: 3542578, increment: 0 }),
            "int64": 46i64,
            "end": "END",
        });
        let rawdoc = unsafe { Doc::new_unchecked(&docbytes) };

        assert_eq!(
            rawdoc
                .into_iter()
                .collect::<Result<Vec<(&str, _)>, RawError>>()
                .expect("collecting iterated doc")
                .len(),
            17
        );
        let end = rawdoc
            .get("end")
            .expect("error finding key end")
            .expect("no key end")
            .as_str()
            .expect("was not str");
        assert_eq!(end, "END");
    }

    #[test]
    fn into_bson_conversion() {
        let docbytes = to_bytes(&doc! {
            "f64": 2.5,
            "string": "hello",
            "document": {},
            "array": ["binary", "serialized", "object", "notation"],
            "object_id": oid::ObjectId::with_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),
            "binary": Binary { subtype: BinarySubtype::Generic, bytes: vec![1u8, 2, 3] },
            "boolean": false,
        });
        let rawbson = elem::Element::new(ElementType::EmbeddedDocument, &docbytes);
        let b: Bson = rawbson.try_into().expect("invalid bson");
        let doc = b.as_document().expect("not a document");
        assert_eq!(*doc.get("f64").expect("f64 not found"), Bson::Double(2.5));
        assert_eq!(
            *doc.get("string").expect("string not found"),
            Bson::String(String::from("hello"))
        );
        assert_eq!(
            *doc.get("document").expect("document not found"),
            Bson::Document(doc! {})
        );
        assert_eq!(
            *doc.get("array").expect("array not found"),
            Bson::Array(
                vec!["binary", "serialized", "object", "notation"]
                    .into_iter()
                    .map(|s| Bson::String(String::from(s)))
                    .collect()
            )
        );
        assert_eq!(
            *doc.get("object_id").expect("object_id not found"),
            Bson::ObjectId(oid::ObjectId::with_bytes([
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
            ]))
        );
        assert_eq!(
            *doc.get("binary").expect("binary not found"),
            Bson::Binary(Binary {
                subtype: BinarySubtype::Generic,
                bytes: vec![1, 2, 3]
            })
        );
        assert_eq!(
            *doc.get("boolean").expect("boolean not found"),
            Bson::Boolean(false)
        );
    }
}

#[cfg(test)]
mod proptests {
    use proptest::prelude::*;
    use std::convert::TryInto;

    use super::DocBuf;
    use crate::props::arbitrary_bson;
    use bson::doc;

    fn to_bytes(doc: &bson::Document) -> Vec<u8> {
        let mut docbytes = Vec::new();
        doc.to_writer(&mut docbytes).unwrap();
        docbytes
    }

    proptest! {
        #[test]
        fn no_crashes(s: Vec<u8>) {
            let _ = DocBuf::new(s);
        }

        #[test]
        fn roundtrip_bson(bson in arbitrary_bson()) {
            println!("{:?}", bson);
            let doc = doc!{"bson": bson};
            let raw = to_bytes(&doc);
            let raw = DocBuf::new(raw);
            prop_assert!(raw.is_ok());
            let raw = raw.unwrap();
            let roundtrip: Result<bson::Document, _> = raw.try_into();
            prop_assert!(roundtrip.is_ok());
            let roundtrip = roundtrip.unwrap();
            prop_assert_eq!(doc, roundtrip);
        }
    }
}