Skip to content

Commit 90acaba

Browse files
committed
Made encode_document generic for any map type.
1 parent 718ded6 commit 90acaba

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

src/encoder.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,12 @@
2222
//! Encoder
2323
2424
use std::io::{self, Write};
25+
use std::iter::IntoIterator;
2526
use std::{mem, error, fmt};
2627

2728
use byteorder::{self, LittleEndian, WriteBytesExt};
2829

29-
use bson::{Array, Document, Bson};
30+
use bson::Bson;
3031

3132
#[derive(Debug)]
3233
pub enum EncoderError {
@@ -96,7 +97,7 @@ fn write_f64<W: Write + ?Sized>(writer: &mut W, val: f64) -> EncoderResult<()> {
9697
writer.write_f64::<LittleEndian>(val).map_err(From::from)
9798
}
9899

99-
fn encode_array<W: Write + ?Sized>(writer: &mut W, arr: &Array) -> EncoderResult<()> {
100+
fn encode_array<W: Write + ?Sized>(writer: &mut W, arr: &[Bson]) -> EncoderResult<()> {
100101
let mut buf = Vec::new();
101102
for (key, val) in arr.iter().enumerate() {
102103
try!(encode_bson(&mut buf, &key.to_string(), val));
@@ -108,9 +109,12 @@ fn encode_array<W: Write + ?Sized>(writer: &mut W, arr: &Array) -> EncoderResult
108109
Ok(())
109110
}
110111

111-
pub fn encode_document<'a, W: Write + ?Sized>(writer: &mut W, doc: &Document) -> EncoderResult<()> {
112+
pub fn encode_document
113+
<'a, W: Write + ?Sized, D: IntoIterator<Item=(&'a String, &'a Bson)>>
114+
(writer: &mut W, doc: D) -> EncoderResult<()>
115+
{
112116
let mut buf = Vec::new();
113-
for (key, val) in doc.iter() {
117+
for (key, val) in doc.into_iter() {
114118
try!(encode_bson(&mut buf, key, val));
115119
}
116120

@@ -128,7 +132,7 @@ fn encode_bson<W: Write + ?Sized>(writer: &mut W, key: &str, val: &Bson) -> Enco
128132
&Bson::FloatingPoint(v) => write_f64(writer, v),
129133
&Bson::String(ref v) => write_string(writer, &v),
130134
&Bson::Array(ref v) => encode_array(writer, &v),
131-
&Bson::Document(ref v) => encode_document(writer, &v),
135+
&Bson::Document(ref v) => encode_document(writer, v),
132136
&Bson::Boolean(v) => writer.write_u8(if v { 0x00 } else { 0x01 }).map_err(From::from),
133137
&Bson::RegExp(ref pat, ref opt) => {
134138
try!(write_cstring(writer, pat));

0 commit comments

Comments
 (0)