Skip to content

Commit a19ec90

Browse files
Added support for serializing sequences of things
1 parent 4a1ab95 commit a19ec90

File tree

1 file changed

+29
-10
lines changed

1 file changed

+29
-10
lines changed

src/ser/mod.rs

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use std::io::Write;
22
use std::fmt::Display;
33

4-
use serde::ser::{self, Impossible, Serialize};
4+
use serde::ser::{self, Impossible, Serialize, SerializeSeq};
55

66
use error::{Error, ErrorKind, Result};
77
use self::var::{Map, Struct};
@@ -112,7 +112,7 @@ where
112112
type Ok = ();
113113
type Error = Error;
114114

115-
type SerializeSeq = Impossible<Self::Ok, Self::Error>;
115+
type SerializeSeq = Seq<'w, W>;
116116
type SerializeTuple = Impossible<Self::Ok, Self::Error>;
117117
type SerializeTupleStruct = Impossible<Self::Ok, Self::Error>;
118118
type SerializeTupleVariant = Impossible<Self::Ok, Self::Error>;
@@ -234,10 +234,7 @@ where
234234
}
235235

236236
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
237-
// TODO: Figure out how to constrain the things written to only be composites
238-
Err(
239-
ErrorKind::UnsupportedOperation("serialize_seq".to_string()).into(),
240-
)
237+
Ok(Seq { parent: self })
241238
}
242239

243240
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
@@ -288,6 +285,26 @@ where
288285
}
289286
}
290287

288+
pub struct Seq<'a, W: 'a + Write> {
289+
parent: &'a mut Serializer<W>,
290+
}
291+
292+
impl<'a, W: Write> SerializeSeq for Seq<'a, W> {
293+
type Ok = ();
294+
type Error = Error;
295+
296+
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<Self::Ok>
297+
where
298+
T: Serialize,
299+
{
300+
value.serialize(&mut *self.parent)
301+
}
302+
303+
fn end(self) -> Result<Self::Ok> {
304+
Ok(())
305+
}
306+
}
307+
291308

292309
#[cfg(test)]
293310
mod tests {
@@ -403,9 +420,12 @@ mod tests {
403420
}
404421

405422
#[test]
406-
#[ignore]
407423
fn serialize_a_list() {
408-
let inputs = vec![1, 2, 3, 4];
424+
#[derive(Serialize)]
425+
struct Foo;
426+
427+
let inputs = vec![Foo, Foo, Foo];
428+
let should_be = "<Foo></Foo><Foo></Foo><Foo></Foo>";
409429

410430
let mut buffer = Vec::new();
411431

@@ -415,7 +435,6 @@ mod tests {
415435
}
416436

417437
let got = String::from_utf8(buffer).unwrap();
418-
println!("{}", got);
419-
panic!();
438+
assert_eq!(got, should_be);
420439
}
421440
}

0 commit comments

Comments
 (0)