Skip to content

Commit 463cdc1

Browse files
Árpád Goretity zonyitoo
authored andcommitted
Code cleanup: remove several unnecessary allocations (clone()/to_owned()/to_string()) and ref-deref noops for Copy types; #[derive] some useful std traits for certain types for better interoperability; replace write!(formatter, "string literal") with write_str() (#100)
1 parent ba45a68 commit 463cdc1

File tree

9 files changed

+138
-141
lines changed

9 files changed

+138
-141
lines changed

src/bson.rs

Lines changed: 72 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -87,71 +87,71 @@ impl Default for Bson {
8787

8888
impl Debug for Bson {
8989
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90-
match self {
91-
&Bson::FloatingPoint(p) => write!(f, "FloatingPoint({:?})", p),
92-
&Bson::String(ref s) => write!(f, "String({:?})", s),
93-
&Bson::Array(ref vec) => write!(f, "Array({:?})", vec),
94-
&Bson::Document(ref doc) => write!(f, "Document({:?})", doc),
95-
&Bson::Boolean(b) => write!(f, "Boolean({:?})", b),
96-
&Bson::Null => write!(f, "Null"),
97-
&Bson::RegExp(ref pat, ref opt) => write!(f, "RegExp(/{:?}/{:?})", pat, opt),
98-
&Bson::JavaScriptCode(ref s) => write!(f, "JavaScriptCode({:?})", s),
99-
&Bson::JavaScriptCodeWithScope(ref s, ref scope) => {
90+
match *self {
91+
Bson::FloatingPoint(p) => write!(f, "FloatingPoint({:?})", p),
92+
Bson::String(ref s) => write!(f, "String({:?})", s),
93+
Bson::Array(ref vec) => write!(f, "Array({:?})", vec),
94+
Bson::Document(ref doc) => write!(f, "Document({:?})", doc),
95+
Bson::Boolean(b) => write!(f, "Boolean({:?})", b),
96+
Bson::Null => write!(f, "Null"),
97+
Bson::RegExp(ref pat, ref opt) => write!(f, "RegExp(/{:?}/{:?})", pat, opt),
98+
Bson::JavaScriptCode(ref s) => write!(f, "JavaScriptCode({:?})", s),
99+
Bson::JavaScriptCodeWithScope(ref s, ref scope) => {
100100
write!(f, "JavaScriptCodeWithScope({:?}, {:?})", s, scope)
101101
}
102-
&Bson::I32(v) => write!(f, "I32({:?})", v),
103-
&Bson::I64(v) => write!(f, "I64({:?})", v),
104-
&Bson::TimeStamp(i) => {
102+
Bson::I32(v) => write!(f, "I32({:?})", v),
103+
Bson::I64(v) => write!(f, "I64({:?})", v),
104+
Bson::TimeStamp(i) => {
105105
let time = (i >> 32) as i32;
106106
let inc = (i & 0xFFFFFFFF) as i32;
107107

108108
write!(f, "TimeStamp({}, {})", time, inc)
109109
}
110-
&Bson::Binary(t, ref vec) => write!(f, "BinData({}, 0x{})", u8::from(t), hex::encode(vec)),
111-
&Bson::ObjectId(ref id) => write!(f, "ObjectId({:?})", id),
112-
&Bson::UtcDatetime(date_time) => write!(f, "UtcDatetime({:?})", date_time),
113-
&Bson::Symbol(ref sym) => write!(f, "Symbol({:?})", sym),
110+
Bson::Binary(t, ref vec) => write!(f, "BinData({}, 0x{})", u8::from(t), hex::encode(vec)),
111+
Bson::ObjectId(ref id) => write!(f, "ObjectId({:?})", id),
112+
Bson::UtcDatetime(date_time) => write!(f, "UtcDatetime({:?})", date_time),
113+
Bson::Symbol(ref sym) => write!(f, "Symbol({:?})", sym),
114114
}
115115
}
116116
}
117117

118118
impl Display for Bson {
119119
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
120-
match self {
121-
&Bson::FloatingPoint(f) => write!(fmt, "{}", f),
122-
&Bson::String(ref s) => write!(fmt, "\"{}\"", s),
123-
&Bson::Array(ref vec) => {
124-
write!(fmt, "[")?;
120+
match *self {
121+
Bson::FloatingPoint(f) => write!(fmt, "{}", f),
122+
Bson::String(ref s) => write!(fmt, "\"{}\"", s),
123+
Bson::Array(ref vec) => {
124+
fmt.write_str("[")?;
125125

126126
let mut first = true;
127-
for bson in vec.iter() {
127+
for bson in vec {
128128
if !first {
129-
write!(fmt, ", ")?;
129+
fmt.write_str(", ")?;
130130
}
131131

132132
write!(fmt, "{}", bson)?;
133133
first = false;
134134
}
135135

136-
write!(fmt, "]")
136+
fmt.write_str("]")
137137
}
138-
&Bson::Document(ref doc) => write!(fmt, "{}", doc),
139-
&Bson::Boolean(b) => write!(fmt, "{}", b),
140-
&Bson::Null => write!(fmt, "null"),
141-
&Bson::RegExp(ref pat, ref opt) => write!(fmt, "/{}/{}", pat, opt),
142-
&Bson::JavaScriptCode(ref s) | &Bson::JavaScriptCodeWithScope(ref s, _) => fmt.write_str(&s),
143-
&Bson::I32(i) => write!(fmt, "{}", i),
144-
&Bson::I64(i) => write!(fmt, "{}", i),
145-
&Bson::TimeStamp(i) => {
138+
Bson::Document(ref doc) => write!(fmt, "{}", doc),
139+
Bson::Boolean(b) => write!(fmt, "{}", b),
140+
Bson::Null => write!(fmt, "null"),
141+
Bson::RegExp(ref pat, ref opt) => write!(fmt, "/{}/{}", pat, opt),
142+
Bson::JavaScriptCode(ref s) | Bson::JavaScriptCodeWithScope(ref s, _) => fmt.write_str(&s),
143+
Bson::I32(i) => write!(fmt, "{}", i),
144+
Bson::I64(i) => write!(fmt, "{}", i),
145+
Bson::TimeStamp(i) => {
146146
let time = (i >> 32) as i32;
147147
let inc = (i & 0xFFFFFFFF) as i32;
148148

149149
write!(fmt, "Timestamp({}, {})", time, inc)
150150
}
151-
&Bson::Binary(t, ref vec) => write!(fmt, "BinData({}, 0x{})", u8::from(t), hex::encode(vec)),
152-
&Bson::ObjectId(ref id) => write!(fmt, "ObjectId(\"{}\")", id),
153-
&Bson::UtcDatetime(date_time) => write!(fmt, "Date(\"{}\")", date_time),
154-
&Bson::Symbol(ref sym) => write!(fmt, "Symbol(\"{}\")", sym),
151+
Bson::Binary(t, ref vec) => write!(fmt, "BinData({}, 0x{})", u8::from(t), hex::encode(vec)),
152+
Bson::ObjectId(ref id) => write!(fmt, "ObjectId(\"{}\")", id),
153+
Bson::UtcDatetime(date_time) => write!(fmt, "Date(\"{}\")", date_time),
154+
Bson::Symbol(ref sym) => write!(fmt, "Symbol(\"{}\")", sym),
155155
}
156156
}
157157
}
@@ -205,23 +205,20 @@ impl From<bool> for Bson {
205205
}
206206

207207
impl From<(String, String)> for Bson {
208-
fn from(a: (String, String)) -> Bson {
209-
let (a1, a2) = a;
210-
Bson::RegExp(a1.to_owned(), a2.to_owned())
208+
fn from((pat, opt): (String, String)) -> Bson {
209+
Bson::RegExp(pat, opt)
211210
}
212211
}
213212

214213
impl From<(String, Document)> for Bson {
215-
fn from(a: (String, Document)) -> Bson {
216-
let (a1, a2) = a;
217-
Bson::JavaScriptCodeWithScope(a1, a2)
214+
fn from((code, scope): (String, Document)) -> Bson {
215+
Bson::JavaScriptCodeWithScope(code, scope)
218216
}
219217
}
220218

221219
impl From<(BinarySubtype, Vec<u8>)> for Bson {
222-
fn from(a: (BinarySubtype, Vec<u8>)) -> Bson {
223-
let (a1, a2) = a;
224-
Bson::Binary(a1, a2)
220+
fn from((ty, data): (BinarySubtype, Vec<u8>)) -> Bson {
221+
Bson::Binary(ty, data)
225222
}
226223
}
227224

@@ -257,7 +254,7 @@ impl From<[u8; 12]> for Bson {
257254

258255
impl From<oid::ObjectId> for Bson {
259256
fn from(a: oid::ObjectId) -> Bson {
260-
Bson::ObjectId(a.to_owned())
257+
Bson::ObjectId(a)
261258
}
262259
}
263260

@@ -279,16 +276,16 @@ impl From<Value> for Bson {
279276
Value::Bool(x) => x.into(),
280277
Value::Array(x) => Bson::Array(x.into_iter().map(Bson::from).collect()),
281278
Value::Object(x) => {
282-
Bson::from_extended_document(x.into_iter().map(|(k, v)| (k.clone(), v.into())).collect())
279+
Bson::from_extended_document(x.into_iter().map(|(k, v)| (k, v.into())).collect())
283280
}
284281
Value::Null => Bson::Null,
285282
}
286283
}
287284
}
288285

289-
impl Into<Value> for Bson {
290-
fn into(self) -> Value {
291-
match self {
286+
impl From<Bson> for Value {
287+
fn from(bson: Bson) -> Self {
288+
match bson {
292289
Bson::FloatingPoint(v) => json!(v),
293290
Bson::String(v) => json!(v),
294291
Bson::Array(v) => json!(v),
@@ -336,23 +333,23 @@ impl Into<Value> for Bson {
336333
impl Bson {
337334
/// Get the `ElementType` of this value.
338335
pub fn element_type(&self) -> ElementType {
339-
match self {
340-
&Bson::FloatingPoint(..) => ElementType::FloatingPoint,
341-
&Bson::String(..) => ElementType::Utf8String,
342-
&Bson::Array(..) => ElementType::Array,
343-
&Bson::Document(..) => ElementType::EmbeddedDocument,
344-
&Bson::Boolean(..) => ElementType::Boolean,
345-
&Bson::Null => ElementType::NullValue,
346-
&Bson::RegExp(..) => ElementType::RegularExpression,
347-
&Bson::JavaScriptCode(..) => ElementType::JavaScriptCode,
348-
&Bson::JavaScriptCodeWithScope(..) => ElementType::JavaScriptCodeWithScope,
349-
&Bson::I32(..) => ElementType::Integer32Bit,
350-
&Bson::I64(..) => ElementType::Integer64Bit,
351-
&Bson::TimeStamp(..) => ElementType::TimeStamp,
352-
&Bson::Binary(..) => ElementType::Binary,
353-
&Bson::ObjectId(..) => ElementType::ObjectId,
354-
&Bson::UtcDatetime(..) => ElementType::UtcDatetime,
355-
&Bson::Symbol(..) => ElementType::Symbol,
336+
match *self {
337+
Bson::FloatingPoint(..) => ElementType::FloatingPoint,
338+
Bson::String(..) => ElementType::Utf8String,
339+
Bson::Array(..) => ElementType::Array,
340+
Bson::Document(..) => ElementType::EmbeddedDocument,
341+
Bson::Boolean(..) => ElementType::Boolean,
342+
Bson::Null => ElementType::NullValue,
343+
Bson::RegExp(..) => ElementType::RegularExpression,
344+
Bson::JavaScriptCode(..) => ElementType::JavaScriptCode,
345+
Bson::JavaScriptCodeWithScope(..) => ElementType::JavaScriptCodeWithScope,
346+
Bson::I32(..) => ElementType::Integer32Bit,
347+
Bson::I64(..) => ElementType::Integer64Bit,
348+
Bson::TimeStamp(..) => ElementType::TimeStamp,
349+
Bson::Binary(..) => ElementType::Binary,
350+
Bson::ObjectId(..) => ElementType::ObjectId,
351+
Bson::UtcDatetime(..) => ElementType::UtcDatetime,
352+
Bson::Symbol(..) => ElementType::Symbol,
356353
}
357354
}
358355

@@ -437,7 +434,7 @@ impl Bson {
437434
}
438435

439436
/// Converts from extended format.
440-
/// This function mainly used for [extended JSON format](https://docs.mongodb.com/manual/reference/mongodb-extended-json/).
437+
/// This function is mainly used for [extended JSON format](https://docs.mongodb.com/manual/reference/mongodb-extended-json/).
441438
#[doc(hidden)]
442439
pub fn from_extended_document(values: Document) -> Bson {
443440
if values.len() == 2 {
@@ -478,7 +475,7 @@ impl Bson {
478475
/// If `Bson` is `FloatingPoint`, return its value. Returns `None` otherwise
479476
pub fn as_f64(&self) -> Option<f64> {
480477
match *self {
481-
Bson::FloatingPoint(ref v) => Some(*v),
478+
Bson::FloatingPoint(v) => Some(v),
482479
_ => None,
483480
}
484481
}
@@ -510,23 +507,23 @@ impl Bson {
510507
/// If `Bson` is `Boolean`, return its value. Returns `None` otherwise
511508
pub fn as_bool(&self) -> Option<bool> {
512509
match *self {
513-
Bson::Boolean(ref v) => Some(*v),
510+
Bson::Boolean(v) => Some(v),
514511
_ => None,
515512
}
516513
}
517514

518515
/// If `Bson` is `I32`, return its value. Returns `None` otherwise
519516
pub fn as_i32(&self) -> Option<i32> {
520517
match *self {
521-
Bson::I32(ref v) => Some(*v),
518+
Bson::I32(v) => Some(v),
522519
_ => None,
523520
}
524521
}
525522

526523
/// If `Bson` is `I64`, return its value. Returns `None` otherwise
527524
pub fn as_i64(&self) -> Option<i64> {
528525
match *self {
529-
Bson::I64(ref v) => Some(*v),
526+
Bson::I64(v) => Some(v),
530527
_ => None,
531528
}
532529
}
@@ -558,7 +555,7 @@ impl Bson {
558555
/// If `Bson` is `TimeStamp`, return its value. Returns `None` otherwise
559556
pub fn as_timestamp(&self) -> Option<i64> {
560557
match *self {
561-
Bson::TimeStamp(ref v) => Some(*v),
558+
Bson::TimeStamp(v) => Some(v),
562559
_ => None,
563560
}
564561
}
@@ -587,7 +584,7 @@ impl Bson {
587584
/// timestamp: TimeStamp,
588585
/// }
589586
/// ```
590-
#[derive(Debug, Eq, PartialEq, Clone)]
587+
#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)]
591588
pub struct TimeStamp {
592589
pub t: u32,
593590
pub i: u32,

src/decoder/error.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ impl fmt::Display for DecoderError {
6060
DecoderError::ExpectedField(field_type) => write!(fmt, "expected a field of type `{}`", field_type),
6161
DecoderError::UnknownField(ref field) => write!(fmt, "unknown field `{}`", field),
6262
DecoderError::SyntaxError(ref inner) => inner.fmt(fmt),
63-
DecoderError::EndOfStream => write!(fmt, "end of stream"),
63+
DecoderError::EndOfStream => fmt.write_str("end of stream"),
6464
DecoderError::InvalidType(ref desc) => desc.fmt(fmt),
6565
DecoderError::InvalidLength(ref len, ref desc) => write!(fmt, "expecting length {}, {}", len, desc),
6666
DecoderError::DuplicatedField(ref field) => write!(fmt, "duplicated field `{}`", field),

src/decoder/serde.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ impl<'de> Visitor<'de> for BsonVisitor {
5858
type Value = Bson;
5959

6060
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
61-
write!(f, "expecting a Bson")
61+
f.write_str("expecting a Bson")
6262
}
6363

6464
#[inline]

src/encoder/error.rs

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -21,34 +21,33 @@ impl From<io::Error> for EncoderError {
2121

2222
impl fmt::Display for EncoderError {
2323
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
24-
match self {
25-
&EncoderError::IoError(ref inner) => inner.fmt(fmt),
26-
&EncoderError::InvalidMapKeyType(ref bson) => write!(fmt, "Invalid map key type: {:?}", bson),
27-
&EncoderError::Unknown(ref inner) => inner.fmt(fmt),
28-
&EncoderError::UnsupportedUnsignedType => write!(fmt, "BSON does not support unsigned type"),
29-
&EncoderError::UnsignedTypesValueExceedsRange(value) => {
30-
write!(
31-
fmt,
32-
"BSON does not support unsigned types.
33-
An attempt to encode the value: {} in a signed type failed due to the values size.",
34-
value
35-
)
36-
},
24+
match *self {
25+
EncoderError::IoError(ref inner) => inner.fmt(fmt),
26+
EncoderError::InvalidMapKeyType(ref bson) => write!(fmt, "Invalid map key type: {:?}", bson),
27+
EncoderError::Unknown(ref inner) => inner.fmt(fmt),
28+
EncoderError::UnsupportedUnsignedType => fmt.write_str("BSON does not support unsigned type"),
29+
EncoderError::UnsignedTypesValueExceedsRange(value) => write!(
30+
fmt,
31+
"BSON does not support unsigned types.
32+
An attempt to encode the value: {} in a signed type failed due to the value's size.",
33+
value
34+
),
3735
}
3836
}
3937
}
4038

4139
impl error::Error for EncoderError {
4240
fn description(&self) -> &str {
43-
match self {
44-
&EncoderError::IoError(ref inner) => inner.description(),
45-
&EncoderError::InvalidMapKeyType(_) => "Invalid map key type",
46-
&EncoderError::Unknown(ref inner) => inner,
47-
&EncoderError::UnsupportedUnsignedType => "BSON does not support unsigned type",
48-
&EncoderError::UnsignedTypesValueExceedsRange(_) => "BSON does not support unsigned types.
41+
match *self {
42+
EncoderError::IoError(ref inner) => inner.description(),
43+
EncoderError::InvalidMapKeyType(_) => "Invalid map key type",
44+
EncoderError::Unknown(ref inner) => inner,
45+
EncoderError::UnsupportedUnsignedType => "BSON does not support unsigned type",
46+
EncoderError::UnsignedTypesValueExceedsRange(_) => "BSON does not support unsigned types.
4947
An attempt to encode the value: {} in a signed type failed due to the values size."
5048
}
5149
}
50+
5251
fn cause(&self) -> Option<&error::Error> {
5352
match self {
5453
&EncoderError::IoError(ref inner) => Some(inner),

src/encoder/mod.rs

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -102,37 +102,37 @@ fn encode_bson<W: Write + ?Sized>(writer: &mut W, key: &str, val: &Bson) -> Enco
102102
writer.write_u8(val.element_type() as u8)?;
103103
write_cstring(writer, key)?;
104104

105-
match val {
106-
&Bson::FloatingPoint(v) => write_f64(writer, v),
107-
&Bson::String(ref v) => write_string(writer, &v),
108-
&Bson::Array(ref v) => encode_array(writer, &v),
109-
&Bson::Document(ref v) => encode_document(writer, v),
110-
&Bson::Boolean(v) => writer.write_u8(if v { 0x01 } else { 0x00 }).map_err(From::from),
111-
&Bson::RegExp(ref pat, ref opt) => {
105+
match *val {
106+
Bson::FloatingPoint(v) => write_f64(writer, v),
107+
Bson::String(ref v) => write_string(writer, &v),
108+
Bson::Array(ref v) => encode_array(writer, &v),
109+
Bson::Document(ref v) => encode_document(writer, v),
110+
Bson::Boolean(v) => writer.write_u8(if v { 0x01 } else { 0x00 }).map_err(From::from),
111+
Bson::RegExp(ref pat, ref opt) => {
112112
write_cstring(writer, pat)?;
113113
write_cstring(writer, opt)
114114
}
115-
&Bson::JavaScriptCode(ref code) => write_string(writer, &code),
116-
&Bson::ObjectId(ref id) => writer.write_all(&id.bytes()).map_err(From::from),
117-
&Bson::JavaScriptCodeWithScope(ref code, ref scope) => {
115+
Bson::JavaScriptCode(ref code) => write_string(writer, &code),
116+
Bson::ObjectId(ref id) => writer.write_all(&id.bytes()).map_err(From::from),
117+
Bson::JavaScriptCodeWithScope(ref code, ref scope) => {
118118
let mut buf = Vec::new();
119119
write_string(&mut buf, code)?;
120120
encode_document(&mut buf, scope)?;
121121

122122
write_i32(writer, buf.len() as i32 + 4)?;
123123
writer.write_all(&buf).map_err(From::from)
124124
}
125-
&Bson::I32(v) => write_i32(writer, v),
126-
&Bson::I64(v) => write_i64(writer, v),
127-
&Bson::TimeStamp(v) => write_i64(writer, v),
128-
&Bson::Binary(subtype, ref data) => {
125+
Bson::I32(v) => write_i32(writer, v),
126+
Bson::I64(v) => write_i64(writer, v),
127+
Bson::TimeStamp(v) => write_i64(writer, v),
128+
Bson::Binary(subtype, ref data) => {
129129
write_i32(writer, data.len() as i32)?;
130130
writer.write_u8(From::from(subtype))?;
131131
writer.write_all(data).map_err(From::from)
132132
}
133-
&Bson::UtcDatetime(ref v) => write_i64(writer, (v.timestamp() * 1000) + (v.nanosecond() / 1_000_000) as i64),
134-
&Bson::Null => Ok(()),
135-
&Bson::Symbol(ref v) => write_string(writer, &v),
133+
Bson::UtcDatetime(ref v) => write_i64(writer, (v.timestamp() * 1000) + (v.nanosecond() / 1_000_000) as i64),
134+
Bson::Null => Ok(()),
135+
Bson::Symbol(ref v) => write_string(writer, &v),
136136
}
137137
}
138138

0 commit comments

Comments
 (0)