Skip to content

Commit eff1348

Browse files
committed
code compiling, tests passing
1 parent 0b17739 commit eff1348

File tree

5 files changed

+113
-114
lines changed

5 files changed

+113
-114
lines changed

src/raw/doc.rs

Lines changed: 43 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use std::{
44
ops::Deref,
55
};
66

7-
use chrono::{DateTime, Utc};
7+
use crate::DateTime;
88

99
use super::{
1010
i32_from_slice,
@@ -130,8 +130,8 @@ impl RawDocument {
130130
/// Element<'_>>`.
131131
///
132132
/// ```
133-
/// # use bson::raw::{elem, RawDocument, Error};
134-
/// use bson::doc;
133+
/// # use bson::raw::Error;
134+
/// use bson::{doc, raw::RawDocument};
135135
///
136136
/// let doc = RawDocument::from_document(&doc! { "ferris": true });
137137
///
@@ -218,7 +218,9 @@ impl ToOwned for RawDocumentRef {
218218
/// original document without making any additional allocations.
219219
220220
/// ```
221-
/// # use bson::raw::{Doc, Error};
221+
/// # use bson::raw::{Error};
222+
/// use bson::raw::RawDocumentRef;
223+
///
222224
/// let doc = RawDocumentRef::new(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00")?;
223225
/// let mut iter = doc.into_iter();
224226
/// let (key, value) = iter.next().unwrap()?;
@@ -259,9 +261,10 @@ impl RawDocumentRef {
259261
/// the RawDocument will return Errors where appropriate.
260262
///
261263
/// ```
262-
/// # use bson::raw::{RawDocument, Error};
264+
/// use bson::raw::RawDocumentRef;
265+
///
263266
/// let doc = RawDocumentRef::new(b"\x05\0\0\0\0")?;
264-
/// # Ok::<(), Error>(())
267+
/// # Ok::<(), bson::raw::Error>(())
265268
/// ```
266269
pub fn new<D: AsRef<[u8]> + ?Sized>(data: &D) -> Result<&RawDocumentRef> {
267270
let data = data.as_ref();
@@ -306,8 +309,7 @@ impl RawDocumentRef {
306309
/// Creates a new RawDocument with an owned copy of the BSON bytes.
307310
///
308311
/// ```
309-
/// # use bson::raw::{Doc, Error};
310-
/// use bson::raw::RawDocument;
312+
/// use bson::raw::{RawDocumentRef, RawDocument, Error};
311313
///
312314
/// let data = b"\x05\0\0\0\0";
313315
/// let doc_ref = RawDocumentRef::new(data)?;
@@ -323,9 +325,8 @@ impl RawDocumentRef {
323325
/// found.
324326
///
325327
/// ```
326-
/// # use bson::raw::{RawDocument, elem::Element, Error};
327-
/// #
328-
/// use bson::{doc, oid::ObjectId};
328+
/// # use bson::raw::Error;
329+
/// use bson::{doc, oid::ObjectId, raw::{RawDocument, RawBson}};
329330
///
330331
/// let doc = RawDocument::from_document(&doc! {
331332
/// "_id": ObjectId::new(),
@@ -359,7 +360,8 @@ impl RawDocumentRef {
359360
/// if the key corresponds to a value which isn't a double.
360361
///
361362
/// ```
362-
/// # use bson::raw::{RawDocument, elem::Element, Error};
363+
/// # use bson::raw::Error;
364+
/// use bson::raw::RawDocument;
363365
/// use bson::doc;
364366
///
365367
/// let doc = RawDocument::from_document(&doc! {
@@ -380,8 +382,7 @@ impl RawDocumentRef {
380382
/// key corresponds to a value which isn't a string.
381383
///
382384
/// ```
383-
/// # use bson::raw::{RawDocument, elem::Element, Error};
384-
/// use bson::doc;
385+
/// use bson::{doc, raw::{RawDocument, Error}};
385386
///
386387
/// let doc = RawDocument::from_document(&doc! {
387388
/// "string": "hello",
@@ -401,8 +402,8 @@ impl RawDocumentRef {
401402
/// the key corresponds to a value which isn't a document.
402403
///
403404
/// ```
404-
/// # use bson::raw::{RawDocument, elem::Element, Error};
405-
/// use bson::doc;
405+
/// use bson::raw::Error;
406+
/// use bson::{doc, raw::RawDocument};
406407
///
407408
/// let doc = RawDocument::from_document(&doc! {
408409
/// "doc": { "key": "value"},
@@ -422,17 +423,17 @@ impl RawDocumentRef {
422423
/// the key corresponds to a value which isn't an array.
423424
///
424425
/// ```
425-
/// # use bson::raw::{RawDocument, elem::Element, Error};
426-
/// use bson::doc;
426+
/// # use bson::raw::Error;
427+
/// use bson::{doc, raw::RawDocument};
427428
///
428429
/// let doc = RawDocument::from_document(&doc! {
429430
/// "array": [true, 3],
430431
/// "bool": true,
431432
/// });
432433
///
433-
/// let mut arr_iter = docbuf.get_array("array")?.expect("finding key array").into_iter();
434-
/// let _: bool = arriter.next().unwrap()?.as_bool()?;
435-
/// let _: i32 = arriter.next().unwrap()?.as_i32()?;
434+
/// let mut arr_iter = doc.get_array("array")?.expect("finding key array").into_iter();
435+
/// let _: bool = arr_iter.next().unwrap()?.as_bool()?;
436+
/// let _: i32 = arr_iter.next().unwrap()?.as_i32()?;
436437
///
437438
/// assert!(arr_iter.next().is_none());
438439
/// assert!(doc.get_array("bool").is_err());
@@ -447,19 +448,20 @@ impl RawDocumentRef {
447448
/// if the key corresponds to a value which isn't a binary value.
448449
///
449450
/// ```
450-
/// # use bson::raw::{RawDocument, elem, Error};
451-
///
451+
/// # use bson::raw::Error;
452452
/// use bson::{
453-
/// spec::BinarySubtype
454-
/// doc, Binary,
453+
/// doc,
454+
/// raw::{RawDocument, RawBinary},
455+
/// spec::BinarySubtype,
456+
/// Binary,
455457
/// };
456458
///
457459
/// let doc = RawDocument::from_document(&doc! {
458460
/// "binary": Binary { subtype: BinarySubtype::Generic, bytes: vec![1, 2, 3] },
459461
/// "bool": true,
460462
/// });
461463
///
462-
/// assert_eq!(doc.get_binary("binary")?.map(elem::RawBsonBinary::as_bytes), Some(&[1, 2, 3][..]));
464+
/// assert_eq!(doc.get_binary("binary")?.map(RawBinary::as_bytes), Some(&[1, 2, 3][..]));
463465
/// assert_eq!(doc.get_binary("bool").unwrap_err(), Error::UnexpectedType);
464466
/// assert!(doc.get_binary("unknown")?.is_none());
465467
/// # Ok::<(), Error>(())
@@ -472,8 +474,8 @@ impl RawDocumentRef {
472474
/// the key corresponds to a value which isn't an ObjectId.
473475
///
474476
/// ```
475-
/// # use bson::raw::{RawDocument, Error};
476-
/// use bson::{doc, oid::ObjectId};
477+
/// # use bson::raw::Error;
478+
/// use bson::{doc, oid::ObjectId, raw::RawDocument};
477479
///
478480
/// let doc = RawDocument::from_document(&doc! {
479481
/// "_id": ObjectId::new(),
@@ -514,28 +516,28 @@ impl RawDocumentRef {
514516
/// if the key corresponds to a value which isn't a DateTime.
515517
///
516518
/// ```
517-
/// # use bson::raw::{RawDocument, Error};
518-
/// use bson::doc;
519-
/// use chrono::{Utc, Datelike, TimeZone};
519+
/// # use bson::raw::Error;
520+
/// use bson::{doc, raw::RawDocument, DateTime};
520521
///
522+
/// let dt = DateTime::now();
521523
/// let doc = RawDocument::from_document(&doc! {
522-
/// "created_at": Utc.ymd(2020, 3, 15).and_hms(17, 0, 0),
524+
/// "created_at": dt,
523525
/// "bool": true,
524526
/// });
525-
/// assert_eq!(doc.get_datetime("created_at")?.unwrap().year(), 2020);
527+
/// assert_eq!(doc.get_datetime("created_at")?, Some(dt));
526528
/// assert_eq!(doc.get_datetime("bool").unwrap_err(), Error::UnexpectedType);
527529
/// assert!(doc.get_datetime("unknown")?.is_none());
528530
/// # Ok::<(), Error>(())
529531
/// ```
530-
pub fn get_datetime(&self, key: &str) -> Result<Option<DateTime<Utc>>> {
532+
pub fn get_datetime(&self, key: &str) -> Result<Option<DateTime>> {
531533
self.get_with(key, RawBson::as_datetime)
532534
}
535+
533536
/// Gets a reference to the BSON regex value corresponding to a given key or returns an error if
534537
/// the key corresponds to a value which isn't a regex.
535538
///
536539
/// ```
537-
/// # use bson::raw::{RawDocument, Error, elem};
538-
/// use bson::{doc, Regex};
540+
/// use bson::{doc, Regex, raw::{RawDocument, Error}};
539541
///
540542
/// let doc = RawDocument::from_document(&doc! {
541543
/// "regex": Regex {
@@ -559,8 +561,7 @@ impl RawDocumentRef {
559561
/// error if the key corresponds to a value which isn't a timestamp.
560562
///
561563
/// ```
562-
/// # use bson::raw::{RawDocument, elem, Error};
563-
/// use bson::{doc, Timestamp};
564+
/// use bson::{doc, Timestamp, raw::{RawDocument, Error}};
564565
///
565566
/// let doc = RawDocument::from_document(&doc! {
566567
/// "bool": true,
@@ -604,8 +605,8 @@ impl RawDocumentRef {
604605
/// the key corresponds to a value which isn't a 64-bit integer.
605606
///
606607
/// ```
607-
/// # use bson::raw::{RawDocument, elem::Element, Error};
608-
/// use bson::doc;
608+
/// # use bson::raw::Error;
609+
/// use bson::{doc, raw::RawDocument};
609610
///
610611
/// let doc = RawDocument::from_document(&doc! {
611612
/// "bool": true,
@@ -624,8 +625,8 @@ impl RawDocumentRef {
624625
/// Return a reference to the contained data as a `&[u8]`
625626
///
626627
/// ```
627-
/// # use bson::raw::RawDocument;
628-
/// use bson::doc;
628+
/// # use bson::raw::Error;
629+
/// use bson::{doc, raw::RawDocument};
629630
/// let docbuf = RawDocument::from_document(&doc!{});
630631
/// assert_eq!(docbuf.as_bytes(), b"\x05\x00\x00\x00\x00");
631632
/// ```

src/raw/elem.rs

Lines changed: 15 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
1-
use std::{
2-
convert::{TryFrom, TryInto},
3-
time::Duration,
4-
};
1+
use std::convert::{TryFrom, TryInto};
52

6-
use chrono::{DateTime, TimeZone, Utc};
3+
// use chrono::{DateTime, TimeZone, Utc};
4+
use crate::DateTime;
75

86
#[cfg(feature = "decimal128")]
97
use super::d128_from_slice;
@@ -122,7 +120,7 @@ impl<'a> RawBson<'a> {
122120
/// Gets the ObjectId that's referenced or returns an error if the value isn't a BSON ObjectId.
123121
pub fn as_object_id(self) -> Result<ObjectId> {
124122
if let ElementType::ObjectId = self.element_type {
125-
Ok(ObjectId::with_bytes(self.data.try_into().map_err(
123+
Ok(ObjectId::from_bytes(self.data.try_into().map_err(
126124
|_| Error::MalformedValue {
127125
message: "object id should be 12 bytes long".into(),
128126
},
@@ -154,26 +152,10 @@ impl<'a> RawBson<'a> {
154152
}
155153

156154
/// Gets the DateTime that's referenced or returns an error if the value isn't a BSON DateTime.
157-
pub fn as_datetime(self) -> Result<DateTime<Utc>> {
155+
pub fn as_datetime(self) -> Result<DateTime> {
158156
if let ElementType::DateTime = self.element_type {
159157
let millis = i64_from_slice(self.data);
160-
if millis >= 0 {
161-
let duration = Duration::from_millis(millis as u64);
162-
Ok(Utc.timestamp(
163-
duration.as_secs().try_into().unwrap(),
164-
duration.subsec_nanos(),
165-
))
166-
} else {
167-
let duration = Duration::from_millis((-millis).try_into().unwrap());
168-
let mut secs: i64 = duration.as_secs().try_into().unwrap();
169-
secs *= -1;
170-
let mut nanos = duration.subsec_nanos();
171-
if nanos > 0 {
172-
secs -= 1;
173-
nanos = 1_000_000_000 - nanos;
174-
}
175-
Ok(Utc.timestamp(secs, nanos))
176-
}
158+
Ok(DateTime::from_millis(millis))
177159
} else {
178160
Err(Error::UnexpectedType)
179161
}
@@ -261,7 +243,15 @@ impl<'a> RawBson<'a> {
261243
assert_eq!(self.data.len(), 16);
262244
Ok(d128_from_slice(self.data))
263245
} else {
264-
Err(RawError::UnexpectedType)
246+
Err(Error::UnexpectedType)
247+
}
248+
}
249+
250+
pub fn as_null(self) -> Result<()> {
251+
if let ElementType::Null = self.element_type {
252+
Ok(())
253+
} else {
254+
Err(Error::UnexpectedType)
265255
}
266256
}
267257
}

src/raw/mod.rs

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,13 @@
1111
//!
1212
//! // See http://bsonspec.org/spec.html for details on the binary encoding of BSON.
1313
//! let doc = RawDocument::new(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00".to_vec())?;
14-
//! let elem: Option<RawBson> = doc.get("hi")?;
14+
//! let elem = doc.get("hi")?.unwrap();
1515
//!
1616
//! assert_eq!(
17-
//! elem?.as_str()?,
17+
//! elem.as_str()?,
1818
//! "y'all",
1919
//! );
20-
//! # Ok::<(), bson::raw::RawError>(())
20+
//! # Ok::<(), bson::raw::Error>(())
2121
//! ```
2222
//!
2323
//! ### bson-rust interop
@@ -48,7 +48,7 @@
4848
//! value,
4949
//! Some("world"),
5050
//! );
51-
//! # Ok::<(), bson::raw::RawError>(())
51+
//! # Ok::<(), bson::raw::Error>(())
5252
//! ```
5353
//!
5454
//! ### Reference types
@@ -60,22 +60,20 @@
6060
//!
6161
//! The below example constructs a bson document in a stack-based array,
6262
//! and extracts a &str from it, performing no heap allocation.
63-
6463
//! ```rust
65-
//! use bson::raw::Doc;
64+
//! use bson::raw::RawDocumentRef;
6665
//!
6766
//! let bytes = b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00";
6867
//! assert_eq!(RawDocumentRef::new(bytes)?.get_str("hi")?, Some("y'all"));
69-
//! # Ok::<(), bson::raw::RawError>(())
68+
//! # Ok::<(), bson::raw::Error>(())
7069
//! ```
71-
//!
70+
//!
7271
//! ### Iteration
7372
//!
7473
//! [`RawDocumentRef`] implements [`IntoIterator`](std::iter::IntoIterator), which can also be
7574
//! accessed via [`RawDocument::iter`].
7675
7776
//! ```rust
78-
//! use bson::doc;
7977
//! use bson::{
8078
//! raw::{
8179
//! RawBson,
@@ -92,14 +90,14 @@
9290
//! let doc = RawDocument::from_document(&original_doc);
9391
//! let mut doc_iter = doc.iter();
9492
//!
95-
//! let (key, value): (&str, Element) = doc_iter.next().unwrap()?;
93+
//! let (key, value): (&str, RawBson) = doc_iter.next().unwrap()?;
9694
//! assert_eq!(key, "crate");
97-
//! assert_eq!(value.as_str()?, "rawbson");
95+
//! assert_eq!(value.as_str()?, "bson");
9896
//!
99-
//! let (key, value): (&str, Element) = doc_iter.next().unwrap()?;
97+
//! let (key, value): (&str, RawBson) = doc_iter.next().unwrap()?;
10098
//! assert_eq!(key, "year");
10199
//! assert_eq!(value.as_str()?, "2021");
102-
//! # Ok::<(), bson::raw::RawError>(())
100+
//! # Ok::<(), bson::raw::Error>(())
103101
//! ```
104102
105103
mod array;

src/raw/props.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,14 @@ pub(crate) fn arbitrary_bson() -> impl Strategy<Value = Bson> {
2121
any::<f64>().prop_map(Bson::Double),
2222
any::<i32>().prop_map(Bson::Int32),
2323
any::<i64>().prop_map(Bson::Int64),
24-
any::<(String, String)>()
25-
.prop_map(|(pattern, options)| Bson::RegularExpression(Regex { pattern, options })),
26-
any::<[u8; 12]>().prop_map(|bytes| Bson::ObjectId(crate::oid::ObjectId::with_bytes(bytes))),
24+
any::<(String, String)>().prop_map(|(pattern, options)| {
25+
let mut chars: Vec<_> = options.chars().collect();
26+
chars.sort_unstable();
27+
28+
let options: String = chars.into_iter().collect();
29+
Bson::RegularExpression(Regex { pattern, options })
30+
}),
31+
any::<[u8; 12]>().prop_map(|bytes| Bson::ObjectId(crate::oid::ObjectId::from_bytes(bytes))),
2732
(arbitrary_binary_subtype(), any::<Vec<u8>>()).prop_map(|(subtype, bytes)| {
2833
let bytes = if let BinarySubtype::BinaryOld = subtype {
2934
// BinarySubtype::BinaryOld expects a four byte prefix, which the bson::Bson type
@@ -32,7 +37,7 @@ pub(crate) fn arbitrary_bson() -> impl Strategy<Value = Bson> {
3237
let mut newbytes = Vec::with_capacity(bytes.len() + 4);
3338
newbytes.extend_from_slice(&(bytes.len() as i32).to_le_bytes());
3439
newbytes.extend_from_slice(&bytes);
35-
newbytes
40+
newbytes
3641
} else {
3742
bytes
3843
};

0 commit comments

Comments
 (0)