update to rust HEAD, switch to rustc_serialize

This commit is contained in:
Erick Tryzelaar 2015-01-04 17:18:50 -08:00
parent f1929ca86d
commit b98719a4a0
16 changed files with 219 additions and 182 deletions

View File

@ -8,5 +8,8 @@ license = "MIT/Apache-2.0"
name = "serde" name = "serde"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies]
rustc-serialize = "*"
[dependencies.serde_macros] [dependencies.serde_macros]
path = "serde_macros/" path = "serde_macros/"

View File

@ -1,15 +1,15 @@
#![feature(phase)] #![feature(associated_types, phase, old_orphan_check)]
#[phase(plugin)] #[phase(plugin)]
extern crate serde_macros; extern crate serde_macros;
extern crate serde; extern crate serde;
extern crate serialize; extern crate "rustc-serialize" as rustc_serialize;
extern crate test; extern crate test;
use test::Bencher; use test::Bencher;
use serialize::{Decoder, Decodable}; use rustc_serialize::{Decoder, Decodable};
use serde::de::{Deserializer, Deserialize}; use serde::de::{Deserializer, Deserialize};
@ -17,8 +17,8 @@ use Animal::{Dog, Frog};
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#[deriving(Clone, PartialEq, Show, Decodable)] #[derive(Clone, PartialEq, Show, RustcDecodable)]
#[deriving_deserialize] #[derive_deserialize]
enum Animal { enum Animal {
Dog, Dog,
Frog(String, int) Frog(String, int)
@ -26,7 +26,7 @@ enum Animal {
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#[deriving(Show)] #[derive(Show)]
pub enum Error { pub enum Error {
EndOfStream, EndOfStream,
SyntaxError, SyntaxError,
@ -36,7 +36,7 @@ pub enum Error {
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
mod decoder { mod decoder {
use serialize::Decoder; use rustc_serialize::Decoder;
use super::{Animal, Error}; use super::{Animal, Error};
use super::Animal::{Dog, Frog}; use super::Animal::{Dog, Frog};
@ -265,7 +265,9 @@ mod deserializer {
} }
} }
impl Iterator<Result<de::Token, Error>> for AnimalDeserializer { impl Iterator for AnimalDeserializer {
type Item = Result<de::Token, Error>;
#[inline] #[inline]
fn next(&mut self) -> Option<Result<de::Token, Error>> { fn next(&mut self) -> Option<Result<de::Token, Error>> {
match self.stack.pop() { match self.stack.pop() {

View File

@ -1,16 +1,17 @@
#![feature(phase, macro_rules)] #![feature(phase, macro_rules, old_orphan_check)]
#![allow(non_camel_case_types)] #![allow(non_camel_case_types)]
#[phase(plugin)] #[phase(plugin)]
extern crate serde_macros; extern crate serde_macros;
extern crate serde; extern crate serde;
extern crate serialize; extern crate "rustc-serialize" as rustc_serialize;
extern crate test; extern crate test;
use std::io;
use std::io::ByRefWriter; use std::io::ByRefWriter;
use std::io::extensions::Bytes; use std::io::extensions::Bytes;
use std::io;
use std::num::FromPrimitive;
use test::Bencher; use test::Bencher;
use serde::de; use serde::de;
@ -19,11 +20,11 @@ use serde::json;
use serde::ser::Serialize; use serde::ser::Serialize;
use serde::ser; use serde::ser;
use serialize::Encodable; use rustc_serialize::Encodable;
#[deriving(Show, PartialEq, Encodable, Decodable)] #[derive(Show, PartialEq, RustcEncodable, RustcDecodable)]
#[deriving_serialize] #[derive_serialize]
#[deriving_deserialize] #[derive_deserialize]
struct Http { struct Http {
protocol: HttpProtocol, protocol: HttpProtocol,
status: u32, status: u32,
@ -36,20 +37,20 @@ struct Http {
request_uri: String, request_uri: String,
} }
#[deriving(Copy, Show, PartialEq, FromPrimitive)] #[derive(Copy, Show, PartialEq, FromPrimitive)]
enum HttpProtocol { enum HttpProtocol {
HTTP_PROTOCOL_UNKNOWN, HTTP_PROTOCOL_UNKNOWN,
HTTP10, HTTP10,
HTTP11, HTTP11,
} }
impl<S: serialize::Encoder<E>, E> serialize::Encodable<S, E> for HttpProtocol { impl<S: rustc_serialize::Encoder<E>, E> rustc_serialize::Encodable<S, E> for HttpProtocol {
fn encode(&self, s: &mut S) -> Result<(), E> { fn encode(&self, s: &mut S) -> Result<(), E> {
(*self as uint).encode(s) (*self as uint).encode(s)
} }
} }
impl<D: ::serialize::Decoder<E>, E> serialize::Decodable<D, E> for HttpProtocol { impl<D: rustc_serialize::Decoder<E>, E> rustc_serialize::Decodable<D, E> for HttpProtocol {
fn decode(d: &mut D) -> Result<HttpProtocol, E> { fn decode(d: &mut D) -> Result<HttpProtocol, E> {
match FromPrimitive::from_uint(try!(d.read_uint())) { match FromPrimitive::from_uint(try!(d.read_uint())) {
Some(value) => Ok(value), Some(value) => Ok(value),
@ -72,7 +73,7 @@ impl<D: de::Deserializer<E>, E> de::Deserialize<D, E> for HttpProtocol {
} }
} }
#[deriving(Copy, Show, PartialEq, FromPrimitive)] #[derive(Copy, Show, PartialEq, FromPrimitive)]
enum HttpMethod { enum HttpMethod {
METHOD_UNKNOWN, METHOD_UNKNOWN,
GET, GET,
@ -87,13 +88,13 @@ enum HttpMethod {
PATCH, PATCH,
} }
impl<S: serialize::Encoder<E>, E> serialize::Encodable<S, E> for HttpMethod { impl<S: rustc_serialize::Encoder<E>, E> rustc_serialize::Encodable<S, E> for HttpMethod {
fn encode(&self, s: &mut S) -> Result<(), E> { fn encode(&self, s: &mut S) -> Result<(), E> {
(*self as uint).encode(s) (*self as uint).encode(s)
} }
} }
impl<D: ::serialize::Decoder<E>, E> serialize::Decodable<D, E> for HttpMethod { impl<D: rustc_serialize::Decoder<E>, E> rustc_serialize::Decodable<D, E> for HttpMethod {
fn decode(d: &mut D) -> Result<HttpMethod, E> { fn decode(d: &mut D) -> Result<HttpMethod, E> {
match FromPrimitive::from_uint(try!(d.read_uint())) { match FromPrimitive::from_uint(try!(d.read_uint())) {
Some(value) => Ok(value), Some(value) => Ok(value),
@ -116,7 +117,7 @@ impl<D: de::Deserializer<E>, E> de::Deserialize<D, E> for HttpMethod {
} }
} }
#[deriving(Copy, Show, PartialEq, FromPrimitive)] #[derive(Copy, Show, PartialEq, FromPrimitive)]
enum CacheStatus { enum CacheStatus {
CACHESTATUS_UNKNOWN, CACHESTATUS_UNKNOWN,
Miss, Miss,
@ -124,13 +125,13 @@ enum CacheStatus {
Hit, Hit,
} }
impl<S: serialize::Encoder<E>, E> serialize::Encodable<S, E> for CacheStatus { impl<S: rustc_serialize::Encoder<E>, E> rustc_serialize::Encodable<S, E> for CacheStatus {
fn encode(&self, s: &mut S) -> Result<(), E> { fn encode(&self, s: &mut S) -> Result<(), E> {
(*self as uint).encode(s) (*self as uint).encode(s)
} }
} }
impl<D: ::serialize::Decoder<E>, E> serialize::Decodable<D, E> for CacheStatus { impl<D: rustc_serialize::Decoder<E>, E> rustc_serialize::Decodable<D, E> for CacheStatus {
fn decode(d: &mut D) -> Result<CacheStatus, E> { fn decode(d: &mut D) -> Result<CacheStatus, E> {
match FromPrimitive::from_uint(try!(d.read_uint())) { match FromPrimitive::from_uint(try!(d.read_uint())) {
Some(value) => Ok(value), Some(value) => Ok(value),
@ -153,9 +154,9 @@ impl<D: de::Deserializer<E>, E> de::Deserialize<D, E> for CacheStatus {
} }
} }
#[deriving(Show, PartialEq, Encodable, Decodable)] #[derive(Show, PartialEq, RustcEncodable, RustcDecodable)]
#[deriving_serialize] #[derive_serialize]
#[deriving_deserialize] #[derive_deserialize]
struct Origin { struct Origin {
ip: String, ip: String,
port: u32, port: u32,
@ -163,20 +164,20 @@ struct Origin {
protocol: OriginProtocol, protocol: OriginProtocol,
} }
#[deriving(Copy, Show, PartialEq, FromPrimitive)] #[derive(Copy, Show, PartialEq, FromPrimitive)]
enum OriginProtocol { enum OriginProtocol {
ORIGIN_PROTOCOL_UNKNOWN, ORIGIN_PROTOCOL_UNKNOWN,
HTTP, HTTP,
HTTPS, HTTPS,
} }
impl<S: serialize::Encoder<E>, E> serialize::Encodable<S, E> for OriginProtocol { impl<S: rustc_serialize::Encoder<E>, E> rustc_serialize::Encodable<S, E> for OriginProtocol {
fn encode(&self, s: &mut S) -> Result<(), E> { fn encode(&self, s: &mut S) -> Result<(), E> {
(*self as uint).encode(s) (*self as uint).encode(s)
} }
} }
impl<D: ::serialize::Decoder<E>, E> serialize::Decodable<D, E> for OriginProtocol { impl<D: rustc_serialize::Decoder<E>, E> rustc_serialize::Decodable<D, E> for OriginProtocol {
fn decode(d: &mut D) -> Result<OriginProtocol, E> { fn decode(d: &mut D) -> Result<OriginProtocol, E> {
match FromPrimitive::from_uint(try!(d.read_uint())) { match FromPrimitive::from_uint(try!(d.read_uint())) {
Some(value) => Ok(value), Some(value) => Ok(value),
@ -199,7 +200,7 @@ impl<D: de::Deserializer<E>, E> de::Deserialize<D, E> for OriginProtocol {
} }
} }
#[deriving(Copy, Show, PartialEq, FromPrimitive)] #[derive(Copy, Show, PartialEq, FromPrimitive)]
enum ZonePlan { enum ZonePlan {
ZONEPLAN_UNKNOWN, ZONEPLAN_UNKNOWN,
FREE, FREE,
@ -208,13 +209,13 @@ enum ZonePlan {
ENT, ENT,
} }
impl<S: serialize::Encoder<E>, E> serialize::Encodable<S, E> for ZonePlan { impl<S: rustc_serialize::Encoder<E>, E> rustc_serialize::Encodable<S, E> for ZonePlan {
fn encode(&self, s: &mut S) -> Result<(), E> { fn encode(&self, s: &mut S) -> Result<(), E> {
(*self as uint).encode(s) (*self as uint).encode(s)
} }
} }
impl<D: ::serialize::Decoder<E>, E> serialize::Decodable<D, E> for ZonePlan { impl<D: rustc_serialize::Decoder<E>, E> rustc_serialize::Decodable<D, E> for ZonePlan {
fn decode(d: &mut D) -> Result<ZonePlan, E> { fn decode(d: &mut D) -> Result<ZonePlan, E> {
match FromPrimitive::from_uint(try!(d.read_uint())) { match FromPrimitive::from_uint(try!(d.read_uint())) {
Some(value) => Ok(value), Some(value) => Ok(value),
@ -237,7 +238,7 @@ impl<D: de::Deserializer<E>, E> de::Deserialize<D, E> for ZonePlan {
} }
} }
#[deriving(Copy, Show, PartialEq, FromPrimitive)] #[derive(Copy, Show, PartialEq, FromPrimitive)]
enum Country { enum Country {
UNKNOWN, UNKNOWN,
A1, A1,
@ -497,13 +498,13 @@ enum Country {
ZW, ZW,
} }
impl<S: serialize::Encoder<E>, E> serialize::Encodable<S, E> for Country { impl<S: rustc_serialize::Encoder<E>, E> rustc_serialize::Encodable<S, E> for Country {
fn encode(&self, s: &mut S) -> Result<(), E> { fn encode(&self, s: &mut S) -> Result<(), E> {
(*self as uint).encode(s) (*self as uint).encode(s)
} }
} }
impl<D: ::serialize::Decoder<E>, E> serialize::Decodable<D, E> for Country { impl<D: rustc_serialize::Decoder<E>, E> rustc_serialize::Decodable<D, E> for Country {
fn decode(d: &mut D) -> Result<Country, E> { fn decode(d: &mut D) -> Result<Country, E> {
match FromPrimitive::from_uint(try!(d.read_uint())) { match FromPrimitive::from_uint(try!(d.read_uint())) {
Some(value) => Ok(value), Some(value) => Ok(value),
@ -526,9 +527,9 @@ impl<D: de::Deserializer<E>, E> de::Deserialize<D, E> for Country {
} }
} }
#[deriving(Show, PartialEq, Encodable, Decodable)] #[derive(Show, PartialEq, RustcEncodable, RustcDecodable)]
#[deriving_serialize] #[derive_serialize]
#[deriving_deserialize] #[derive_deserialize]
struct Log { struct Log {
timestamp: i64, timestamp: i64,
zone_id: u32, zone_id: u32,
@ -669,14 +670,14 @@ const JSON_STR: &'static str = r#"{"timestamp":2837513946597,"zone_id":123456,"z
#[test] #[test]
fn test_encoder() { fn test_encoder() {
use serialize::Encodable; use rustc_serialize::Encodable;
let log = Log::new(); let log = Log::new();
let mut wr = Vec::with_capacity(1024); let mut wr = Vec::with_capacity(1024);
{ {
let mut encoder = serialize::json::Encoder::new(&mut wr as &mut Writer); let mut encoder = rustc_serialize::json::Encoder::new(&mut wr);
log.encode(&mut encoder).unwrap(); log.encode(&mut encoder).unwrap();
} }
@ -690,7 +691,7 @@ fn bench_encoder(b: &mut Bencher) {
let mut wr = Vec::with_capacity(1024); let mut wr = Vec::with_capacity(1024);
{ {
let mut encoder = serialize::json::Encoder::new(&mut wr as &mut Writer); let mut encoder = rustc_serialize::json::Encoder::new(&mut wr);
log.encode(&mut encoder).unwrap(); log.encode(&mut encoder).unwrap();
} }
@ -699,7 +700,7 @@ fn bench_encoder(b: &mut Bencher) {
b.iter(|| { b.iter(|| {
wr.clear(); wr.clear();
let mut encoder = serialize::json::Encoder::new(&mut wr as &mut Writer); let mut encoder = rustc_serialize::json::Encoder::new(&mut wr);
log.encode(&mut encoder).unwrap(); log.encode(&mut encoder).unwrap();
}); });
} }
@ -756,7 +757,7 @@ fn bench_serializer_slice(b: &mut Bencher) {
let json = json::to_vec(&log); let json = json::to_vec(&log);
b.bytes = json.len() as u64; b.bytes = json.len() as u64;
let mut buf = [0, .. 1024]; let mut buf = [0; 1024];
b.iter(|| { b.iter(|| {
for item in buf.iter_mut(){ *item = 0; } for item in buf.iter_mut(){ *item = 0; }
@ -1259,20 +1260,24 @@ fn bench_direct_my_mem_writer1(b: &mut Bencher) {
#[test] #[test]
fn test_decoder() { fn test_decoder() {
let json = serialize::json::from_str(JSON_STR).unwrap(); use rustc_serialize::json::Json;
let mut decoder = serialize::json::Decoder::new(json);
let log: Log = serialize::Decodable::decode(&mut decoder).unwrap(); let json = Json::from_str(JSON_STR).unwrap();
let mut decoder = rustc_serialize::json::Decoder::new(json);
let log: Log = rustc_serialize::Decodable::decode(&mut decoder).unwrap();
assert_eq!(log, Log::new()); assert_eq!(log, Log::new());
} }
#[bench] #[bench]
fn bench_decoder(b: &mut Bencher) { fn bench_decoder(b: &mut Bencher) {
use rustc_serialize::json::Json;
b.bytes = JSON_STR.len() as u64; b.bytes = JSON_STR.len() as u64;
b.iter(|| { b.iter(|| {
let json = serialize::json::from_str(JSON_STR).unwrap(); let json = Json::from_str(JSON_STR).unwrap();
let mut decoder = serialize::json::Decoder::new(json); let mut decoder = rustc_serialize::json::Decoder::new(json);
let _log: Log = serialize::Decodable::decode(&mut decoder).unwrap(); let _log: Log = rustc_serialize::Decodable::decode(&mut decoder).unwrap();
}); });
} }
@ -1350,7 +1355,7 @@ fn manual_reader_string<R: Reader>(rdr: &mut R, buf: &mut [u8], key: &[u8]) -> S
#[inline] #[inline]
fn manual_reader_deserialize<R: Reader>(rdr: &mut R) -> Log { fn manual_reader_deserialize<R: Reader>(rdr: &mut R) -> Log {
let mut buf = [0, .. 128]; let mut buf = [0; 128];
manual_reader_ignore(rdr, &mut buf, b"{"); manual_reader_ignore(rdr, &mut buf, b"{");
let timestamp = manual_reader_int(rdr, &mut buf, b"timestamp"); let timestamp = manual_reader_int(rdr, &mut buf, b"timestamp");
@ -1426,7 +1431,7 @@ fn manual_reader_deserialize<R: Reader>(rdr: &mut R) -> Log {
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#[inline] #[inline]
fn manual_iter_ignore<R: Iterator<u8>>(mut rdr: R, buf: &mut [u8], key: &[u8]) { fn manual_iter_ignore<R: Iterator<Item=u8>>(mut rdr: R, buf: &mut [u8], key: &[u8]) {
let buf = buf.slice_mut(0, key.len()); let buf = buf.slice_mut(0, key.len());
for idx in range(0, key.len()) { for idx in range(0, key.len()) {
@ -1436,7 +1441,7 @@ fn manual_iter_ignore<R: Iterator<u8>>(mut rdr: R, buf: &mut [u8], key: &[u8]) {
} }
#[inline] #[inline]
fn manual_iter_field<R: Iterator<u8>>(mut rdr: R, buf: &mut [u8], key: &[u8]) { fn manual_iter_field<R: Iterator<Item=u8>>(mut rdr: R, buf: &mut [u8], key: &[u8]) {
let b = rdr.next().unwrap(); let b = rdr.next().unwrap();
assert_eq!(b, b'"'); assert_eq!(b, b'"');
@ -1450,7 +1455,7 @@ fn manual_iter_field<R: Iterator<u8>>(mut rdr: R, buf: &mut [u8], key: &[u8]) {
} }
#[inline] #[inline]
fn manual_iter_int<R: Iterator<u8>>(mut rdr: R, buf: &mut [u8], key: &[u8]) -> i64 { fn manual_iter_int<R: Iterator<Item=u8>>(mut rdr: R, buf: &mut [u8], key: &[u8]) -> i64 {
manual_iter_field(rdr.by_ref(), buf, key); manual_iter_field(rdr.by_ref(), buf, key);
let mut res = 0; let mut res = 0;
@ -1470,7 +1475,7 @@ fn manual_iter_int<R: Iterator<u8>>(mut rdr: R, buf: &mut [u8], key: &[u8]) -> i
} }
#[inline] #[inline]
fn manual_iter_string<R: Iterator<u8>>(mut rdr: R, buf: &mut [u8], key: &[u8]) -> String { fn manual_iter_string<R: Iterator<Item=u8>>(mut rdr: R, buf: &mut [u8], key: &[u8]) -> String {
manual_iter_field(rdr.by_ref(), buf, key); manual_iter_field(rdr.by_ref(), buf, key);
manual_iter_ignore(rdr.by_ref(), buf, b"\""); manual_iter_ignore(rdr.by_ref(), buf, b"\"");
@ -1493,8 +1498,8 @@ fn manual_iter_string<R: Iterator<u8>>(mut rdr: R, buf: &mut [u8], key: &[u8]) -
} }
#[inline] #[inline]
fn manual_iter_deserialize<R: Iterator<u8>>(mut rdr: R) -> Log { fn manual_iter_deserialize<R: Iterator<Item=u8>>(mut rdr: R) -> Log {
let mut buf = [0u8, .. 128]; let mut buf = [0u8; 128];
manual_iter_ignore(rdr.by_ref(), &mut buf, b"{"); manual_iter_ignore(rdr.by_ref(), &mut buf, b"{");
let timestamp = manual_iter_int(rdr.by_ref(), &mut buf, b"timestamp"); let timestamp = manual_iter_int(rdr.by_ref(), &mut buf, b"timestamp");

View File

@ -1,4 +1,4 @@
#![feature(phase)] #![feature(associated_types, phase)]
#[phase(plugin)] #[phase(plugin)]
extern crate serde_macros; extern crate serde_macros;
@ -17,7 +17,7 @@ use serde::de::{Deserializer, Deserialize};
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#[deriving(Show)] #[derive(Show)]
pub enum Error { pub enum Error {
EndOfStream, EndOfStream,
SyntaxError, SyntaxError,
@ -224,7 +224,7 @@ mod deserializer {
use serde::de; use serde::de;
#[deriving(PartialEq, Show)] #[derive(PartialEq, Show)]
enum State { enum State {
StartState, StartState,
KeyOrEndState, KeyOrEndState,
@ -249,7 +249,9 @@ mod deserializer {
} }
} }
impl Iterator<Result<de::Token, Error>> for IntDeserializer { impl Iterator for IntDeserializer {
type Item = Result<de::Token, Error>;
#[inline] #[inline]
fn next(&mut self) -> Option<Result<de::Token, Error>> { fn next(&mut self) -> Option<Result<de::Token, Error>> {
match self.stack.pop() { match self.stack.pop() {

View File

@ -1,23 +1,23 @@
#![feature(phase)] #![feature(associated_types, phase, old_orphan_check)]
#[phase(plugin)] #[phase(plugin)]
extern crate serde_macros; extern crate serde_macros;
extern crate serde; extern crate serde;
extern crate serialize; extern crate "rustc-serialize" as rustc_serialize;
extern crate test; extern crate test;
use std::collections::HashMap; use std::collections::HashMap;
use test::Bencher; use test::Bencher;
use serialize::{Decoder, Decodable}; use rustc_serialize::{Decoder, Decodable};
use serde::de::{Deserializer, Deserialize}; use serde::de::{Deserializer, Deserialize};
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#[deriving(Clone, PartialEq, Show, Decodable)] #[derive(Clone, PartialEq, Show, RustcDecodable)]
#[deriving_deserialize] #[derive_deserialize]
struct Inner { struct Inner {
a: (), a: (),
b: uint, b: uint,
@ -26,15 +26,15 @@ struct Inner {
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#[deriving(Clone, PartialEq, Show, Decodable)] #[derive(Clone, PartialEq, Show, RustcDecodable)]
#[deriving_deserialize] #[derive_deserialize]
struct Outer { struct Outer {
inner: Vec<Inner>, inner: Vec<Inner>,
} }
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#[deriving(Show)] #[derive(Show)]
pub enum Error { pub enum Error {
EndOfStream, EndOfStream,
SyntaxError(String), SyntaxError(String),
@ -46,7 +46,7 @@ pub enum Error {
mod decoder { mod decoder {
use std::collections::HashMap; use std::collections::HashMap;
use serialize::Decoder; use rustc_serialize::Decoder;
use super::{Outer, Inner, Error}; use super::{Outer, Inner, Error};
@ -63,7 +63,7 @@ mod decoder {
OptionState, OptionState,
}; };
#[deriving(Show)] #[derive(Show)]
enum State { enum State {
OuterState(Outer), OuterState(Outer),
InnerState(Inner), InnerState(Inner),
@ -337,7 +337,7 @@ mod deserializer {
EndState, EndState,
}; };
#[deriving(Show)] #[derive(Show)]
enum State { enum State {
OuterState(Outer), OuterState(Outer),
InnerState(Inner), InnerState(Inner),
@ -366,7 +366,9 @@ mod deserializer {
} }
} }
impl Iterator<Result<de::Token, Error>> for OuterDeserializer { impl Iterator for OuterDeserializer {
type Item = Result<de::Token, Error>;
#[inline] #[inline]
fn next(&mut self) -> Option<Result<de::Token, Error>> { fn next(&mut self) -> Option<Result<de::Token, Error>> {
match self.stack.pop() { match self.stack.pop() {

View File

@ -1,22 +1,22 @@
#![feature(phase)] #![feature(associated_types, phase)]
#[phase(plugin)] #[phase(plugin)]
extern crate serde_macros; extern crate serde_macros;
extern crate serde; extern crate serde;
extern crate serialize; extern crate "rustc-serialize" as rustc_serialize;
extern crate test; extern crate test;
use std::fmt::Show; use std::fmt::Show;
use test::Bencher; use test::Bencher;
use serialize::{Decoder, Decodable}; use rustc_serialize::{Decoder, Decodable};
use serde::de::{Deserializer, Deserialize}; use serde::de::{Deserializer, Deserialize};
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#[deriving(Show)] #[derive(Show)]
pub enum Error { pub enum Error {
EndOfStream, EndOfStream,
SyntaxError, SyntaxError,
@ -27,7 +27,7 @@ pub enum Error {
mod decoder { mod decoder {
use std::vec; use std::vec;
use serialize; use rustc_serialize;
use super::Error; use super::Error;
use super::Error::{EndOfStream, SyntaxError, OtherError}; use super::Error::{EndOfStream, SyntaxError, OtherError};
@ -47,7 +47,7 @@ mod decoder {
} }
} }
impl serialize::Decoder<Error> for IntDecoder { impl rustc_serialize::Decoder<Error> for IntDecoder {
fn error(&mut self, msg: &str) -> Error { fn error(&mut self, msg: &str) -> Error {
OtherError(msg.to_string()) OtherError(msg.to_string())
} }
@ -199,7 +199,7 @@ mod decoder {
} }
} }
impl serialize::Decoder<Error> for U8Decoder { impl rustc_serialize::Decoder<Error> for U8Decoder {
fn error(&mut self, msg: &str) -> Error { fn error(&mut self, msg: &str) -> Error {
OtherError(msg.to_string()) OtherError(msg.to_string())
} }
@ -349,7 +349,7 @@ mod deserializer {
use serde::de; use serde::de;
#[deriving(PartialEq, Show)] #[derive(PartialEq, Show)]
enum State { enum State {
StartState, StartState,
SepOrEndState, SepOrEndState,
@ -373,7 +373,9 @@ mod deserializer {
} }
} }
impl Iterator<Result<de::Token, Error>> for IntDeserializer { impl Iterator for IntDeserializer {
type Item = Result<de::Token, Error>;
#[inline] #[inline]
fn next(&mut self) -> Option<Result<de::Token, Error>> { fn next(&mut self) -> Option<Result<de::Token, Error>> {
match self.state { match self.state {
@ -445,7 +447,9 @@ mod deserializer {
} }
} }
impl Iterator<Result<de::Token, Error>> for U8Deserializer { impl Iterator for U8Deserializer {
type Item = Result<de::Token, Error>;
#[inline] #[inline]
fn next(&mut self) -> Option<Result<de::Token, Error>> { fn next(&mut self) -> Option<Result<de::Token, Error>> {
match self.state { match self.state {

View File

@ -58,15 +58,15 @@ use rustc::plugin::Registry;
#[doc(hidden)] #[doc(hidden)]
pub fn plugin_registrar(reg: &mut Registry) { pub fn plugin_registrar(reg: &mut Registry) {
reg.register_syntax_extension( reg.register_syntax_extension(
token::intern("deriving_serialize"), token::intern("derive_serialize"),
Decorator(box expand_deriving_serialize)); Decorator(box expand_derive_serialize));
reg.register_syntax_extension( reg.register_syntax_extension(
token::intern("deriving_deserialize"), token::intern("derive_deserialize"),
Decorator(box expand_deriving_deserialize)); Decorator(box expand_derive_deserialize));
} }
fn expand_deriving_serialize(cx: &mut ExtCtxt, fn expand_derive_serialize(cx: &mut ExtCtxt,
sp: Span, sp: Span,
mitem: &MetaItem, mitem: &MetaItem,
item: &Item, item: &Item,
@ -191,11 +191,11 @@ fn serialize_substructure(cx: &ExtCtxt,
}) })
} }
_ => cx.bug("expected Struct or EnumMatching in deriving_serialize") _ => cx.bug("expected Struct or EnumMatching in derive_serialize")
} }
} }
pub fn expand_deriving_deserialize(cx: &mut ExtCtxt, pub fn expand_derive_deserialize(cx: &mut ExtCtxt,
span: Span, span: Span,
mitem: &MetaItem, mitem: &MetaItem,
item: &Item, item: &Item,
@ -274,7 +274,7 @@ fn deserialize_substructure(cx: &mut ExtCtxt,
deserializer, deserializer,
token) token)
} }
_ => cx.bug("expected StaticEnum or StaticStruct in deriving(Deserialize)") _ => cx.bug("expected StaticEnum or StaticStruct in derive(Deserialize)")
} }
} }
@ -486,8 +486,9 @@ fn deserialize_static_fields(
} }
} }
fn find_serial_name<'a, I: Iterator<&'a Attribute>>(mut iterator: I) fn find_serial_name<'a, I>(mut iterator: I) -> Option<token::InternedString> where
-> Option<token::InternedString> { I: Iterator<Item=&'a Attribute>
{
for at in iterator { for at in iterator {
match at.node.value.node { match at.node.value.node {
MetaNameValue(ref at_name, ref value) => { MetaNameValue(ref at_name, ref value) => {

View File

@ -10,13 +10,14 @@
use std::collections::{HashMap, HashSet, BTreeMap, BTreeSet}; use std::collections::{HashMap, HashSet, BTreeMap, BTreeSet};
use std::hash::Hash; use std::hash::Hash;
use std::num; use std::iter::FromIterator;
use std::rc::Rc; use std::num::{self, FromPrimitive};
use std::option; use std::option;
use std::rc::Rc;
use std::string; use std::string;
use std::sync::Arc; use std::sync::Arc;
#[deriving(Clone, PartialEq, Show)] #[derive(Clone, PartialEq, Show)]
pub enum Token { pub enum Token {
Null, Null,
Bool(bool), Bool(bool),
@ -77,7 +78,7 @@ impl Token {
} }
} }
#[deriving(Copy, Clone, PartialEq, Eq)] #[derive(Copy, Clone, PartialEq, Eq)]
pub enum TokenKind { pub enum TokenKind {
NullKind, NullKind,
BoolKind, BoolKind,
@ -176,7 +177,7 @@ macro_rules! to_result {
} }
} }
pub trait Deserializer<E>: Iterator<Result<Token, E>> { pub trait Deserializer<E>: Iterator<Item=Result<Token, E>> + Sized {
/// Called when a `Deserialize` expected more tokens, but the /// Called when a `Deserialize` expected more tokens, but the
/// `Deserializer` was empty. /// `Deserializer` was empty.
fn end_of_stream_error(&mut self) -> E; fn end_of_stream_error(&mut self) -> E;
@ -196,11 +197,13 @@ pub trait Deserializer<E>: Iterator<Result<Token, E>> {
T: Deserialize<Self, E> T: Deserialize<Self, E>
>(&mut self, field: &'static str) -> Result<T, E>; >(&mut self, field: &'static str) -> Result<T, E>;
/*
/// Called when a `Deserialize` has decided to not consume this token. /// Called when a `Deserialize` has decided to not consume this token.
fn ignore_field(&mut self, _token: Token) -> Result<(), E> { fn ignore_field(&mut self, _token: Token) -> Result<(), E> {
let _: IgnoreTokens = try!(Deserialize::deserialize(self)); let _: IgnoreTokens = try!(Deserialize::deserialize(self));
Ok(()) Ok(())
} }
*/
#[inline] #[inline]
fn expect_token(&mut self) -> Result<Token, E> { fn expect_token(&mut self) -> Result<Token, E> {
@ -584,7 +587,7 @@ pub trait Deserializer<E>: Iterator<Result<Token, E>> {
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
struct SeqDeserializer<'a, D: 'a, E: 'a> { struct SeqDeserializer<'a, D: 'a, E: 'a, T> {
d: &'a mut D, d: &'a mut D,
len: uint, len: uint,
err: &'a mut Option<E>, err: &'a mut Option<E>,
@ -595,7 +598,9 @@ impl<
D: Deserializer<E>, D: Deserializer<E>,
E, E,
T: Deserialize<D, E> T: Deserialize<D, E>
> Iterator<T> for SeqDeserializer<'a, D, E> { > Iterator for SeqDeserializer<'a, D, E, T> {
type Item = T;
#[inline] #[inline]
fn next(&mut self) -> option::Option<T> { fn next(&mut self) -> option::Option<T> {
match self.d.expect_seq_elt_or_end() { match self.d.expect_seq_elt_or_end() {
@ -618,7 +623,7 @@ impl<
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
struct MapDeserializer<'a, D:'a, E: 'a> { struct MapDeserializer<'a, D:'a, E: 'a, K, V> {
d: &'a mut D, d: &'a mut D,
len: uint, len: uint,
err: &'a mut option::Option<E>, err: &'a mut option::Option<E>,
@ -630,7 +635,9 @@ impl<
E, E,
K: Deserialize<D, E>, K: Deserialize<D, E>,
V: Deserialize<D, E> V: Deserialize<D, E>
> Iterator<(K, V)> for MapDeserializer<'a, D, E> { > Iterator for MapDeserializer<'a, D, E, K, V> {
type Item = (K, V);
#[inline] #[inline]
fn next(&mut self) -> option::Option<(K, V)> { fn next(&mut self) -> option::Option<(K, V)> {
match self.d.expect_map_elt_or_end() { match self.d.expect_map_elt_or_end() {
@ -650,7 +657,7 @@ impl<
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
pub trait Deserialize<D: Deserializer<E>, E> { pub trait Deserialize<D: Deserializer<E>, E>: Sized {
#[inline] #[inline]
fn deserialize(d: &mut D) -> Result<Self, E> { fn deserialize(d: &mut D) -> Result<Self, E> {
let token = try!(d.expect_token()); let token = try!(d.expect_token());
@ -850,7 +857,7 @@ impl_deserialize_tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
/// Helper struct that will ignore tokens while taking in consideration /// Helper struct that will ignore tokens while taking in consideration
/// recursive structures. /// recursive structures.
#[deriving(Copy)] #[derive(Copy)]
pub struct IgnoreTokens; pub struct IgnoreTokens;
impl<D: Deserializer<E>, E> Deserialize<D, E> for IgnoreTokens { impl<D: Deserializer<E>, E> Deserialize<D, E> for IgnoreTokens {
@ -1083,7 +1090,7 @@ mod tests {
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#[deriving(Clone, PartialEq, Show, Decodable)] #[derive(Clone, PartialEq, Show, RustcDecodable)]
struct Inner { struct Inner {
a: (), a: (),
b: uint, b: uint,
@ -1125,7 +1132,7 @@ mod tests {
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#[deriving(Clone, PartialEq, Show, Decodable)] #[derive(Clone, PartialEq, Show, RustcDecodable)]
struct Outer { struct Outer {
inner: Vec<Inner>, inner: Vec<Inner>,
} }
@ -1158,7 +1165,7 @@ mod tests {
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#[deriving(Clone, PartialEq, Show, Decodable)] #[derive(Clone, PartialEq, Show, RustcDecodable)]
enum Animal { enum Animal {
Dog, Dog,
Frog(string::String, int) Frog(string::String, int)
@ -1185,7 +1192,7 @@ mod tests {
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#[deriving(Show)] #[derive(Show)]
enum Error { enum Error {
EndOfStream, EndOfStream,
SyntaxError(Vec<TokenKind>), SyntaxError(Vec<TokenKind>),
@ -1200,7 +1207,7 @@ mod tests {
tokens: Iter, tokens: Iter,
} }
impl<Iter: Iterator<Token>> TokenDeserializer<Iter> { impl<Iter: Iterator<Item=Token>> TokenDeserializer<Iter> {
#[inline] #[inline]
fn new(tokens: Iter) -> TokenDeserializer<Iter> { fn new(tokens: Iter) -> TokenDeserializer<Iter> {
TokenDeserializer { TokenDeserializer {
@ -1209,14 +1216,16 @@ mod tests {
} }
} }
impl<Iter: Iterator<Token>> Iterator<Result<Token, Error>> for TokenDeserializer<Iter> { impl<Iter: Iterator<Item=Token>> Iterator for TokenDeserializer<Iter> {
type Item = Result<Token, Error>;
#[inline] #[inline]
fn next(&mut self) -> option::Option<Result<Token, Error>> { fn next(&mut self) -> option::Option<Result<Token, Error>> {
self.tokens.next().map(|token| Ok(token)) self.tokens.next().map(|token| Ok(token))
} }
} }
impl<Iter: Iterator<Token>> Deserializer<Error> for TokenDeserializer<Iter> { impl<Iter: Iterator<Item=Token>> Deserializer<Error> for TokenDeserializer<Iter> {
fn end_of_stream_error(&mut self) -> Error { fn end_of_stream_error(&mut self) -> Error {
Error::EndOfStream Error::EndOfStream
} }

View File

@ -7,7 +7,7 @@ use de;
use super::error::{Error, ErrorCode}; use super::error::{Error, ErrorCode};
#[deriving(PartialEq, Show)] #[derive(PartialEq, Show)]
enum State { enum State {
// Parse a value. // Parse a value.
Value, Value,
@ -37,7 +37,9 @@ pub struct Parser<Iter> {
buf: Vec<u8>, buf: Vec<u8>,
} }
impl<Iter: Iterator<u8>> Iterator<Result<de::Token, Error>> for Parser<Iter> { impl<Iter: Iterator<Item=u8>> Iterator for Parser<Iter> {
type Item = Result<de::Token, Error>;
#[inline] #[inline]
fn next(&mut self) -> Option<Result<de::Token, Error>> { fn next(&mut self) -> Option<Result<de::Token, Error>> {
let state = match self.state_stack.pop() { let state = match self.state_stack.pop() {
@ -80,7 +82,7 @@ impl<Iter: Iterator<u8>> Iterator<Result<de::Token, Error>> for Parser<Iter> {
} }
} }
impl<Iter: Iterator<u8>> Parser<Iter> { impl<Iter: Iterator<Item=u8>> Parser<Iter> {
/// Creates the JSON parser. /// Creates the JSON parser.
#[inline] #[inline]
pub fn new(rdr: Iter) -> Parser<Iter> { pub fn new(rdr: Iter) -> Parser<Iter> {
@ -395,7 +397,7 @@ impl<Iter: Iterator<u8>> Parser<Iter> {
} }
}; };
let buf = &mut [0u8, .. 4]; let buf = &mut [0u8; 4];
let len = c.encode_utf8(buf).unwrap_or(0); let len = c.encode_utf8(buf).unwrap_or(0);
self.buf.extend(buf.slice_to(len).iter().map(|b| *b)); self.buf.extend(buf.slice_to(len).iter().map(|b| *b));
} }
@ -515,7 +517,7 @@ impl<Iter: Iterator<u8>> Parser<Iter> {
} }
} }
impl<Iter: Iterator<u8>> de::Deserializer<Error> for Parser<Iter> { impl<Iter: Iterator<Item=u8>> de::Deserializer<Error> for Parser<Iter> {
fn end_of_stream_error(&mut self) -> Error { fn end_of_stream_error(&mut self) -> Error {
Error::SyntaxError(ErrorCode::EOFWhileParsingValue, self.line, self.col) Error::SyntaxError(ErrorCode::EOFWhileParsingValue, self.line, self.col)
} }
@ -635,7 +637,7 @@ impl<Iter: Iterator<u8>> de::Deserializer<Error> for Parser<Iter> {
/// Decodes a json value from an `Iterator<u8>`. /// Decodes a json value from an `Iterator<u8>`.
pub fn from_iter< pub fn from_iter<
Iter: Iterator<u8>, Iter: Iterator<Item=u8>,
T: de::Deserialize<Parser<Iter>, Error> T: de::Deserialize<Parser<Iter>, Error>
>(iter: Iter) -> Result<T, Error> { >(iter: Iter) -> Result<T, Error> {
let mut parser = Parser::new(iter); let mut parser = Parser::new(iter);

View File

@ -5,7 +5,7 @@ use std::io;
use de::{Token, TokenKind}; use de::{Token, TokenKind};
/// The errors that can arise while parsing a JSON stream. /// The errors that can arise while parsing a JSON stream.
#[deriving(Clone, PartialEq)] #[derive(Clone, PartialEq)]
pub enum ErrorCode { pub enum ErrorCode {
ConversionError(Token), ConversionError(Token),
EOFWhileParsingList, EOFWhileParsingList,
@ -78,7 +78,7 @@ impl fmt::Show for ErrorCode {
} }
} }
#[deriving(Clone, PartialEq, Show)] #[derive(Clone, PartialEq, Show)]
pub enum Error { pub enum Error {
/// msg, line, col /// msg, line, col
SyntaxError(ErrorCode, uint, uint), SyntaxError(ErrorCode, uint, uint),

View File

@ -55,12 +55,12 @@ of values to and from JSON via the serialization API.
To be able to serialize a piece of data, it must implement the `serde::Serialize` trait. To be able to serialize a piece of data, it must implement the `serde::Serialize` trait.
To be able to deserialize a piece of data, it must implement the `serde::Deserialize` trait. To be able to deserialize a piece of data, it must implement the `serde::Deserialize` trait.
The Rust compiler provides an annotation to automatically generate The Rust compiler provides an annotation to automatically generate
the code for these traits: `#[deriving_serialize]` and `#[deriving_deserialize]`. the code for these traits: `#[derive_serialize]` and `#[derive_deserialize]`.
To serialize using `Serialize`: To serialize using `Serialize`:
```rust ```rust
#![feature(phase)] #![feature(phase, old_orphan_check)]
#[phase(plugin)] #[phase(plugin)]
extern crate serde_macros; extern crate serde_macros;
extern crate serde; extern crate serde;
@ -69,7 +69,7 @@ use std::io::ByRefWriter;
use serde::json; use serde::json;
use serde::Serialize; use serde::Serialize;
#[deriving_serialize] #[derive_serialize]
pub struct TestStruct { pub struct TestStruct {
data_str: String, data_str: String,
} }
@ -110,7 +110,7 @@ A basic `ToJson` example using a BTreeMap of attribute name / attribute value:
```rust ```rust
#![feature(phase)] #![feature(phase, old_orphan_check)]
#[phase(plugin)] #[phase(plugin)]
extern crate serde_macros; extern crate serde_macros;
extern crate serde; extern crate serde;
@ -142,7 +142,7 @@ fn main() {
Or you can use the helper type `ObjectBuilder`: Or you can use the helper type `ObjectBuilder`:
```rust ```rust
#![feature(phase)] #![feature(phase, old_orphan_check)]
#[phase(plugin)] #[phase(plugin)]
extern crate serde_macros; extern crate serde_macros;
extern crate serde; extern crate serde;
@ -173,7 +173,7 @@ fn main() {
To deserialize a JSON string using `Deserialize` trait: To deserialize a JSON string using `Deserialize` trait:
```rust ```rust
#![feature(phase)] #![feature(phase, old_orphan_check)]
#[phase(plugin)] #[phase(plugin)]
extern crate serde_macros; extern crate serde_macros;
extern crate serde; extern crate serde;
@ -181,7 +181,7 @@ extern crate serde;
use serde::json; use serde::json;
use serde::Deserialize; use serde::Deserialize;
#[deriving_deserialize] #[derive_deserialize]
pub struct MyStruct { pub struct MyStruct {
attr1: u8, attr1: u8,
attr2: String, attr2: String,
@ -205,15 +205,15 @@ Create a struct called `TestStruct1` and serialize and deserialize it to and fro
using the serialization API, using the derived serialization code. using the serialization API, using the derived serialization code.
```rust ```rust
#![feature(phase)] #![feature(phase, old_orphan_check)]
#[phase(plugin)] #[phase(plugin)]
extern crate serde_macros; extern crate serde_macros;
extern crate serde; extern crate serde;
use serde::json; use serde::json;
#[deriving_serialize] #[derive_serialize]
#[deriving_deserialize] #[derive_deserialize]
pub struct TestStruct1 { pub struct TestStruct1 {
data_int: u8, data_int: u8,
data_str: String, data_str: String,
@ -245,7 +245,7 @@ This example use the ToJson impl to deserialize the JSON string.
Example of `ToJson` trait implementation for TestStruct1. Example of `ToJson` trait implementation for TestStruct1.
```rust ```rust
#![feature(phase)] #![feature(phase, old_orphan_check)]
#[phase(plugin)] #[phase(plugin)]
extern crate serde_macros; extern crate serde_macros;
extern crate serde; extern crate serde;
@ -254,8 +254,8 @@ use serde::json::ToJson;
use serde::json; use serde::json;
use serde::Deserialize; use serde::Deserialize;
#[deriving_serialize] // generate Serialize impl #[derive_serialize] // generate Serialize impl
#[deriving_deserialize] // generate Deserialize impl #[derive_deserialize] // generate Deserialize impl
pub struct TestStruct1 { pub struct TestStruct1 {
data_int: u8, data_int: u8,
data_str: String, data_str: String,
@ -357,9 +357,9 @@ mod tests {
}) })
} }
#[deriving(PartialEq, Show)] #[derive(PartialEq, Show)]
#[deriving_serialize] #[derive_serialize]
#[deriving_deserialize] #[derive_deserialize]
enum Animal { enum Animal {
Dog, Dog,
Frog(String, Vec<int>) Frog(String, Vec<int>)
@ -386,9 +386,9 @@ mod tests {
} }
} }
#[deriving(PartialEq, Show)] #[derive(PartialEq, Show)]
#[deriving_serialize] #[derive_serialize]
#[deriving_deserialize] #[derive_deserialize]
struct Inner { struct Inner {
a: (), a: (),
b: uint, b: uint,
@ -407,9 +407,9 @@ mod tests {
} }
} }
#[deriving(PartialEq, Show)] #[derive(PartialEq, Show)]
#[deriving_serialize] #[derive_serialize]
#[deriving_deserialize] #[derive_deserialize]
struct Outer { struct Outer {
inner: Vec<Inner>, inner: Vec<Inner>,
} }
@ -1103,9 +1103,9 @@ mod tests {
("\"jodhpurs\"", Some("jodhpurs".to_string())), ("\"jodhpurs\"", Some("jodhpurs".to_string())),
]); ]);
#[deriving(PartialEq, Show)] #[derive(PartialEq, Show)]
#[deriving_serialize] #[derive_serialize]
#[deriving_deserialize] #[derive_deserialize]
struct Foo { struct Foo {
x: Option<int>, x: Option<int>,
} }
@ -1177,23 +1177,23 @@ mod tests {
} }
/* /*
#[deriving(Decodable)] #[derive(Decodable)]
struct DecodeStruct { struct DecodeStruct {
x: f64, x: f64,
y: bool, y: bool,
z: String, z: String,
w: Vec<DecodeStruct> w: Vec<DecodeStruct>
} }
#[deriving(Decodable)] #[derive(Decodable)]
enum DecodeEnum { enum DecodeEnum {
A(f64), A(f64),
B(String) B(String)
} }
fn check_err<T: Decodable<Decoder, DecoderError>>(to_parse: &'static str, fn check_err<T: RustcDecodable<Decoder, DecoderError>>(to_parse: &'static str,
expected: DecoderError) { expected: DecoderError) {
let res: DecodeResult<T> = match from_str(to_parse) { let res: DecodeResult<T> = match from_str(to_parse) {
Err(e) => Err(ParseError(e)), Err(e) => Err(ParseError(e)),
Ok(json) => Decodable::decode(&mut Decoder::new(json)) Ok(json) => RustcDecodable::decode(&mut Decoder::new(json))
}; };
match res { match res {
Ok(_) => panic!("`{}` parsed & decoded ok, expecting error `{}`", Ok(_) => panic!("`{}` parsed & decoded ok, expecting error `{}`",
@ -1792,7 +1792,7 @@ mod bench {
let json = encoder_json(count); let json = encoder_json(count);
b.iter(|| { b.iter(|| {
assert_eq!(json.to_string(), src); assert_eq!(json.pretty().to_string(), src);
}); });
} }
@ -1801,7 +1801,7 @@ mod bench {
let json = encoder_json(count); let json = encoder_json(count);
b.iter(|| { b.iter(|| {
assert_eq!(json.to_pretty_str(), src); assert_eq!(json.pretty().to_string(), src);
}); });
} }

View File

@ -45,7 +45,7 @@ pub fn escape_str<W: Writer>(wr: &mut W, v: &str) -> IoResult<()> {
} }
fn escape_char<W: Writer>(wr: &mut W, v: char) -> IoResult<()> { fn escape_char<W: Writer>(wr: &mut W, v: char) -> IoResult<()> {
let buf = &mut [0, .. 4]; let buf = &mut [0; 4];
v.encode_utf8(buf); v.encode_utf8(buf);
escape_bytes(wr, buf) escape_bytes(wr, buf)
} }
@ -66,7 +66,7 @@ fn fmt_f64_or_null<W: Writer>(wr: &mut W, v: f64) -> IoResult<()> {
fn spaces<W: Writer>(wr: &mut W, mut n: uint) -> IoResult<()> { fn spaces<W: Writer>(wr: &mut W, mut n: uint) -> IoResult<()> {
const LEN: uint = 16; const LEN: uint = 16;
const BUF: &'static [u8, ..LEN] = &[b' ', ..LEN]; const BUF: &'static [u8; LEN] = &[b' '; LEN];
while n >= LEN { while n >= LEN {
try!(wr.write(BUF)); try!(wr.write(BUF));
@ -81,7 +81,7 @@ fn spaces<W: Writer>(wr: &mut W, mut n: uint) -> IoResult<()> {
} }
/* /*
#[deriving(Show)] #[derive(Show)]
enum SerializerState { enum SerializerState {
ValueState, ValueState,
TupleState, TupleState,
@ -287,7 +287,7 @@ impl<W: Writer> ser::Serializer<IoError> for Serializer<W> {
#[inline] #[inline]
fn serialize_seq< fn serialize_seq<
T: Serialize<Serializer<W>, IoError>, T: Serialize<Serializer<W>, IoError>,
Iter: Iterator<T> Iter: Iterator<Item=T>
>(&mut self, mut iter: Iter) -> IoResult<()> { >(&mut self, mut iter: Iter) -> IoResult<()> {
try!(self.wr.write_str("[")); try!(self.wr.write_str("["));
let mut first = true; let mut first = true;
@ -307,7 +307,7 @@ impl<W: Writer> ser::Serializer<IoError> for Serializer<W> {
fn serialize_map< fn serialize_map<
K: Serialize<Serializer<W>, IoError>, K: Serialize<Serializer<W>, IoError>,
V: Serialize<Serializer<W>, IoError>, V: Serialize<Serializer<W>, IoError>,
Iter: Iterator<(K, V)> Iter: Iterator<Item=(K, V)>
>(&mut self, mut iter: Iter) -> IoResult<()> { >(&mut self, mut iter: Iter) -> IoResult<()> {
try!(self.wr.write_str("{")); try!(self.wr.write_str("{"));
let mut first = true; let mut first = true;
@ -541,7 +541,7 @@ impl<W: Writer> ser::Serializer<IoError> for PrettySerializer<W> {
#[inline] #[inline]
fn serialize_seq< fn serialize_seq<
T: Serialize<PrettySerializer<W>, IoError>, T: Serialize<PrettySerializer<W>, IoError>,
Iter: Iterator<T> Iter: Iterator<Item=T>
>(&mut self, mut iter: Iter) -> IoResult<()> { >(&mut self, mut iter: Iter) -> IoResult<()> {
try!(self.wr.write_str("[")); try!(self.wr.write_str("["));
@ -558,7 +558,7 @@ impl<W: Writer> ser::Serializer<IoError> for PrettySerializer<W> {
fn serialize_map< fn serialize_map<
K: Serialize<PrettySerializer<W>, IoError>, K: Serialize<PrettySerializer<W>, IoError>,
V: Serialize<PrettySerializer<W>, IoError>, V: Serialize<PrettySerializer<W>, IoError>,
Iter: Iterator<(K, V)> Iter: Iterator<Item=(K, V)>
>(&mut self, mut iter: Iter) -> IoResult<()> { >(&mut self, mut iter: Iter) -> IoResult<()> {
try!(self.wr.write_str("{")); try!(self.wr.write_str("{"));

View File

@ -5,7 +5,7 @@ use std::io;
use std::str; use std::str;
use std::vec; use std::vec;
use de::{mod, Token, TokenKind}; use de::{self, Token, TokenKind};
use ser::Serialize; use ser::Serialize;
use ser; use ser;
@ -13,7 +13,7 @@ use super::ser::{Serializer, PrettySerializer};
use super::error::{Error, ErrorCode}; use super::error::{Error, ErrorCode};
/// Represents a JSON value /// Represents a JSON value
#[deriving(Clone, PartialEq, PartialOrd)] #[derive(Clone, PartialEq, PartialOrd)]
pub enum Value { pub enum Value {
Null, Null,
Boolean(bool), Boolean(bool),
@ -207,19 +207,21 @@ impl Value {
} }
} }
struct WriterFormatter<'a, 'b: 'a>(&'a mut fmt::Formatter<'b>); struct WriterFormatter<'a, 'b: 'a> {
inner: &'a mut fmt::Formatter<'b>,
}
impl<'a, 'b> Writer for WriterFormatter<'a, 'b> { impl<'a, 'b> Writer for WriterFormatter<'a, 'b> {
fn write(&mut self, buf: &[u8]) -> IoResult<()> { fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let WriterFormatter(ref mut f) = *self; self.inner.write_str(str::from_utf8(buf).unwrap()).map_err(|_| io::IoError::last_error())
f.write(buf).map_err(|_| io::IoError::last_error())
} }
} }
impl fmt::Show for Value { impl fmt::Show for Value {
/// Serializes a json value into a string /// Serializes a json value into a string
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.to_writer(WriterFormatter(f)).map_err(|_| fmt::Error) let wr = WriterFormatter { inner: f };
self.to_writer(wr).map_err(|_| fmt::Error)
} }
} }
@ -320,7 +322,9 @@ impl Deserializer {
} }
} }
impl Iterator<Result<Token, Error>> for Deserializer { impl Iterator for Deserializer {
type Item = Result<Token, Error>;
#[inline] #[inline]
fn next(&mut self) -> Option<Result<Token, Error>> { fn next(&mut self) -> Option<Result<Token, Error>> {
loop { loop {

View File

@ -2,6 +2,8 @@
#![crate_type = "dylib"] #![crate_type = "dylib"]
#![crate_type = "rlib"] #![crate_type = "rlib"]
#![feature(associated_types, old_orphan_check)]
// test harness access // test harness access
#[cfg(test)] #[cfg(test)]
extern crate test; extern crate test;
@ -12,6 +14,7 @@ extern crate serde_macros;
#[cfg(test)] #[cfg(test)]
extern crate serialize; extern crate serialize;
extern crate "rustc-serialize" as rustc_serialize;
extern crate unicode; extern crate unicode;
pub use de::{Deserializer, Deserialize}; pub use de::{Deserializer, Deserialize};

View File

@ -101,13 +101,13 @@ pub trait Serializer<E> {
fn serialize_seq< fn serialize_seq<
T: Serialize<Self, E>, T: Serialize<Self, E>,
Iter: Iterator<T> Iter: Iterator<Item=T>
>(&mut self, iter: Iter) -> Result<(), E>; >(&mut self, iter: Iter) -> Result<(), E>;
fn serialize_map< fn serialize_map<
K: Serialize<Self, E>, K: Serialize<Self, E>,
V: Serialize<Self, E>, V: Serialize<Self, E>,
Iter: Iterator<(K, V)> Iter: Iterator<Item=(K, V)>
>(&mut self, iter: Iter) -> Result<(), E>; >(&mut self, iter: Iter) -> Result<(), E>;
} }
@ -327,8 +327,8 @@ mod tests {
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#[deriving(Clone, PartialEq, Show, Decodable)] #[derive(Clone, PartialEq, Show, RustcDecodable)]
#[deriving_serialize] #[derive_serialize]
struct Inner { struct Inner {
a: (), a: (),
b: uint, b: uint,
@ -337,16 +337,16 @@ mod tests {
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#[deriving(Clone, PartialEq, Show, Decodable)] #[derive(Clone, PartialEq, Show, RustcDecodable)]
#[deriving_serialize] #[derive_serialize]
struct Outer { struct Outer {
inner: Vec<Inner>, inner: Vec<Inner>,
} }
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#[deriving(Clone, PartialEq, Show, Decodable)] #[derive(Clone, PartialEq, Show, RustcDecodable)]
#[deriving_serialize] #[derive_serialize]
enum Animal { enum Animal {
Dog, Dog,
Frog(String, int) Frog(String, int)
@ -354,7 +354,7 @@ mod tests {
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#[deriving(Clone, PartialEq, Show)] #[derive(Clone, PartialEq, Show)]
pub enum Token<'a> { pub enum Token<'a> {
Null, Null,
Bool(bool), Bool(bool),
@ -394,7 +394,7 @@ mod tests {
MapEnd, MapEnd,
} }
#[deriving(Show)] #[derive(Show)]
#[allow(dead_code)] #[allow(dead_code)]
enum Error { enum Error {
EndOfStream, EndOfStream,
@ -407,7 +407,7 @@ mod tests {
iter: Iter, iter: Iter,
} }
impl<'a, Iter: Iterator<Token<'a>>> AssertSerializer<Iter> { impl<'a, Iter: Iterator<Item=Token<'a>>> AssertSerializer<Iter> {
fn new(iter: Iter) -> AssertSerializer<Iter> { fn new(iter: Iter) -> AssertSerializer<Iter> {
AssertSerializer { AssertSerializer {
iter: iter, iter: iter,
@ -426,7 +426,7 @@ mod tests {
} }
} }
impl<'a, Iter: Iterator<Token<'a>>> Serializer<Error> for AssertSerializer<Iter> { impl<'a, Iter: Iterator<Item=Token<'a>>> Serializer<Error> for AssertSerializer<Iter> {
fn serialize_null(&mut self) -> Result<(), Error> { fn serialize_null(&mut self) -> Result<(), Error> {
self.serialize(Token::Null) self.serialize(Token::Null)
} }
@ -550,7 +550,7 @@ mod tests {
fn serialize_seq< fn serialize_seq<
T: Serialize<AssertSerializer<Iter>, Error>, T: Serialize<AssertSerializer<Iter>, Error>,
SeqIter: Iterator<T> SeqIter: Iterator<Item=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();
try!(self.serialize(Token::SeqStart(len))); try!(self.serialize(Token::SeqStart(len)));
@ -563,7 +563,7 @@ mod tests {
fn serialize_map< fn serialize_map<
K: Serialize<AssertSerializer<Iter>, Error>, K: Serialize<AssertSerializer<Iter>, Error>,
V: Serialize<AssertSerializer<Iter>, Error>, V: Serialize<AssertSerializer<Iter>, Error>,
MapIter: Iterator<(K, V)> MapIter: Iterator<Item=(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();
try!(self.serialize(Token::MapStart(len))); try!(self.serialize(Token::MapStart(len)));

View File

@ -1,12 +1,12 @@
#![feature(phase)] #![feature(phase, old_orphan_check)]
extern crate serde; extern crate serde;
#[phase(plugin)] #[phase(plugin)]
extern crate serde_macros; extern crate serde_macros;
#[deriving(PartialEq, Show)] #[derive(PartialEq, Show)]
#[deriving_serialize] #[derive_serialize]
#[deriving_deserialize] #[derive_deserialize]
struct Test { struct Test {
#[serial_name = "$schema"] #[serial_name = "$schema"]
schema: String, schema: String,