More cleanup

This commit is contained in:
Erick Tryzelaar 2014-09-01 15:08:34 -07:00
parent a624d05afa
commit 9fe405319e
5 changed files with 59 additions and 167 deletions

View File

@ -1,8 +1,8 @@
extern crate serde2; extern crate serde2;
use std::io;
use std::collections::TreeMap; use std::collections::TreeMap;
use serde2::{Serialize, FormatState, GatherTokens}; use serde2::{Serialize, GatherTokens};
use serde2::json;
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -31,15 +31,15 @@ impl<'a, S: serde2::VisitorState<R>, R> serde2::Visitor<S, R> for FooSerialize<'
match self.state { match self.state {
0 => { 0 => {
self.state += 1; self.state += 1;
Some(state.visit_map_elt("x", &self.value.x)) Some(state.visit_map_elt(true, "x", &self.value.x))
} }
1 => { 1 => {
self.state += 1; self.state += 1;
Some(state.visit_map_elt("y", &self.value.y)) Some(state.visit_map_elt(false, "y", &self.value.y))
} }
2 => { 2 => {
self.state += 1; self.state += 1;
Some(state.visit_map_elt("z", &self.value.z)) Some(state.visit_map_elt(false, "z", &self.value.z))
} }
_ => { _ => {
None None
@ -62,7 +62,7 @@ fn main() {
value.serialize(&mut s); value.serialize(&mut s);
println!("tokens: {}", s.unwrap()); println!("tokens: {}", s.unwrap());
value.serialize(&mut FormatState::new(io::stdout())).unwrap(); println!("json: {}", json::to_string(&value).unwrap().unwrap());
println!(""); println!("");
//// ////
@ -73,7 +73,7 @@ fn main() {
value.serialize(&mut s); value.serialize(&mut s);
println!("tokens: {}", s.unwrap()); println!("tokens: {}", s.unwrap());
value.serialize(&mut FormatState::new(io::stdout())).unwrap(); println!("json: {}", json::to_string(&value).unwrap().unwrap());
println!(""); println!("");
//// ////
@ -87,7 +87,7 @@ fn main() {
value.serialize(&mut s); value.serialize(&mut s);
println!("tokens: {}", s.unwrap()); println!("tokens: {}", s.unwrap());
value.serialize(&mut FormatState::new(io::stdout())).unwrap(); println!("json: {}", json::to_string(&value).unwrap().unwrap());
println!(""); println!("");
//// ////
@ -103,7 +103,7 @@ fn main() {
value.serialize(&mut s); value.serialize(&mut s);
println!("tokens: {}", s.unwrap()); println!("tokens: {}", s.unwrap());
value.serialize(&mut FormatState::new(io::stdout())).unwrap(); println!("json: {}", json::to_string(&value).unwrap().unwrap());
println!(""); println!("");
//// ////
@ -114,6 +114,6 @@ fn main() {
value.serialize(&mut s); value.serialize(&mut s);
println!("tokens: {}", s.unwrap()); println!("tokens: {}", s.unwrap());
value.serialize(&mut FormatState::new(io::stdout())).unwrap(); println!("json: {}", json::to_string(&value).unwrap().unwrap());
println!(""); println!("");
} }

View File

@ -1,3 +1,4 @@
pub use ser::Serializer; pub use self::ser::Serializer;
pub use self::ser::{to_vec, to_string};
pub mod ser; pub mod ser;

View File

@ -2,7 +2,7 @@ use std::io;
use std::num::{FPNaN, FPInfinite}; use std::num::{FPNaN, FPInfinite};
use std::f64; use std::f64;
use super::super::ser as ser; use ser;
/// A structure for implementing serialization to JSON. /// A structure for implementing serialization to JSON.
pub struct Serializer<W> { pub struct Serializer<W> {
@ -69,14 +69,7 @@ impl<W: Writer> ser::VisitorState<io::IoResult<()>> for Serializer<W> {
>(&mut self, mut visitor: V) -> io::IoResult<()> { >(&mut self, mut visitor: V) -> io::IoResult<()> {
try!(write!(self.writer, "[")); try!(write!(self.writer, "["));
let mut first = true;
loop { loop {
if first {
first = false;
} else {
try!(write!(self.writer, ", "));
}
match visitor.visit(self) { match visitor.visit(self) {
Some(Ok(())) => { } Some(Ok(())) => { }
Some(Err(err)) => { return Err(err); } Some(Err(err)) => { return Err(err); }
@ -88,7 +81,11 @@ impl<W: Writer> ser::VisitorState<io::IoResult<()>> for Serializer<W> {
fn visit_seq_elt< fn visit_seq_elt<
T: ser::Serialize<Serializer<W>, io::IoResult<()>> T: ser::Serialize<Serializer<W>, io::IoResult<()>>
>(&mut self, value: T) -> io::IoResult<()> { >(&mut self, first: bool, value: T) -> io::IoResult<()> {
if !first {
try!(write!(self.writer, ", "));
}
value.serialize(self) value.serialize(self)
} }
@ -97,14 +94,7 @@ impl<W: Writer> ser::VisitorState<io::IoResult<()>> for Serializer<W> {
>(&mut self, mut visitor: V) -> io::IoResult<()> { >(&mut self, mut visitor: V) -> io::IoResult<()> {
try!(write!(self.writer, "{{")); try!(write!(self.writer, "{{"));
let mut first = true;
loop { loop {
if first {
first = false;
} else {
try!(write!(self.writer, ", "));
}
match visitor.visit(self) { match visitor.visit(self) {
Some(Ok(())) => { } Some(Ok(())) => { }
Some(Err(err)) => { return Err(err); } Some(Err(err)) => { return Err(err); }
@ -117,7 +107,11 @@ impl<W: Writer> ser::VisitorState<io::IoResult<()>> for Serializer<W> {
fn visit_map_elt< fn visit_map_elt<
K: ser::Serialize<Serializer<W>, io::IoResult<()>>, K: ser::Serialize<Serializer<W>, io::IoResult<()>>,
V: ser::Serialize<Serializer<W>, io::IoResult<()>> V: ser::Serialize<Serializer<W>, io::IoResult<()>>
>(&mut self, key: K, value: V) -> io::IoResult<()> { >(&mut self, first: bool, key: K, value: V) -> io::IoResult<()> {
if !first {
try!(write!(self.writer, ", "));
}
try!(key.serialize(self)); try!(key.serialize(self));
try!(write!(self.writer, ": ")); try!(write!(self.writer, ": "));
value.serialize(self) value.serialize(self)
@ -173,3 +167,19 @@ fn fmt_f64_or_null<W: Writer>(wr: &mut W, value: f64) -> io::IoResult<()> {
_ => wr.write_str(f64::to_str_digits(value, 6).as_slice()), _ => wr.write_str(f64::to_str_digits(value, 6).as_slice()),
} }
} }
pub fn to_vec<
T: ser::Serialize<Serializer<io::MemWriter>, io::IoResult<()>>
>(value: &T) -> io::IoResult<Vec<u8>> {
let writer = io::MemWriter::new();
let mut state = Serializer::new(writer);
try!(value.serialize(&mut state));
Ok(state.unwrap().unwrap())
}
pub fn to_string<
T: ser::Serialize<Serializer<io::MemWriter>, io::IoResult<()>>
>(value: &T) -> io::IoResult<Result<String, Vec<u8>>> {
let vec = try!(to_vec(value));
Ok(String::from_utf8(vec))
}

View File

@ -1,6 +1,5 @@
pub use ser::{Serialize, Serializer}; pub use ser::{Serialize, Serializer};
pub use ser::{Visitor, VisitorState}; pub use ser::{Visitor, VisitorState};
pub use ser::FormatState;
pub use ser::GatherTokens; pub use ser::GatherTokens;
pub mod ser; pub mod ser;

View File

@ -1,5 +1,3 @@
use std::io::IoResult;
use std::io;
use std::collections::TreeMap; use std::collections::TreeMap;
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -106,7 +104,7 @@ pub trait VisitorState<R> {
fn visit_seq_elt< fn visit_seq_elt<
T: Serialize<Self, R> T: Serialize<Self, R>
>(&mut self, value: T) -> R; >(&mut self, first: bool, value: T) -> R;
fn visit_map< fn visit_map<
V: Visitor<Self, R> V: Visitor<Self, R>
@ -122,7 +120,7 @@ pub trait VisitorState<R> {
fn visit_map_elt< fn visit_map_elt<
K: Serialize<Self, R>, K: Serialize<Self, R>,
V: Serialize<Self, R> V: Serialize<Self, R>
>(&mut self, key: K, value: V) -> R; >(&mut self, first: bool, key: K, value: V) -> R;
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -141,14 +139,16 @@ impl<S: VisitorState<R>, R> Serialize<S, R> for &'static str {
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
struct SeqIteratorVisitor<Iter> { pub struct SeqIteratorVisitor<Iter> {
iter: Iter, iter: Iter,
first: bool,
} }
impl<T, Iter: Iterator<T>> SeqIteratorVisitor<Iter> { impl<T, Iter: Iterator<T>> SeqIteratorVisitor<Iter> {
pub fn new(iter: Iter) -> SeqIteratorVisitor<Iter> { pub fn new(iter: Iter) -> SeqIteratorVisitor<Iter> {
SeqIteratorVisitor { SeqIteratorVisitor {
iter: iter, iter: iter,
first: true,
} }
} }
} }
@ -160,8 +160,11 @@ impl<
R R
> Visitor<S, R> for SeqIteratorVisitor<Iter> { > Visitor<S, R> for SeqIteratorVisitor<Iter> {
fn visit(&mut self, state: &mut S) -> Option<R> { fn visit(&mut self, state: &mut S) -> Option<R> {
let first = self.first;
self.first = false;
match self.iter.next() { match self.iter.next() {
Some(value) => Some(state.visit_seq_elt(value)), Some(value) => Some(state.visit_seq_elt(first, value)),
None => None None => None
} }
} }
@ -185,8 +188,9 @@ impl<
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
struct MapIteratorVisitor<Iter> { pub struct MapIteratorVisitor<Iter> {
iter: Iter, iter: Iter,
first: bool,
} }
impl< impl<
@ -196,6 +200,7 @@ impl<
pub fn new(iter: Iter) -> MapIteratorVisitor<Iter> { pub fn new(iter: Iter) -> MapIteratorVisitor<Iter> {
MapIteratorVisitor { MapIteratorVisitor {
iter: iter, iter: iter,
first: true,
} }
} }
} }
@ -208,8 +213,11 @@ impl<
R R
> Visitor<S, R> for MapIteratorVisitor<Iter> { > Visitor<S, R> for MapIteratorVisitor<Iter> {
fn visit(&mut self, state: &mut S) -> Option<R> { fn visit(&mut self, state: &mut S) -> Option<R> {
let first = self.first;
self.first = false;
match self.iter.next() { match self.iter.next() {
Some((key, value)) => Some(state.visit_map_elt(key, value)), Some((key, value)) => Some(state.visit_map_elt(first, key, value)),
None => None None => None
} }
} }
@ -261,12 +269,12 @@ impl<
0 => { 0 => {
self.state += 1; self.state += 1;
let (ref value, _) = *self.value; let (ref value, _) = *self.value;
Some(state.visit_seq_elt(value)) Some(state.visit_seq_elt(true, value))
} }
1 => { 1 => {
self.state += 1; self.state += 1;
let (_, ref value) = *self.value; let (_, ref value) = *self.value;
Some(state.visit_seq_elt(value)) Some(state.visit_seq_elt(false, value))
} }
_ => { _ => {
None None
@ -382,7 +390,7 @@ impl VisitorState<()> for GatherTokens {
fn visit_seq_elt< fn visit_seq_elt<
T: Serialize<GatherTokens, ()> T: Serialize<GatherTokens, ()>
>(&mut self, value: T) -> () { >(&mut self, _first: bool, value: T) -> () {
value.serialize(self) value.serialize(self)
} }
@ -417,134 +425,8 @@ impl VisitorState<()> for GatherTokens {
fn visit_map_elt< fn visit_map_elt<
K: Serialize<GatherTokens, ()>, K: Serialize<GatherTokens, ()>,
V: Serialize<GatherTokens, ()> V: Serialize<GatherTokens, ()>
>(&mut self, key: K, value: V) -> () { >(&mut self, _first: bool, key: K, value: V) -> () {
key.serialize(self); key.serialize(self);
value.serialize(self) value.serialize(self)
} }
}
///////////////////////////////////////////////////////////////////////////////
pub struct FormatState<W: Writer> {
writer: W,
}
impl<W: Writer> FormatState<W> {
pub fn new(writer: W) -> FormatState<W> {
FormatState {
writer: writer,
}
}
pub fn unwrap(self) -> W {
self.writer
}
}
impl<W: Writer> VisitorState<IoResult<()>> for FormatState<W> {
fn visit_null(&mut self) -> IoResult<()> {
write!(self.writer, "()")
}
fn visit_bool(&mut self, value: bool) -> IoResult<()> {
write!(self.writer, "{}", value)
}
fn visit_i64(&mut self, value: i64) -> IoResult<()> {
write!(self.writer, "{}", value)
}
fn visit_u64(&mut self, value: u64) -> IoResult<()> {
write!(self.writer, "{}", value)
}
fn visit_f64(&mut self, value: f64) -> IoResult<()> {
write!(self.writer, "{}", value)
}
fn visit_char(&mut self, value: char) -> io::IoResult<()> {
write!(self.writer, "{}", value)
}
fn visit_str(&mut self, value: &'static str) -> IoResult<()> {
write!(self.writer, "{}", value)
}
fn visit_seq<
V: Visitor<FormatState<W>, IoResult<()>>
>(&mut self, mut visitor: V) -> IoResult<()> {
try!(write!(self.writer, "["));
let mut first = true;
loop {
if first {
first = false;
} else {
try!(write!(self.writer, ", "));
}
match visitor.visit(self) {
Some(Ok(())) => { }
Some(Err(err)) => { return Err(err); }
None => { break; }
}
}
write!(self.writer, "]")
}
fn visit_seq_elt<
T: Serialize<FormatState<W>, IoResult<()>>
>(&mut self, value: T) -> IoResult<()> {
value.serialize(self)
}
fn visit_map<
V: Visitor<FormatState<W>, IoResult<()>>
>(&mut self, mut visitor: V) -> IoResult<()> {
try!(write!(self.writer, "{{"));
let mut first = true;
loop {
if first {
first = false;
} else {
try!(write!(self.writer, ", "));
}
match visitor.visit(self) {
Some(Ok(())) => { }
Some(Err(err)) => { return Err(err); }
None => { break; }
}
}
write!(self.writer, "}}")
}
fn visit_map_elt<
K: Serialize<FormatState<W>, IoResult<()>>,
V: Serialize<FormatState<W>, IoResult<()>>
>(&mut self, key: K, value: V) -> IoResult<()> {
try!(key.serialize(self));
try!(write!(self.writer, ": "));
value.serialize(self)
}
}
///////////////////////////////////////////////////////////////////////////////
pub fn to_format_vec<
T: Serialize<FormatState<io::MemWriter>, IoResult<()>>
>(value: &T) -> IoResult<Vec<u8>> {
let writer = io::MemWriter::new();
let mut state = FormatState::new(writer);
try!(value.serialize(&mut state));
Ok(state.unwrap().unwrap())
}
pub fn to_format_string<
T: Serialize<FormatState<io::MemWriter>, IoResult<()>>
>(value: &T) -> IoResult<Result<String, Vec<u8>>> {
let vec = try!(to_format_vec(value));
Ok(String::from_utf8(vec))
} }