Skip to content

Commit 3c2aa07

Browse files
committed
Optimized impl Display for Bson
1 parent eeb556a commit 3c2aa07

File tree

1 file changed

+23
-23
lines changed

1 file changed

+23
-23
lines changed

src/bson.rs

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -58,43 +58,43 @@ pub type Document = OrderedDocument;
5858

5959
impl Display for Bson {
6060
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
61-
let bson_string = match self {
62-
&Bson::FloatingPoint(f) => format!("{}", f),
63-
&Bson::String(ref s) => format!("\"{}\"", s),
61+
match self {
62+
&Bson::FloatingPoint(f) => write!(fmt, "{}", f),
63+
&Bson::String(ref s) => write!(fmt, "\"{}\"", s),
6464
&Bson::Array(ref vec) => {
65-
let mut string = "[".to_owned();
65+
try!(write!(fmt, "["));
6666

67+
let mut first = true;
6768
for bson in vec.iter() {
68-
if !string.eq("[") {
69-
string.push_str(", ");
69+
if !first {
70+
try!(write!(fmt, ", "));
7071
}
7172

72-
string.push_str(&format!("{}", bson));
73+
try!(write!(fmt, "{}", bson));
74+
first = false;
7375
}
7476

75-
string.push_str("]");
76-
string
77+
write!(fmt, "]")
7778
}
78-
&Bson::Document(ref doc) => format!("{}", doc),
79-
&Bson::Boolean(b) => format!("{}", b),
80-
&Bson::Null => "null".to_owned(),
81-
&Bson::RegExp(ref pat, ref opt) => format!("/{}/{}", pat, opt),
79+
&Bson::Document(ref doc) => write!(fmt, "{}", doc),
80+
&Bson::Boolean(b) => write!(fmt, "{}", b),
81+
&Bson::Null => write!(fmt, "null"),
82+
&Bson::RegExp(ref pat, ref opt) => write!(fmt, "/{}/{}", pat, opt),
8283
&Bson::JavaScriptCode(ref s) |
83-
&Bson::JavaScriptCodeWithScope(ref s, _) => s.to_owned(),
84-
&Bson::I32(i) => format!("{}", i),
85-
&Bson::I64(i) => format!("{}", i),
84+
&Bson::JavaScriptCodeWithScope(ref s, _) => fmt.write_str(&s),
85+
&Bson::I32(i) => write!(fmt, "{}", i),
86+
&Bson::I64(i) => write!(fmt, "{}", i),
8687
&Bson::TimeStamp(i) => {
8788
let time = (i >> 32) as i32;
8889
let inc = (i & 0xFFFFFFFF) as i32;
8990

90-
format!("Timestamp({}, {})", time, inc)
91+
write!(fmt, "Timestamp({}, {})", time, inc)
9192
}
92-
&Bson::Binary(t, ref vec) => format!("BinData({}, 0x{})", u8::from(t), vec.to_hex()),
93-
&Bson::ObjectId(ref id) => format!("ObjectId(\"{}\")", id),
94-
&Bson::UtcDatetime(date_time) => format!("Date(\"{}\")", date_time)
95-
};
96-
97-
fmt.write_str(&bson_string)
93+
&Bson::Binary(t, ref vec) =>
94+
write!(fmt, "BinData({}, 0x{})", u8::from(t), vec.to_hex()),
95+
&Bson::ObjectId(ref id) => write!(fmt, "ObjectId(\"{}\")", id),
96+
&Bson::UtcDatetime(date_time) => write!(fmt, "Date(\"{}\")", date_time)
97+
}
9898
}
9999
}
100100

0 commit comments

Comments
 (0)