Skip to content

Commit eeb556a

Browse files
committed
Improved ObjectId displaying and fixed its Bson display
1 parent c31480b commit eeb556a

File tree

3 files changed

+14
-16
lines changed

3 files changed

+14
-16
lines changed

src/bson.rs

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -90,16 +90,7 @@ impl Display for Bson {
9090
format!("Timestamp({}, {})", time, inc)
9191
}
9292
&Bson::Binary(t, ref vec) => format!("BinData({}, 0x{})", u8::from(t), vec.to_hex()),
93-
&Bson::ObjectId(ref id) => {
94-
let mut vec = vec![];
95-
96-
for byte in id.bytes().iter() {
97-
vec.push(byte.to_owned());
98-
}
99-
100-
let string = unsafe { String::from_utf8_unchecked(vec) };
101-
format!("ObjectId(\"{}\")", string)
102-
}
93+
&Bson::ObjectId(ref id) => format!("ObjectId(\"{}\")", id),
10394
&Bson::UtcDatetime(date_time) => format!("Date(\"{}\")", date_time)
10495
};
10596

src/oid.rs

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -146,11 +146,6 @@ impl ObjectId {
146146
self.id
147147
}
148148

149-
/// Returns a 12-byte (24-char) hexadecimal string
150-
pub fn to_string(&self) -> String {
151-
self.id.to_hex()
152-
}
153-
154149
/// Retrieves the timestamp (seconds since epoch) from an ObjectId.
155150
pub fn timestamp(&self) -> u32 {
156151
BigEndian::read_u32(&self.id)
@@ -271,6 +266,18 @@ impl ObjectId {
271266
}
272267
}
273268

269+
impl ToHex for ObjectId {
270+
fn to_hex(&self) -> String {
271+
self.id.to_hex()
272+
}
273+
}
274+
275+
impl fmt::Display for ObjectId {
276+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
277+
f.write_str(&self.to_hex())
278+
}
279+
}
280+
274281
impl Decodable for ObjectId {
275282
fn decode<D: Decoder>(d: &mut D) -> result::Result<Self, D::Error> {
276283
let str = try!(d.read_str());

tests/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ fn test_format() {
4545
"date" => (Bson::UtcDatetime(date))
4646
};
4747

48-
let expected = format!("{{ float: 2.4, string: \"hello\", array: [\"testing\", 1], doc: {{ fish: \"in\", a: \"barrel\", !: 1 }}, bool: true, null: null, regexp: /s[ao]d/i, code: function(x) {{ return x._id; }}, i32: 12, i64: -55, timestamp: Timestamp(0, 229999444), binary: BinData(5, 0x{}), _id: ObjectId(\"{}\"), date: Date(\"{}\") }}", "thingies".as_bytes().to_hex(), id_string, date);
48+
let expected = format!("{{ float: 2.4, string: \"hello\", array: [\"testing\", 1], doc: {{ fish: \"in\", a: \"barrel\", !: 1 }}, bool: true, null: null, regexp: /s[ao]d/i, code: function(x) {{ return x._id; }}, i32: 12, i64: -55, timestamp: Timestamp(0, 229999444), binary: BinData(5, 0x{}), _id: ObjectId(\"{}\"), date: Date(\"{}\") }}", "thingies".as_bytes().to_hex(), id_string.as_bytes().to_hex(), date);
4949

5050
assert_eq!(expected, format!("{}", doc));
5151
}

0 commit comments

Comments
 (0)