typarameterize Serializer

This commit is contained in:
Erick Tryzelaar 2014-08-31 20:44:19 -07:00
parent dbbb016ada
commit 3a6eb83da6
4 changed files with 187 additions and 232 deletions

View File

@ -72,15 +72,10 @@ fn expand_deriving_serializable(cx: &mut ExtCtxt,
let trait_def = TraitDef { let trait_def = TraitDef {
span: sp, span: sp,
attributes: vec!(), attributes: vec!(),
path: Path::new(vec!("serde", "ser", "Serializable")),
/*
path: Path::new_(vec!("serde", "ser", "Serializable"), None, path: Path::new_(vec!("serde", "ser", "Serializable"), None,
vec!(box Literal(Path::new_local("__S")), vec!(box Literal(Path::new_local("__S")),
box Literal(Path::new_local("__E"))), true), box Literal(Path::new_local("__E"))), true),
*/
additional_bounds: Vec::new(), additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
/*
generics: LifetimeBounds { generics: LifetimeBounds {
lifetimes: Vec::new(), lifetimes: Vec::new(),
bounds: vec!(("__S", None, vec!(Path::new_( bounds: vec!(("__S", None, vec!(Path::new_(
@ -88,32 +83,10 @@ fn expand_deriving_serializable(cx: &mut ExtCtxt,
vec!(box Literal(Path::new_local("__E"))), true))), vec!(box Literal(Path::new_local("__E"))), true))),
("__E", None, vec!())) ("__E", None, vec!()))
}, },
*/
methods: vec!( methods: vec!(
MethodDef { MethodDef {
name: "serialize", name: "serialize",
generics: LifetimeBounds { generics: LifetimeBounds::empty(),
lifetimes: Vec::new(),
bounds: vec!(
(
"__S",
None,
vec!(
Path::new_(
vec!("serde", "ser", "Serializer"),
None,
vec!(box Literal(Path::new_local("__E"))),
true
)
),
),
(
"__E",
None,
vec!(),
),
)
},
explicit_self: borrowed_explicit_self(), explicit_self: borrowed_explicit_self(),
args: vec!(Ptr(box Literal(Path::new_local("__S")), args: vec!(Ptr(box Literal(Path::new_local("__S")),
Borrowed(None, MutMutable))), Borrowed(None, MutMutable))),

View File

@ -35,12 +35,9 @@ enum HttpProtocol {
HTTP11, HTTP11,
} }
impl ser::Serializable for HttpProtocol { impl<S: ser::Serializer<E>, E> ser::Serializable<S, E> for HttpProtocol {
#[inline] #[inline]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: ser::Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
s.serialize_uint(*self as uint) s.serialize_uint(*self as uint)
} }
} }
@ -67,12 +64,9 @@ enum HttpMethod {
PATCH, PATCH,
} }
impl ser::Serializable for HttpMethod { impl<S: ser::Serializer<E>, E> ser::Serializable<S, E> for HttpMethod {
#[inline] #[inline]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: ser::Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
s.serialize_uint(*self as uint) s.serialize_uint(*self as uint)
} }
} }
@ -92,12 +86,9 @@ enum CacheStatus {
Hit, Hit,
} }
impl ser::Serializable for CacheStatus { impl<S: ser::Serializer<E>, E> ser::Serializable<S, E> for CacheStatus {
#[inline] #[inline]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: ser::Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
s.serialize_uint(*self as uint) s.serialize_uint(*self as uint)
} }
} }
@ -126,12 +117,9 @@ enum OriginProtocol {
HTTPS, HTTPS,
} }
impl ser::Serializable for OriginProtocol { impl<S: ser::Serializer<E>, E> ser::Serializable<S, E> for OriginProtocol {
#[inline] #[inline]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: ser::Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
s.serialize_uint(*self as uint) s.serialize_uint(*self as uint)
} }
} }
@ -152,12 +140,9 @@ enum ZonePlan {
ENT, ENT,
} }
impl ser::Serializable for ZonePlan { impl<S: ser::Serializer<E>, E> ser::Serializable<S, E> for ZonePlan {
#[inline] #[inline]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: ser::Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
s.serialize_uint(*self as uint) s.serialize_uint(*self as uint)
} }
} }
@ -429,12 +414,9 @@ enum Country {
ZW, ZW,
} }
impl ser::Serializable for Country { impl<S: ser::Serializer<E>, E> ser::Serializable<S, E> for Country {
#[inline] #[inline]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: ser::Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
s.serialize_uint(*self as uint) s.serialize_uint(*self as uint)
} }
} }
@ -799,12 +781,10 @@ fn bench_serializer_mem_writer(b: &mut Bencher) {
b.iter(|| { b.iter(|| {
//let _json = json::to_str(&log).unwrap(); //let _json = json::to_str(&log).unwrap();
let mut wr = MemWriter::with_capacity(1024); let wr = MemWriter::with_capacity(1024);
{ let mut serializer = json::Serializer::new(wr);
let mut serializer = json::Serializer::new(wr.by_ref()); log.serialize(&mut serializer).unwrap();
log.serialize(&mut serializer).unwrap(); let _json = serializer.unwrap().unwrap();
}
let _json = wr.unwrap();
}); });
} }
@ -816,12 +796,10 @@ fn bench_serializer_my_mem_writer0(b: &mut Bencher) {
b.iter(|| { b.iter(|| {
//let _json = json::to_str(&log).unwrap(); //let _json = json::to_str(&log).unwrap();
let mut wr = MyMemWriter0::with_capacity(1024); let wr = MyMemWriter0::with_capacity(1024);
{ let mut serializer = json::Serializer::new(wr);
let mut serializer = json::Serializer::new(wr.by_ref()); log.serialize(&mut serializer).unwrap();
log.serialize(&mut serializer).unwrap(); let _json = serializer.unwrap().unwrap();
}
let _json = wr.unwrap();
}); });
} }
@ -833,12 +811,10 @@ fn bench_serializer_my_mem_writer1(b: &mut Bencher) {
b.iter(|| { b.iter(|| {
//let _json = json::to_str(&log).unwrap(); //let _json = json::to_str(&log).unwrap();
let mut wr = MyMemWriter1::with_capacity(1024); let wr = MyMemWriter1::with_capacity(1024);
{ let mut serializer = json::Serializer::new(wr);
let mut serializer = json::Serializer::new(wr.by_ref()); log.serialize(&mut serializer).unwrap();
log.serialize(&mut serializer).unwrap(); let _json = serializer.unwrap().unwrap();
}
let _json = wr.unwrap();
}); });
} }
@ -850,12 +826,10 @@ fn bench_serializer_my_mem_writer2(b: &mut Bencher) {
b.iter(|| { b.iter(|| {
//let _json = json::to_str(&log).unwrap(); //let _json = json::to_str(&log).unwrap();
let mut wr = MyMemWriter2::with_capacity(1024); let wr = MyMemWriter2::with_capacity(1024);
{ let mut serializer = json::Serializer::new(wr);
let mut serializer = json::Serializer::new(wr.by_ref()); log.serialize(&mut serializer).unwrap();
log.serialize(&mut serializer).unwrap(); let _json = serializer.unwrap().unwrap();
}
let _json = wr.unwrap();
}); });
} }
@ -867,12 +841,10 @@ fn bench_serializer_my_mem_writer3(b: &mut Bencher) {
b.iter(|| { b.iter(|| {
//let _json = json::to_str(&log).unwrap(); //let _json = json::to_str(&log).unwrap();
let mut wr = MyMemWriter3::with_capacity(1024); let wr = MyMemWriter3::with_capacity(1024);
{ let mut serializer = json::Serializer::new(wr);
let mut serializer = json::Serializer::new(wr.by_ref()); log.serialize(&mut serializer).unwrap();
log.serialize(&mut serializer).unwrap(); let _json = serializer.unwrap().unwrap();
}
let _json = wr.unwrap();
}); });
} }
@ -1256,10 +1228,10 @@ fn bench_manual_my_mem_writer3_escape(b: &mut Bencher) {
}); });
} }
fn direct<W: Writer>(mut wr: W, log: &Log) { fn direct<W: Writer>(wr: W, log: &Log) {
use ser::Serializer; use ser::Serializer;
let mut serializer = json::Serializer::new(wr.by_ref()); let mut serializer = json::Serializer::new(wr);
serializer.serialize_struct_start("Log", 12).unwrap(); serializer.serialize_struct_start("Log", 12).unwrap();
serializer.serialize_struct_elt("timestamp", &log.timestamp).unwrap(); serializer.serialize_struct_elt("timestamp", &log.timestamp).unwrap();

View File

@ -489,12 +489,9 @@ impl fmt::Show for Json {
} }
} }
impl ser::Serializable for Json { impl<S: ser::Serializer<E>, E> ser::Serializable<S, E> for Json {
#[inline] #[inline]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: ser::Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
match *self { match *self {
Null => { Null => {
().serialize(s) ().serialize(s)
@ -913,6 +910,11 @@ impl<W: Writer> Serializer<W> {
first: true, first: true,
} }
} }
/// Unwrap the Writer from the Serializer.
pub fn unwrap(self) -> W {
self.wr
}
} }
impl<W: Writer> ser::Serializer<io::IoError> for Serializer<W> { impl<W: Writer> ser::Serializer<io::IoError> for Serializer<W> {
@ -1008,7 +1010,7 @@ impl<W: Writer> ser::Serializer<io::IoError> for Serializer<W> {
#[inline] #[inline]
fn serialize_tuple_elt< fn serialize_tuple_elt<
T: Serializable T: Serializable<Serializer<W>, io::IoError>
>(&mut self, value: &T) -> IoResult<()> { >(&mut self, value: &T) -> IoResult<()> {
if self.first { if self.first {
self.first = false; self.first = false;
@ -1031,7 +1033,7 @@ impl<W: Writer> ser::Serializer<io::IoError> for Serializer<W> {
#[inline] #[inline]
fn serialize_struct_elt< fn serialize_struct_elt<
T: Serializable T: Serializable<Serializer<W>, io::IoError>
>(&mut self, name: &str, value: &T) -> IoResult<()> { >(&mut self, name: &str, value: &T) -> IoResult<()> {
if self.first { if self.first {
self.first = false; self.first = false;
@ -1058,7 +1060,7 @@ impl<W: Writer> ser::Serializer<io::IoError> for Serializer<W> {
#[inline] #[inline]
fn serialize_enum_elt< fn serialize_enum_elt<
T: Serializable T: Serializable<Serializer<W>, io::IoError>
>(&mut self, value: &T) -> IoResult<()> { >(&mut self, value: &T) -> IoResult<()> {
if self.first { if self.first {
self.first = false; self.first = false;
@ -1075,7 +1077,7 @@ impl<W: Writer> ser::Serializer<io::IoError> for Serializer<W> {
#[inline] #[inline]
fn serialize_option< fn serialize_option<
T: Serializable T: Serializable<Serializer<W>, io::IoError>
>(&mut self, v: &Option<T>) -> IoResult<()> { >(&mut self, v: &Option<T>) -> IoResult<()> {
match *v { match *v {
Some(ref v) => { Some(ref v) => {
@ -1089,7 +1091,7 @@ impl<W: Writer> ser::Serializer<io::IoError> for Serializer<W> {
#[inline] #[inline]
fn serialize_seq< fn serialize_seq<
T: Serializable, T: Serializable<Serializer<W>, io::IoError>,
Iter: Iterator<T> Iter: Iterator<T>
>(&mut self, mut iter: Iter) -> IoResult<()> { >(&mut self, mut iter: Iter) -> IoResult<()> {
try!(self.wr.write_str("[")); try!(self.wr.write_str("["));
@ -1108,8 +1110,8 @@ impl<W: Writer> ser::Serializer<io::IoError> for Serializer<W> {
#[inline] #[inline]
fn serialize_map< fn serialize_map<
K: Serializable, K: Serializable<Serializer<W>, io::IoError>,
V: Serializable, V: Serializable<Serializer<W>, io::IoError>,
Iter: Iterator<(K, V)> Iter: Iterator<(K, V)>
>(&mut self, mut iter: Iter) -> IoResult<()> { >(&mut self, mut iter: Iter) -> IoResult<()> {
try!(self.wr.write_str("{")); try!(self.wr.write_str("{"));
@ -1147,6 +1149,11 @@ impl<W: Writer> PrettySerializer<W> {
} }
} }
/// Unwrap the Writer from the Serializer.
pub fn unwrap(self) -> W {
self.wr
}
#[inline] #[inline]
fn serialize_sep(&mut self) -> IoResult<()> { fn serialize_sep(&mut self) -> IoResult<()> {
if self.first { if self.first {
@ -1267,7 +1274,7 @@ impl<W: Writer> ser::Serializer<io::IoError> for PrettySerializer<W> {
#[inline] #[inline]
fn serialize_tuple_elt< fn serialize_tuple_elt<
T: Serializable T: Serializable<PrettySerializer<W>, io::IoError>
>(&mut self, value: &T) -> IoResult<()> { >(&mut self, value: &T) -> IoResult<()> {
try!(self.serialize_sep()); try!(self.serialize_sep());
value.serialize(self) value.serialize(self)
@ -1286,7 +1293,7 @@ impl<W: Writer> ser::Serializer<io::IoError> for PrettySerializer<W> {
#[inline] #[inline]
fn serialize_struct_elt< fn serialize_struct_elt<
T: Serializable T: Serializable<PrettySerializer<W>, io::IoError>
>(&mut self, name: &str, value: &T) -> IoResult<()> { >(&mut self, name: &str, value: &T) -> IoResult<()> {
try!(self.serialize_sep()); try!(self.serialize_sep());
try!(self.serialize_str(name)); try!(self.serialize_str(name));
@ -1311,7 +1318,7 @@ impl<W: Writer> ser::Serializer<io::IoError> for PrettySerializer<W> {
#[inline] #[inline]
fn serialize_enum_elt< fn serialize_enum_elt<
T: Serializable T: Serializable<PrettySerializer<W>, io::IoError>
>(&mut self, value: &T) -> IoResult<()> { >(&mut self, value: &T) -> IoResult<()> {
try!(self.serialize_sep()); try!(self.serialize_sep());
value.serialize(self) value.serialize(self)
@ -1325,7 +1332,7 @@ impl<W: Writer> ser::Serializer<io::IoError> for PrettySerializer<W> {
#[inline] #[inline]
fn serialize_option< fn serialize_option<
T: Serializable T: Serializable<PrettySerializer<W>, io::IoError>
>(&mut self, v: &Option<T>) -> IoResult<()> { >(&mut self, v: &Option<T>) -> IoResult<()> {
match *v { match *v {
Some(ref v) => { Some(ref v) => {
@ -1339,7 +1346,7 @@ impl<W: Writer> ser::Serializer<io::IoError> for PrettySerializer<W> {
#[inline] #[inline]
fn serialize_seq< fn serialize_seq<
T: Serializable, T: Serializable<PrettySerializer<W>, io::IoError>,
Iter: Iterator<T> Iter: Iterator<T>
>(&mut self, mut iter: Iter) -> IoResult<()> { >(&mut self, mut iter: Iter) -> IoResult<()> {
try!(self.wr.write_str("[")); try!(self.wr.write_str("["));
@ -1355,8 +1362,8 @@ impl<W: Writer> ser::Serializer<io::IoError> for PrettySerializer<W> {
#[inline] #[inline]
fn serialize_map< fn serialize_map<
K: Serializable, K: Serializable<PrettySerializer<W>, io::IoError>,
V: Serializable, V: Serializable<PrettySerializer<W>, io::IoError>,
Iter: Iterator<(K, V)> Iter: Iterator<(K, V)>
>(&mut self, mut iter: Iter) -> IoResult<()> { >(&mut self, mut iter: Iter) -> IoResult<()> {
try!(self.wr.write_str("{")); try!(self.wr.write_str("{"));
@ -1375,36 +1382,40 @@ impl<W: Writer> ser::Serializer<io::IoError> for PrettySerializer<W> {
/// Encode the specified struct into a json `[u8]` buffer. /// Encode the specified struct into a json `[u8]` buffer.
#[inline] #[inline]
pub fn to_vec<T: ser::Serializable>(value: &T) -> Vec<u8> { pub fn to_vec<
let mut wr = MemWriter::with_capacity(1024); T: ser::Serializable<Serializer<MemWriter>, io::IoError>
{ >(value: &T) -> Vec<u8> {
let mut serializer = Serializer::new(wr.by_ref()); let wr = MemWriter::with_capacity(1024);
// We are writing to a MemWriter, which doesn't fail. So we can ignore let mut serializer = Serializer::new(wr);
// the error. // We are writing to a MemWriter, which doesn't fail. So we can ignore
value.serialize(&mut serializer).unwrap(); // the error.
} value.serialize(&mut serializer).unwrap();
wr.unwrap() serializer.unwrap().unwrap()
} }
/// Encode the specified struct into a json `String` buffer. /// Encode the specified struct into a json `String` buffer.
#[inline] #[inline]
pub fn to_string<T: ser::Serializable>(value: &T) -> Result<String, Vec<u8>> { pub fn to_string<
T: ser::Serializable<Serializer<MemWriter>, io::IoError>
>(value: &T) -> Result<String, Vec<u8>> {
let buf = to_vec(value); let buf = to_vec(value);
String::from_utf8(buf) String::from_utf8(buf)
} }
/// Encode the specified struct into a json `[u8]` buffer. /// Encode the specified struct into a json `[u8]` buffer.
pub fn to_pretty_vec<T: ser::Serializable>(value: &T) -> Vec<u8> { pub fn to_pretty_vec<
let mut wr = MemWriter::new(); T: ser::Serializable<PrettySerializer<MemWriter>, io::IoError>
{ >(value: &T) -> Vec<u8> {
let mut serializer = PrettySerializer::new(wr.by_ref()); let wr = MemWriter::new();
value.serialize(&mut serializer).unwrap(); let mut serializer = PrettySerializer::new(wr);
} value.serialize(&mut serializer).unwrap();
wr.unwrap() serializer.unwrap().unwrap()
} }
/// Encode the specified struct into a json `String` buffer. /// Encode the specified struct into a json `String` buffer.
pub fn to_pretty_string<T: ser::Serializable>(value: &T) -> Result<String, Vec<u8>> { pub fn to_pretty_string<
T: ser::Serializable<PrettySerializer<MemWriter>, io::IoError>
>(value: &T) -> Result<String, Vec<u8>> {
let buf = to_pretty_vec(value); let buf = to_pretty_vec(value);
String::from_utf8(buf) String::from_utf8(buf)
} }
@ -2302,6 +2313,7 @@ impl<A:ToJson> ToJson for Option<A> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::fmt::Show; use std::fmt::Show;
use std::io;
use std::str; use std::str;
use std::collections::TreeMap; use std::collections::TreeMap;
@ -2321,7 +2333,7 @@ mod tests {
SyntaxError, SyntaxError,
}; };
use de; use de;
use ser::Serializable; use ser::{Serializable, Serializer};
use ser; use ser;
macro_rules! treemap { macro_rules! treemap {
@ -2400,7 +2412,7 @@ mod tests {
} }
fn test_encode_ok< fn test_encode_ok<
T: PartialEq + Show + ToJson + ser::Serializable T: PartialEq + Show + ToJson + ser::Serializable<super::Serializer<io::MemWriter>, io::IoError>
>(errors: &[(T, &str)]) { >(errors: &[(T, &str)]) {
for &(ref value, out) in errors.iter() { for &(ref value, out) in errors.iter() {
let out = out.to_string(); let out = out.to_string();
@ -2414,7 +2426,7 @@ mod tests {
} }
fn test_pretty_encode_ok< fn test_pretty_encode_ok<
T: PartialEq + Show + ToJson + ser::Serializable T: PartialEq + Show + ToJson + ser::Serializable<super::PrettySerializer<io::MemWriter>, io::IoError>
>(errors: &[(T, &str)]) { >(errors: &[(T, &str)]) {
for &(ref value, out) in errors.iter() { for &(ref value, out) in errors.iter() {
let out = out.to_string(); let out = out.to_string();
@ -3460,7 +3472,7 @@ mod tests {
"{\"a\": 3}", "{\"a\": 3}",
box [ box [
(ObjectStart, box []), (ObjectStart, box []),
(NumberValue(3.0), box [Key("a")]), (F64Value(3.0), box [Key("a")]),
(ObjectEnd, box []), (ObjectEnd, box []),
] ]
); );
@ -3477,7 +3489,7 @@ mod tests {
"{\"a\" : 1.0 ,\"b\": [ true ]}", "{\"a\" : 1.0 ,\"b\": [ true ]}",
box [ box [
(ObjectStart, box []), (ObjectStart, box []),
(NumberValue(1.0), box [Key("a")]), (F64Value(1.0), box [Key("a")]),
(ListStart, box [Key("b")]), (ListStart, box [Key("b")]),
(BooleanValue(true),box [Key("b"), Index(0)]), (BooleanValue(true),box [Key("b"), Index(0)]),
(ListEnd, box [Key("b")]), (ListEnd, box [Key("b")]),
@ -3495,7 +3507,7 @@ mod tests {
}"#, }"#,
~[ ~[
(ObjectStart, ~[]), (ObjectStart, ~[]),
(NumberValue(1.0), ~[Key("a")]), (F64Value(1.0), ~[Key("a")]),
(ListStart, ~[Key("b")]), (ListStart, ~[Key("b")]),
(BooleanValue(true), ~[Key("b"), Index(0)]), (BooleanValue(true), ~[Key("b"), Index(0)]),
(StringValue("foo\nbar".to_string()), ~[Key("b"), Index(1)]), (StringValue("foo\nbar".to_string()), ~[Key("b"), Index(1)]),
@ -3554,8 +3566,8 @@ mod tests {
"[3, 1]", "[3, 1]",
box [ box [
(ListStart, box []), (ListStart, box []),
(NumberValue(3.0), box [Index(0)]), (F64Value(3.0), box [Index(0)]),
(NumberValue(1.0), box [Index(1)]), (F64Value(1.0), box [Index(1)]),
(ListEnd, box []), (ListEnd, box []),
] ]
); );
@ -3563,8 +3575,8 @@ mod tests {
"\n[3, 2]\n", "\n[3, 2]\n",
box [ box [
(ListStart, box []), (ListStart, box []),
(NumberValue(3.0), box [Index(0)]), (F64Value(3.0), box [Index(0)]),
(NumberValue(2.0), box [Index(1)]), (F64Value(2.0), box [Index(1)]),
(ListEnd, box []), (ListEnd, box []),
] ]
); );
@ -3572,10 +3584,10 @@ mod tests {
"[2, [4, 1]]", "[2, [4, 1]]",
box [ box [
(ListStart, box []), (ListStart, box []),
(NumberValue(2.0), box [Index(0)]), (F64Value(2.0), box [Index(0)]),
(ListStart, box [Index(1)]), (ListStart, box [Index(1)]),
(NumberValue(4.0), box [Index(1), Index(0)]), (F64Value(4.0), box [Index(1), Index(0)]),
(NumberValue(1.0), box [Index(1), Index(1)]), (F64Value(1.0), box [Index(1), Index(1)]),
(ListEnd, box [Index(1)]), (ListEnd, box [Index(1)]),
(ListEnd, box []), (ListEnd, box []),
] ]
@ -3731,12 +3743,12 @@ mod bench {
list.push(json::Object(treemap!( list.push(json::Object(treemap!(
"a".to_string() => json::Boolean(true), "a".to_string() => json::Boolean(true),
"b".to_string() => json::Null, "b".to_string() => json::Null,
"c".to_string() => json::Number(3.1415), "c".to_string() => json::F64(3.1415),
"d".to_string() => json::String("Hello world".to_string()), "d".to_string() => json::String("Hello world".to_string()),
"e".to_string() => json::List(vec!( "e".to_string() => json::List(vec!(
json::Number(1f64), json::U64(1),
json::Number(2f64), json::U64(2),
json::Number(3f64) json::U64(3)
)) ))
))); )));
} }
@ -3832,7 +3844,7 @@ mod bench {
assert_eq!(parser.next(), Some(json::NullValue)); assert_eq!(parser.next(), Some(json::NullValue));
assert_eq!(parser.stack().top(), Some(json::Key("b"))); assert_eq!(parser.stack().top(), Some(json::Key("b")));
assert_eq!(parser.next(), Some(json::NumberValue(3.1415))); assert_eq!(parser.next(), Some(json::F64Value(3.1415)));
assert_eq!(parser.stack().top(), Some(json::Key("c"))); assert_eq!(parser.stack().top(), Some(json::Key("c")));
assert_eq!(parser.next(), Some(json::StringValue("Hello world".to_string()))); assert_eq!(parser.next(), Some(json::StringValue("Hello world".to_string())));
@ -3840,9 +3852,9 @@ mod bench {
assert_eq!(parser.next(), Some(json::ListStart)); assert_eq!(parser.next(), Some(json::ListStart));
assert_eq!(parser.stack().top(), Some(json::Key("e"))); assert_eq!(parser.stack().top(), Some(json::Key("e")));
assert_eq!(parser.next(), Some(json::NumberValue(1f64))); assert_eq!(parser.next(), Some(json::U64Value(1)));
assert_eq!(parser.next(), Some(json::NumberValue(2f64))); assert_eq!(parser.next(), Some(json::U64Value(2)));
assert_eq!(parser.next(), Some(json::NumberValue(3f64))); assert_eq!(parser.next(), Some(json::U64Value(3)));
assert_eq!(parser.next(), Some(json::ListEnd)); assert_eq!(parser.next(), Some(json::ListEnd));
assert_eq!(parser.next(), Some(json::ObjectEnd)); assert_eq!(parser.next(), Some(json::ObjectEnd));

View File

@ -79,47 +79,52 @@ pub trait Serializer<E> {
fn serialize_str(&mut self, v: &str) -> Result<(), E>; fn serialize_str(&mut self, v: &str) -> Result<(), E>;
fn serialize_tuple_start(&mut self, len: uint) -> Result<(), E>; fn serialize_tuple_start(&mut self, len: uint) -> Result<(), E>;
fn serialize_tuple_elt<T: Serializable>(&mut self, v: &T) -> Result<(), E>; fn serialize_tuple_elt<
T: Serializable<Self, E>
>(&mut self, v: &T) -> Result<(), E>;
fn serialize_tuple_end(&mut self) -> Result<(), E>; fn serialize_tuple_end(&mut self) -> Result<(), E>;
fn serialize_struct_start(&mut self, name: &str, len: uint) -> Result<(), E>; fn serialize_struct_start(&mut self, name: &str, len: uint) -> Result<(), E>;
fn serialize_struct_elt<T: Serializable>(&mut self, name: &str, v: &T) -> Result<(), E>; fn serialize_struct_elt<
T: Serializable<Self, E>
>(&mut self, name: &str, v: &T) -> Result<(), E>;
fn serialize_struct_end(&mut self) -> Result<(), E>; fn serialize_struct_end(&mut self) -> Result<(), E>;
fn serialize_enum_start(&mut self, name: &str, variant: &str, len: uint) -> Result<(), E>; fn serialize_enum_start(&mut self, name: &str, variant: &str, len: uint) -> Result<(), E>;
fn serialize_enum_elt<T: Serializable>(&mut self, v: &T) -> Result<(), E>; fn serialize_enum_elt<
T: Serializable<Self, E>
>(&mut self, v: &T) -> Result<(), E>;
fn serialize_enum_end(&mut self) -> Result<(), E>; fn serialize_enum_end(&mut self) -> Result<(), E>;
fn serialize_option<T: Serializable>(&mut self, v: &Option<T>) -> Result<(), E>; fn serialize_option<
T: Serializable<Self, E>
>(&mut self, v: &Option<T>) -> Result<(), E>;
fn serialize_seq< fn serialize_seq<
T: Serializable, T: Serializable<Self, E>,
Iter: Iterator<T> Iter: Iterator<T>
>(&mut self, iter: Iter) -> Result<(), E>; >(&mut self, iter: Iter) -> Result<(), E>;
fn serialize_map< fn serialize_map<
K: Serializable, K: Serializable<Self, E>,
V: Serializable, V: Serializable<Self, E>,
Iter: Iterator<(K, V)> Iter: Iterator<(K, V)>
>(&mut self, iter: Iter) -> Result<(), E>; >(&mut self, iter: Iter) -> Result<(), E>;
} }
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
pub trait Serializable { pub trait Serializable<S: Serializer<E>, E> {
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E>;
S: Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E>;
} }
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
macro_rules! impl_serializable { macro_rules! impl_serializable {
($ty:ty, $method:ident) => { ($ty:ty, $method:ident) => {
impl Serializable for $ty { impl<S: Serializer<E>, E> Serializable<S, E> for $ty {
#[inline] #[inline]
fn serialize<S: Serializer<E>, E>(&self, s: &mut S) -> Result<(), E> { fn serialize(&self, s: &mut S) -> Result<(), E> {
s.$method(*self) s.$method(*self)
} }
} }
@ -143,22 +148,16 @@ impl_serializable!(char, serialize_char)
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
impl<'a> Serializable for &'a str { impl<'a, S: Serializer<E>, E> Serializable<S, E> for &'a str {
#[inline] #[inline]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
s.serialize_str(*self) s.serialize_str(*self)
} }
} }
impl Serializable for String { impl<S: Serializer<E>, E> Serializable<S, E> for String {
#[inline] #[inline]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
self.as_slice().serialize(s) self.as_slice().serialize(s)
} }
} }
@ -167,9 +166,14 @@ impl Serializable for String {
macro_rules! impl_serializable_box { macro_rules! impl_serializable_box {
($ty:ty) => { ($ty:ty) => {
impl<'a, T: Serializable> Serializable for $ty { impl<
'a,
S: Serializer<E>,
E,
T: Serializable<S, E>
> Serializable<S, E> for $ty {
#[inline] #[inline]
fn serialize<S: Serializer<E>, E>(&self, s: &mut S) -> Result<(), E> { fn serialize(&self, s: &mut S) -> Result<(), E> {
(**self).serialize(s) (**self).serialize(s)
} }
} }
@ -181,9 +185,13 @@ impl_serializable_box!(Box<T>)
impl_serializable_box!(Gc<T>) impl_serializable_box!(Gc<T>)
impl_serializable_box!(Rc<T>) impl_serializable_box!(Rc<T>)
impl<T: Serializable + Send + Sync> Serializable for Arc<T> { impl<
S: Serializer<E>,
E,
T: Serializable<S, E> + Send + Sync
> Serializable<S, E> for Arc<T> {
#[inline] #[inline]
fn serialize<S: Serializer<E>, E>(&self, s: &mut S) -> Result<(), E> { fn serialize(&self, s: &mut S) -> Result<(), E> {
(**self).serialize(s) (**self).serialize(s)
} }
} }
@ -191,13 +199,12 @@ impl<T: Serializable + Send + Sync> Serializable for Arc<T> {
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
impl< impl<
T: Serializable S: Serializer<E>,
> Serializable for Option<T> { E,
T: Serializable<S, E>
> Serializable<S, E> for Option<T> {
#[inline] #[inline]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
s.serialize_option(self) s.serialize_option(self)
} }
} }
@ -205,13 +212,12 @@ impl<
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
impl< impl<
T: Serializable S: Serializer<E>,
> Serializable for Vec<T> { E,
T: Serializable<S, E>
> Serializable<S, E> for Vec<T> {
#[inline] #[inline]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
s.serialize_seq(self.iter()) s.serialize_seq(self.iter())
} }
} }
@ -219,27 +225,25 @@ impl<
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
impl< impl<
K: Serializable + Eq + Hash, S: Serializer<E>,
V: Serializable E,
> Serializable for HashMap<K, V> { K: Serializable<S, E> + Eq + Hash,
V: Serializable<S, E>
> Serializable<S, E> for HashMap<K, V> {
#[inline] #[inline]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
s.serialize_map(self.iter()) s.serialize_map(self.iter())
} }
} }
impl< impl<
K: Serializable + Ord, S: Serializer<E>,
V: Serializable E,
> Serializable for TreeMap<K, V> { K: Serializable<S, E> + Ord,
V: Serializable<S, E>
> Serializable<S, E> for TreeMap<K, V> {
#[inline] #[inline]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
s.serialize_map(self.iter()) s.serialize_map(self.iter())
} }
} }
@ -247,25 +251,23 @@ impl<
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
impl< impl<
T: Serializable + Eq + Hash S: Serializer<E>,
> Serializable for HashSet<T> { E,
T: Serializable<S, E> + Eq + Hash
> Serializable<S, E> for HashSet<T> {
#[inline] #[inline]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
s.serialize_seq(self.iter()) s.serialize_seq(self.iter())
} }
} }
impl< impl<
T: Serializable + Ord S: Serializer<E>,
> Serializable for TreeSet<T> { E,
T: Serializable<S, E> + Ord
> Serializable<S, E> for TreeSet<T> {
#[inline] #[inline]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
s.serialize_seq(self.iter()) s.serialize_seq(self.iter())
} }
} }
@ -278,26 +280,22 @@ macro_rules! peel {
macro_rules! impl_serialize_tuple { macro_rules! impl_serialize_tuple {
() => { () => {
impl Serializable for () { impl<S: Serializer<E>, E> Serializable<S, E> for () {
#[inline] #[inline]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
s.serialize_null() s.serialize_null()
} }
} }
}; };
( $($name:ident,)+ ) => { ( $($name:ident,)+ ) => {
impl< impl<
$($name:Serializable),* S: Serializer<E>,
> Serializable for ($($name,)*) { E,
$($name:Serializable<S, E>),+
> Serializable<S, E> for ($($name,)+) {
#[inline] #[inline]
#[allow(uppercase_variables)] #[allow(uppercase_variables)]
fn serialize< fn serialize(&self, s: &mut S) -> Result<(), E> {
S: Serializer<E>,
E
>(&self, s: &mut S) -> Result<(), E> {
// FIXME: how can we count macro args? // FIXME: how can we count macro args?
let mut len = 0; let mut len = 0;
$({ let $name = 1; len += $name; })*; $({ let $name = 1; len += $name; })*;
@ -495,7 +493,7 @@ mod tests {
} }
fn serialize_tuple_elt< fn serialize_tuple_elt<
T: Serializable T: Serializable<AssertSerializer<Iter>, Error>
>(&mut self, value: &T) -> Result<(), Error> { >(&mut self, value: &T) -> Result<(), Error> {
try!(self.serialize(TupleSep)); try!(self.serialize(TupleSep));
value.serialize(self) value.serialize(self)
@ -510,7 +508,7 @@ mod tests {
} }
fn serialize_struct_elt< fn serialize_struct_elt<
T: Serializable T: Serializable<AssertSerializer<Iter>, Error>
>(&mut self, name: &str, value: &T) -> Result<(), Error> { >(&mut self, name: &str, value: &T) -> Result<(), Error> {
try!(self.serialize(StructSep(name))); try!(self.serialize(StructSep(name)));
value.serialize(self) value.serialize(self)
@ -525,7 +523,7 @@ mod tests {
} }
fn serialize_enum_elt< fn serialize_enum_elt<
T: Serializable T: Serializable<AssertSerializer<Iter>, Error>
>(&mut self, value: &T) -> Result<(), Error> { >(&mut self, value: &T) -> Result<(), Error> {
try!(self.serialize(EnumSep)); try!(self.serialize(EnumSep));
value.serialize(self) value.serialize(self)
@ -536,7 +534,7 @@ mod tests {
} }
fn serialize_option< fn serialize_option<
T: Serializable T: Serializable<AssertSerializer<Iter>, Error>
>(&mut self, v: &Option<T>) -> Result<(), Error> { >(&mut self, v: &Option<T>) -> Result<(), Error> {
match *v { match *v {
Some(ref v) => { Some(ref v) => {
@ -550,7 +548,7 @@ mod tests {
} }
fn serialize_seq< fn serialize_seq<
T: Serializable, T: Serializable<AssertSerializer<Iter>, Error>,
SeqIter: Iterator<T> SeqIter: Iterator<T>
>(&mut self, mut iter: SeqIter) -> Result<(), Error> { >(&mut self, mut iter: SeqIter) -> Result<(), Error> {
let (len, _) = iter.size_hint(); let (len, _) = iter.size_hint();
@ -562,8 +560,8 @@ mod tests {
} }
fn serialize_map< fn serialize_map<
K: Serializable, K: Serializable<AssertSerializer<Iter>, Error>,
V: Serializable, V: Serializable<AssertSerializer<Iter>, Error>,
MapIter: Iterator<(K, V)> MapIter: Iterator<(K, V)>
>(&mut self, mut iter: MapIter) -> Result<(), Error> { >(&mut self, mut iter: MapIter) -> Result<(), Error> {
let (len, _) = iter.size_hint(); let (len, _) = iter.size_hint();