Skip to content

Commit b55e958

Browse files
RUST-868 Add serialize_object_id_as_hex_string helper (#273)
1 parent 84ced4d commit b55e958

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/serde_helpers.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
33
use std::{convert::TryFrom, result::Result};
44

5-
use serde::{ser, Serializer};
5+
use serde::{ser, Serialize, Serializer};
6+
7+
use crate::oid::ObjectId;
68

79
pub use bson_datetime_as_rfc3339_string::{
810
deserialize as deserialize_bson_datetime_from_rfc3339_string,
@@ -82,6 +84,14 @@ pub fn serialize_u64_as_i64<S: Serializer>(val: &u64, serializer: S) -> Result<S
8284
}
8385
}
8486

87+
/// Serializes an [`ObjectId`] as a hex string.
88+
pub fn serialize_object_id_as_hex_string<S: Serializer>(
89+
val: &ObjectId,
90+
serializer: S,
91+
) -> Result<S::Ok, S::Error> {
92+
val.to_hex().serialize(serializer)
93+
}
94+
8595
/// Contains functions to serialize a u32 as an f64 (BSON double) and deserialize a
8696
/// u32 from an f64 (BSON double).
8797
///

src/tests/serde.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use crate::{
1111
bson_datetime_as_rfc3339_string,
1212
hex_string_as_object_id,
1313
rfc3339_string_as_bson_datetime,
14+
serialize_object_id_as_hex_string,
1415
timestamp_as_u32,
1516
u32_as_timestamp,
1617
},
@@ -898,3 +899,19 @@ fn large_dates() {
898899
&DateTime::MIN
899900
);
900901
}
902+
903+
#[test]
904+
fn oid_as_hex_string() {
905+
let _guard = LOCK.run_concurrently();
906+
907+
#[derive(Serialize)]
908+
struct Foo {
909+
#[serde(serialize_with = "serialize_object_id_as_hex_string")]
910+
oid: ObjectId,
911+
}
912+
913+
let oid = ObjectId::new();
914+
let foo = Foo { oid };
915+
let doc = to_document(&foo).unwrap();
916+
assert_eq!(doc.get_str("oid").unwrap(), oid.to_hex());
917+
}

0 commit comments

Comments
 (0)