Skip to content

Commit 24352d0

Browse files
stefano-poglianizonyitoo
authored andcommitted
Implement TimeStamp serialisation (#99)
1 parent b323a2f commit 24352d0

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/encoder/serde.rs

+12-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use serde::ser::{Serialize, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
22
SerializeTupleStruct, SerializeTupleVariant, Serializer};
33

4-
use bson::{Array, Bson, Document, UtcDateTime};
4+
use bson::{Array, Bson, Document, UtcDateTime, TimeStamp};
55
use oid::ObjectId;
66
use try_from::TryFrom;
77

@@ -435,6 +435,17 @@ impl SerializeStructVariant for StructVariantSerializer {
435435
}
436436
}
437437

438+
impl Serialize for TimeStamp {
439+
#[inline]
440+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
441+
where S: Serializer
442+
{
443+
let ts = ((self.t.to_le() as u64) << 32) | (self.i.to_le() as u64);
444+
let doc = Bson::TimeStamp(ts as i64);
445+
doc.serialize(serializer)
446+
}
447+
}
448+
438449
impl Serialize for UtcDateTime {
439450
#[inline]
440451
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>

tests/serde.rs

+18
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,24 @@ fn test_de_map() {
5959
assert_eq!(expected, map);
6060
}
6161

62+
#[test]
63+
fn test_ser_timestamp() {
64+
use bson::TimeStamp;
65+
66+
#[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
67+
struct Foo {
68+
ts: TimeStamp,
69+
}
70+
71+
let foo = Foo { ts: TimeStamp { t: 12, i: 10 } };
72+
73+
let x = bson::to_bson(&foo).unwrap();
74+
assert_eq!(x.as_document().unwrap(), &doc! { "ts": Bson::TimeStamp(0x0000_000C_0000_000A) });
75+
76+
let xfoo: Foo = bson::from_bson(x).unwrap();
77+
assert_eq!(xfoo, foo);
78+
}
79+
6280
#[test]
6381
fn test_de_timestamp() {
6482
use bson::TimeStamp;

0 commit comments

Comments
 (0)