/
bson.rs
647 lines (582 loc) · 20.8 KB
/
bson.rs
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
// The MIT License (MIT)
// Copyright (c) 2015 Y. T. Chung <zonyitoo@gmail.com>
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//! BSON definition
use std::fmt::{self, Debug, Display};
use std::ops::{Deref, DerefMut};
use chrono::offset::TimeZone;
use chrono::{DateTime, Timelike, Utc};
use hex;
use serde_json::Value;
use decimal128::Decimal128;
use oid;
use ordered::OrderedDocument;
use spec::{BinarySubtype, ElementType};
/// Possible BSON value types.
#[derive(Clone, PartialEq)]
pub enum Bson {
/// 64-bit binary floating point
FloatingPoint(f64),
/// UTF-8 string
String(String),
/// Array
Array(Array),
/// Embedded document
Document(Document),
/// Boolean value
Boolean(bool),
/// Null value
Null,
/// Regular expression - The first cstring is the regex pattern, the second is the regex options string.
/// Options are identified by characters, which must be stored in alphabetical order.
/// Valid options are 'i' for case insensitive matching, 'm' for multiline matching, 'x' for verbose mode,
/// 'l' to make \w, \W, etc. locale dependent, 's' for dotall mode ('.' matches everything), and 'u' to
/// make \w, \W, etc. match unicode.
RegExp(String, String),
/// JavaScript code
JavaScriptCode(String),
/// JavaScript code w/ scope
JavaScriptCodeWithScope(String, Document),
/// 32-bit integer
I32(i32),
/// 64-bit integer
I64(i64),
/// Timestamp
TimeStamp(i64),
/// Binary data
Binary(BinarySubtype, Vec<u8>),
/// [ObjectId](http://dochub.mongodb.org/core/objectids)
ObjectId(oid::ObjectId),
/// UTC datetime
UtcDatetime(DateTime<Utc>),
/// Symbol (Deprecated)
Symbol(String),
/// [128-bit decimal floating point](https://github.com/mongodb/specifications/blob/master/source/bson-decimal128/decimal128.rst)
Decimal128(Decimal128),
}
/// Alias for `Vec<Bson>`.
pub type Array = Vec<Bson>;
/// Alias for `OrderedDocument`.
pub type Document = OrderedDocument;
impl Default for Bson {
fn default() -> Self {
Bson::Null
}
}
impl Debug for Bson {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Bson::FloatingPoint(p) => write!(f, "FloatingPoint({:?})", p),
Bson::String(ref s) => write!(f, "String({:?})", s),
Bson::Array(ref vec) => write!(f, "Array({:?})", vec),
Bson::Document(ref doc) => write!(f, "Document({:?})", doc),
Bson::Boolean(b) => write!(f, "Boolean({:?})", b),
Bson::Null => write!(f, "Null"),
Bson::RegExp(ref pat, ref opt) => write!(f, "RegExp(/{:?}/{:?})", pat, opt),
Bson::JavaScriptCode(ref s) => write!(f, "JavaScriptCode({:?})", s),
Bson::JavaScriptCodeWithScope(ref s, ref scope) => {
write!(f, "JavaScriptCodeWithScope({:?}, {:?})", s, scope)
}
Bson::I32(v) => write!(f, "I32({:?})", v),
Bson::I64(v) => write!(f, "I64({:?})", v),
Bson::TimeStamp(i) => {
let time = (i >> 32) as i32;
let inc = (i & 0xFFFF_FFFF) as i32;
write!(f, "TimeStamp({}, {})", time, inc)
}
Bson::Binary(t, ref vec) => write!(f, "BinData({}, 0x{})", u8::from(t), hex::encode(vec)),
Bson::ObjectId(ref id) => write!(f, "ObjectId({:?})", id),
Bson::UtcDatetime(date_time) => write!(f, "UtcDatetime({:?})", date_time),
Bson::Symbol(ref sym) => write!(f, "Symbol({:?})", sym),
Bson::Decimal128(ref d) => write!(f, "Decimal128({:?})", d),
}
}
}
impl Display for Bson {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
Bson::FloatingPoint(f) => write!(fmt, "{}", f),
Bson::String(ref s) => write!(fmt, "\"{}\"", s),
Bson::Array(ref vec) => {
fmt.write_str("[")?;
let mut first = true;
for bson in vec {
if !first {
fmt.write_str(", ")?;
}
write!(fmt, "{}", bson)?;
first = false;
}
fmt.write_str("]")
}
Bson::Document(ref doc) => write!(fmt, "{}", doc),
Bson::Boolean(b) => write!(fmt, "{}", b),
Bson::Null => write!(fmt, "null"),
Bson::RegExp(ref pat, ref opt) => write!(fmt, "/{}/{}", pat, opt),
Bson::JavaScriptCode(ref s) | Bson::JavaScriptCodeWithScope(ref s, _) => fmt.write_str(&s),
Bson::I32(i) => write!(fmt, "{}", i),
Bson::I64(i) => write!(fmt, "{}", i),
Bson::TimeStamp(i) => {
let time = (i >> 32) as i32;
let inc = (i & 0xFFFFFFFF) as i32;
write!(fmt, "Timestamp({}, {})", time, inc)
}
Bson::Binary(t, ref vec) => write!(fmt, "BinData({}, 0x{})", u8::from(t), hex::encode(vec)),
Bson::ObjectId(ref id) => write!(fmt, "ObjectId(\"{}\")", id),
Bson::UtcDatetime(date_time) => write!(fmt, "Date(\"{}\")", date_time),
Bson::Symbol(ref sym) => write!(fmt, "Symbol(\"{}\")", sym),
Bson::Decimal128(ref d) => write!(fmt, "Decimal128({})", d),
}
}
}
impl From<f32> for Bson {
fn from(a: f32) -> Bson {
Bson::FloatingPoint(a as f64)
}
}
impl From<f64> for Bson {
fn from(a: f64) -> Bson {
Bson::FloatingPoint(a)
}
}
impl<'a> From<&'a str> for Bson {
fn from(s: &str) -> Bson {
Bson::String(s.to_owned())
}
}
impl From<String> for Bson {
fn from(a: String) -> Bson {
Bson::String(a)
}
}
impl<'a> From<&'a String> for Bson {
fn from(a: &'a String) -> Bson {
Bson::String(a.to_owned())
}
}
impl From<Array> for Bson {
fn from(a: Array) -> Bson {
Bson::Array(a)
}
}
impl From<Document> for Bson {
fn from(a: Document) -> Bson {
Bson::Document(a)
}
}
impl From<bool> for Bson {
fn from(a: bool) -> Bson {
Bson::Boolean(a)
}
}
impl From<(String, String)> for Bson {
fn from((pat, opt): (String, String)) -> Bson {
Bson::RegExp(pat, opt)
}
}
impl From<(String, Document)> for Bson {
fn from((code, scope): (String, Document)) -> Bson {
Bson::JavaScriptCodeWithScope(code, scope)
}
}
impl From<(BinarySubtype, Vec<u8>)> for Bson {
fn from((ty, data): (BinarySubtype, Vec<u8>)) -> Bson {
Bson::Binary(ty, data)
}
}
impl From<i32> for Bson {
fn from(a: i32) -> Bson {
Bson::I32(a)
}
}
impl From<i64> for Bson {
fn from(a: i64) -> Bson {
Bson::I64(a)
}
}
impl From<u32> for Bson {
fn from(a: u32) -> Bson {
Bson::I32(a as i32)
}
}
impl From<u64> for Bson {
fn from(a: u64) -> Bson {
Bson::I64(a as i64)
}
}
impl From<[u8; 12]> for Bson {
fn from(a: [u8; 12]) -> Bson {
Bson::ObjectId(oid::ObjectId::with_bytes(a))
}
}
impl From<oid::ObjectId> for Bson {
fn from(a: oid::ObjectId) -> Bson {
Bson::ObjectId(a)
}
}
impl From<DateTime<Utc>> for Bson {
fn from(a: DateTime<Utc>) -> Bson {
Bson::UtcDatetime(a)
}
}
impl From<Value> for Bson {
fn from(a: Value) -> Bson {
match a {
Value::Number(x) => x.as_i64()
.map(Bson::from)
.or_else(|| x.as_u64().map(Bson::from))
.or_else(|| x.as_f64().map(Bson::from))
.unwrap_or_else(|| panic!("Invalid number value: {}", x)),
Value::String(x) => x.into(),
Value::Bool(x) => x.into(),
Value::Array(x) => Bson::Array(x.into_iter().map(Bson::from).collect()),
Value::Object(x) => Bson::from_extended_document(x.into_iter().map(|(k, v)| (k, v.into())).collect()),
Value::Null => Bson::Null,
}
}
}
impl From<Bson> for Value {
fn from(bson: Bson) -> Self {
match bson {
Bson::FloatingPoint(v) => json!(v),
Bson::String(v) => json!(v),
Bson::Array(v) => json!(v),
Bson::Document(v) => json!(v),
Bson::Boolean(v) => json!(v),
Bson::Null => Value::Null,
Bson::RegExp(pat, opt) => json!({
"$regex": pat,
"$options": opt
}),
Bson::JavaScriptCode(code) => json!({ "$code": code }),
Bson::JavaScriptCodeWithScope(code, scope) => json!({
"$code": code,
"scope": scope
}),
Bson::I32(v) => v.into(),
Bson::I64(v) => v.into(),
Bson::TimeStamp(v) => {
let time = v >> 32;
let inc = v & 0x0000_FFFF;
json!({
"t": time,
"i": inc
})
}
Bson::Binary(t, ref v) => {
let tval: u8 = From::from(t);
json!({
"type": tval,
"$binary": hex::encode(v),
})
}
Bson::ObjectId(v) => json!({"$oid": v.to_string()}),
Bson::UtcDatetime(v) => json!({
"$date": {
"$numberLong": (v.timestamp() * 1000) + ((v.nanosecond() / 1000000) as i64)
}
}),
// FIXME: Don't know what is the best way to encode Symbol type
Bson::Symbol(v) => json!({ "$symbol": v }),
Bson::Decimal128(ref v) => json!({ "$numberDecimal": v.to_string() }),
}
}
}
impl Bson {
/// Get the `ElementType` of this value.
pub fn element_type(&self) -> ElementType {
match *self {
Bson::FloatingPoint(..) => ElementType::FloatingPoint,
Bson::String(..) => ElementType::Utf8String,
Bson::Array(..) => ElementType::Array,
Bson::Document(..) => ElementType::EmbeddedDocument,
Bson::Boolean(..) => ElementType::Boolean,
Bson::Null => ElementType::NullValue,
Bson::RegExp(..) => ElementType::RegularExpression,
Bson::JavaScriptCode(..) => ElementType::JavaScriptCode,
Bson::JavaScriptCodeWithScope(..) => ElementType::JavaScriptCodeWithScope,
Bson::I32(..) => ElementType::Integer32Bit,
Bson::I64(..) => ElementType::Integer64Bit,
Bson::TimeStamp(..) => ElementType::TimeStamp,
Bson::Binary(..) => ElementType::Binary,
Bson::ObjectId(..) => ElementType::ObjectId,
Bson::UtcDatetime(..) => ElementType::UtcDatetime,
Bson::Symbol(..) => ElementType::Symbol,
Bson::Decimal128(..) => ElementType::Decimal128Bit,
}
}
/// Clones the bson and returns the representative serde_json Value.
/// The json will be in [extended JSON format](https://docs.mongodb.com/manual/reference/mongodb-extended-json/).
#[deprecated(since = "0.5.1", note = "use bson.clone().into() instead")]
pub fn to_json(&self) -> Value {
self.clone().into()
}
/// Consumes the bson and returns the representative serde_json Value.
/// The json will be in [extended JSON format](https://docs.mongodb.com/manual/reference/mongodb-extended-json/).
#[deprecated(since = "0.5.1", note = "use bson.into() instead")]
pub fn into_json(self) -> Value {
self.into()
}
/// Consumes the serde_json Value and returns the representative bson.
/// The json should be in [extended JSON format](https://docs.mongodb.com/manual/reference/mongodb-extended-json/).
#[deprecated(since = "0.5.1", note = "use json.into() instead")]
pub fn from_json(val: Value) -> Bson {
val.into()
}
/// Converts to extended format.
/// This function mainly used for [extended JSON format](https://docs.mongodb.com/manual/reference/mongodb-extended-json/).
#[doc(hidden)]
pub fn to_extended_document(&self) -> Document {
match *self {
Bson::RegExp(ref pat, ref opt) => {
doc! {
"$regex": pat.clone(),
"$options": opt.clone(),
}
}
Bson::JavaScriptCode(ref code) => {
doc! {
"$code": code.clone(),
}
}
Bson::JavaScriptCodeWithScope(ref code, ref scope) => {
doc! {
"$code": code.clone(),
"$scope": scope.clone(),
}
}
Bson::TimeStamp(v) => {
let time = (v >> 32) as i32;
let inc = (v & 0xFFFF_FFFF) as i32;
doc! {
"t": time,
"i": inc
}
}
Bson::Binary(t, ref v) => {
let tval: u8 = From::from(t);
doc! {
"$binary": hex::encode(v),
"type": tval as i64,
}
}
Bson::ObjectId(ref v) => {
doc! {
"$oid": v.to_string(),
}
}
Bson::UtcDatetime(ref v) => {
doc! {
"$date": {
"$numberLong" => (v.timestamp() * 1000) + v.nanosecond() as i64 / 1000000,
}
}
}
Bson::Symbol(ref v) => {
doc! {
"$symbol": v.to_owned(),
}
}
Bson::Decimal128(ref v) => {
doc! {
"$numberDecimal" => (v.to_string())
}
}
_ => panic!("Attempted conversion of invalid data type: {}", self),
}
}
/// Converts from extended format.
/// This function is mainly used for [extended JSON format](https://docs.mongodb.com/manual/reference/mongodb-extended-json/).
#[doc(hidden)]
pub fn from_extended_document(values: Document) -> Bson {
if values.len() == 2 {
if let (Ok(pat), Ok(opt)) = (values.get_str("$regex"), values.get_str("$options")) {
return Bson::RegExp(pat.to_owned(), opt.to_owned());
} else if let (Ok(code), Ok(scope)) = (values.get_str("$code"), values.get_document("$scope")) {
return Bson::JavaScriptCodeWithScope(code.to_owned(), scope.to_owned());
} else if let (Ok(t), Ok(i)) = (values.get_i32("t"), values.get_i32("i")) {
let timestamp = ((t as i64) << 32) + (i as i64);
return Bson::TimeStamp(timestamp);
} else if let (Ok(t), Ok(i)) = (values.get_i64("t"), values.get_i64("i")) {
let timestamp = (t << 32) + i;
return Bson::TimeStamp(timestamp);
} else if let (Ok(hex), Ok(t)) = (values.get_str("$binary"), values.get_i64("type")) {
let ttype = t as u8;
return Bson::Binary(From::from(ttype), hex::decode(hex.as_bytes()).expect("$binary value is not a valid Hex encoded bytes"));
}
} else if values.len() == 1 {
if let Ok(code) = values.get_str("$code") {
return Bson::JavaScriptCode(code.to_owned());
} else if let Ok(hex) = values.get_str("$oid") {
return Bson::ObjectId(oid::ObjectId::with_string(hex).unwrap());
} else if let Ok(long) = values.get_document("$date")
.and_then(|inner| inner.get_i64("$numberLong"))
{
return Bson::UtcDatetime(Utc.timestamp(long / 1000, ((long % 1000) * 1_000_000) as u32));
} else if let Ok(sym) = values.get_str("$symbol") {
return Bson::Symbol(sym.to_owned());
} else if let Ok(dec) = values.get_str("$numberDecimal") {
return Bson::Decimal128(dec.parse::<Decimal128>().unwrap());
}
}
Bson::Document(values)
}
}
/// Value helpers
impl Bson {
/// If `Bson` is `FloatingPoint`, return its value. Returns `None` otherwise
pub fn as_f64(&self) -> Option<f64> {
match *self {
Bson::FloatingPoint(v) => Some(v),
_ => None,
}
}
/// If `Bson` is `String`, return its value. Returns `None` otherwise
pub fn as_str(&self) -> Option<&str> {
match *self {
Bson::String(ref s) => Some(s),
_ => None,
}
}
/// If `Bson` is `Array`, return its value. Returns `None` otherwise
pub fn as_array(&self) -> Option<&Array> {
match *self {
Bson::Array(ref v) => Some(v),
_ => None,
}
}
/// If `Bson` is `Document`, return its value. Returns `None` otherwise
pub fn as_document(&self) -> Option<&Document> {
match *self {
Bson::Document(ref v) => Some(v),
_ => None,
}
}
/// If `Bson` is `Boolean`, return its value. Returns `None` otherwise
pub fn as_bool(&self) -> Option<bool> {
match *self {
Bson::Boolean(v) => Some(v),
_ => None,
}
}
/// If `Bson` is `I32`, return its value. Returns `None` otherwise
pub fn as_i32(&self) -> Option<i32> {
match *self {
Bson::I32(v) => Some(v),
_ => None,
}
}
/// If `Bson` is `I64`, return its value. Returns `None` otherwise
pub fn as_i64(&self) -> Option<i64> {
match *self {
Bson::I64(v) => Some(v),
_ => None,
}
}
/// If `Bson` is `Objectid`, return its value. Returns `None` otherwise
pub fn as_object_id(&self) -> Option<&oid::ObjectId> {
match *self {
Bson::ObjectId(ref v) => Some(v),
_ => None,
}
}
/// If `Bson` is `UtcDateTime`, return its value. Returns `None` otherwise
pub fn as_utc_date_time(&self) -> Option<&DateTime<Utc>> {
match *self {
Bson::UtcDatetime(ref v) => Some(v),
_ => None,
}
}
/// If `Bson` is `Symbol`, return its value. Returns `None` otherwise
pub fn as_symbol(&self) -> Option<&str> {
match *self {
Bson::Symbol(ref v) => Some(v),
_ => None,
}
}
/// If `Bson` is `TimeStamp`, return its value. Returns `None` otherwise
pub fn as_timestamp(&self) -> Option<i64> {
match *self {
Bson::TimeStamp(v) => Some(v),
_ => None,
}
}
/// If `Bson` is `Null`, return its value. Returns `None` otherwise
pub fn as_null(&self) -> Option<()> {
match *self {
Bson::Null => Some(()),
_ => None,
}
}
}
/// `TimeStamp` representation in struct for serde serialization
///
/// Just a helper for convenience
///
/// ```rust,ignore
/// #[macro_use]
/// extern crate serde_derive;
/// extern crate bson;
/// use bson::TimeStamp;
///
/// #[derive(Serialize, Deserialize)]
/// struct Foo {
/// timestamp: TimeStamp,
/// }
/// ```
#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)]
pub struct TimeStamp {
pub t: u32,
pub i: u32,
}
/// `DateTime` representation in struct for serde serialization
///
/// Just a helper for convenience
///
/// ```rust,ignore
/// #[macro_use]
/// extern crate serde_derive;
/// extern crate bson;
/// use bson::UtcDateTime;
///
/// #[derive(Serialize, Deserialize)]
/// struct Foo {
/// date_time: UtcDateTime,
/// }
/// ```
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)]
pub struct UtcDateTime(pub DateTime<Utc>);
impl Deref for UtcDateTime {
type Target = DateTime<Utc>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for UtcDateTime {
fn deref_mut(&mut self) -> &mut DateTime<Utc> {
&mut self.0
}
}
impl From<UtcDateTime> for DateTime<Utc> {
fn from(utc: UtcDateTime) -> Self {
utc.0
}
}
impl From<DateTime<Utc>> for UtcDateTime {
fn from(x: DateTime<Utc>) -> Self {
UtcDateTime(x)
}
}