Merge remote-tracking branch 'remotes/kvark/rust'

This commit is contained in:
Erick Tryzelaar
2014-10-06 21:39:53 -07:00
8 changed files with 138 additions and 121 deletions
+2 -2
View File
@@ -49,7 +49,7 @@ mod decoder {
pub fn new(values: HashMap<String, int>) -> IntDecoder { pub fn new(values: HashMap<String, int>) -> IntDecoder {
IntDecoder { IntDecoder {
len: values.len(), len: values.len(),
iter: values.move_iter(), iter: values.into_iter(),
stack: vec!(), stack: vec!(),
} }
} }
@@ -195,7 +195,7 @@ mod deserializer {
IntDeserializer { IntDeserializer {
stack: vec!(StartState), stack: vec!(StartState),
len: values.len(), len: values.len(),
iter: values.move_iter(), iter: values.into_iter(),
} }
} }
} }
+4 -4
View File
@@ -214,7 +214,7 @@ mod decoder {
match self.stack.pop() { match self.stack.pop() {
Some(VecState(value)) => { Some(VecState(value)) => {
let len = value.len(); let len = value.len();
for inner in value.move_iter().rev() { for inner in value.into_iter().rev() {
self.stack.push(InnerState(inner)); self.stack.push(InnerState(inner));
} }
f(self, len) f(self, len)
@@ -232,7 +232,7 @@ mod decoder {
match self.stack.pop() { match self.stack.pop() {
Some(MapState(map)) => { Some(MapState(map)) => {
let len = map.len(); let len = map.len();
for (key, value) in map.move_iter() { for (key, value) in map.into_iter() {
match value { match value {
Some(c) => { Some(c) => {
self.stack.push(CharState(c)); self.stack.push(CharState(c));
@@ -322,7 +322,7 @@ mod deserializer {
Some(VecState(value)) => { Some(VecState(value)) => {
self.stack.push(EndState); self.stack.push(EndState);
let len = value.len(); let len = value.len();
for inner in value.move_iter().rev() { for inner in value.into_iter().rev() {
self.stack.push(InnerState(inner)); self.stack.push(InnerState(inner));
} }
Some(Ok(de::SeqStart(len))) Some(Ok(de::SeqStart(len)))
@@ -330,7 +330,7 @@ mod deserializer {
Some(MapState(value)) => { Some(MapState(value)) => {
self.stack.push(EndState); self.stack.push(EndState);
let len = value.len(); let len = value.len();
for (key, value) in value.move_iter() { for (key, value) in value.into_iter() {
match value { match value {
Some(c) => { Some(c) => {
self.stack.push(CharState(c)); self.stack.push(CharState(c));
+4 -4
View File
@@ -41,7 +41,7 @@ mod decoder {
pub fn new(values: Vec<int>) -> IntDecoder { pub fn new(values: Vec<int>) -> IntDecoder {
IntDecoder { IntDecoder {
len: values.len(), len: values.len(),
iter: values.move_iter(), iter: values.into_iter(),
} }
} }
} }
@@ -146,7 +146,7 @@ mod decoder {
pub fn new(values: Vec<u8>) -> U8Decoder { pub fn new(values: Vec<u8>) -> U8Decoder {
U8Decoder { U8Decoder {
len: values.len(), len: values.len(),
iter: values.move_iter(), iter: values.into_iter(),
} }
} }
} }
@@ -271,7 +271,7 @@ mod deserializer {
IntDeserializer { IntDeserializer {
state: StartState, state: StartState,
len: values.len(), len: values.len(),
iter: values.move_iter(), iter: values.into_iter(),
} }
} }
} }
@@ -343,7 +343,7 @@ mod deserializer {
U8Deserializer { U8Deserializer {
state: StartState, state: StartState,
len: values.len(), len: values.len(),
iter: values.move_iter(), iter: values.into_iter(),
} }
} }
} }
+8 -9
View File
@@ -17,7 +17,6 @@ use syntax::ast::{
ItemStruct, ItemStruct,
Expr, Expr,
MutMutable, MutMutable,
LitNil,
LitStr, LitStr,
StructField, StructField,
Variant, Variant,
@@ -25,7 +24,7 @@ use syntax::ast::{
use syntax::ast; use syntax::ast;
use syntax::attr; use syntax::attr;
use syntax::codemap::Span; use syntax::codemap::Span;
use syntax::ext::base::{ExtCtxt, ItemDecorator}; use syntax::ext::base::{ExtCtxt, Decorator};
use syntax::ext::build::AstBuilder; use syntax::ext::build::AstBuilder;
use syntax::ext::deriving::generic::{ use syntax::ext::deriving::generic::{
EnumMatching, EnumMatching,
@@ -61,11 +60,11 @@ use rustc::plugin::Registry;
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_serializable"), token::intern("deriving_serializable"),
ItemDecorator(box expand_deriving_serializable)); Decorator(box expand_deriving_serializable));
reg.register_syntax_extension( reg.register_syntax_extension(
token::intern("deriving_deserializable"), token::intern("deriving_deserializable"),
ItemDecorator(box expand_deriving_deserializable)); Decorator(box expand_deriving_deserializable));
} }
fn expand_deriving_serializable(cx: &mut ExtCtxt, fn expand_deriving_serializable(cx: &mut ExtCtxt,
@@ -137,7 +136,7 @@ fn serializable_substructure(cx: &ExtCtxt,
); );
let len = fields.len(); let len = fields.len();
let mut stmts: Vec<P<ast::Stmt>> = definition.fields.iter() let stmts: Vec<P<ast::Stmt>> = definition.fields.iter()
.zip(fields.iter()) .zip(fields.iter())
.enumerate() .enumerate()
.map(|(i, (def, &FieldInfo { name, ref self_, span, .. }))| { .map(|(i, (def, &FieldInfo { name, ref self_, span, .. }))| {
@@ -178,7 +177,7 @@ fn serializable_substructure(cx: &ExtCtxt,
let stmts: Vec<P<ast::Stmt>> = definition.variants.iter() let stmts: Vec<P<ast::Stmt>> = definition.variants.iter()
.zip(fields.iter()) .zip(fields.iter())
.map(|(def, &FieldInfo { ref self_, span, .. })| { .map(|(def, &FieldInfo { ref self_, .. })| {
let _serial_name = find_serial_name(def.node.attrs.iter()); let _serial_name = find_serial_name(def.node.attrs.iter());
quote_stmt!( quote_stmt!(
cx, cx,
@@ -336,7 +335,7 @@ fn deserialize_struct_from_struct(
fields: &StaticFields, fields: &StaticFields,
deserializer: P<ast::Expr> deserializer: P<ast::Expr>
) -> P<ast::Expr> { ) -> P<ast::Expr> {
let expect_struct_field = cx.ident_of("expect_struct_field"); //let expect_struct_field = cx.ident_of("expect_struct_field");
let call = deserializable_static_fields( let call = deserializable_static_fields(
cx, cx,
@@ -375,7 +374,7 @@ fn deserialize_struct_from_map(
// Declare each field. // Declare each field.
let let_fields: Vec<P<ast::Stmt>> = fields.iter() let let_fields: Vec<P<ast::Stmt>> = fields.iter()
.map(|&(name, span)| { .map(|&(name, _)| {
quote_stmt!(cx, let mut $name = None) quote_stmt!(cx, let mut $name = None)
}) })
.collect(); .collect();
@@ -494,7 +493,7 @@ fn deserialize_enum(
name, name,
serial_names.as_slice(), serial_names.as_slice(),
parts, parts,
|cx, span, _| { |cx, _, _| {
quote_expr!(cx, try!($deserializer.expect_enum_elt())) quote_expr!(cx, try!($deserializer.expect_enum_elt()))
} }
); );
+27 -23
View File
@@ -13,6 +13,8 @@ use std::gc::{GC, Gc};
use std::hash::Hash; use std::hash::Hash;
use std::num; use std::num;
use std::rc::Rc; use std::rc::Rc;
use std::option;
use std::string;
use std::sync::Arc; use std::sync::Arc;
#[deriving(Clone, PartialEq, Show)] #[deriving(Clone, PartialEq, Show)]
@@ -33,7 +35,7 @@ pub enum Token {
F64(f64), F64(f64),
Char(char), Char(char),
Str(&'static str), Str(&'static str),
String(String), String(string::String),
Option(bool), Option(bool),
TupleStart(uint), TupleStart(uint),
@@ -293,7 +295,7 @@ pub trait Deserializer<E>: Iterator<Result<Token, E>> {
} }
#[inline] #[inline]
fn expect_string(&mut self, token: Token) -> Result<String, E> { fn expect_string(&mut self, token: Token) -> Result<string::String, E> {
match token { match token {
Char(value) => Ok(value.to_string()), Char(value) => Ok(value.to_string()),
Str(value) => Ok(value.to_string()), Str(value) => Ok(value.to_string()),
@@ -305,7 +307,7 @@ pub trait Deserializer<E>: Iterator<Result<Token, E>> {
#[inline] #[inline]
fn expect_option< fn expect_option<
T: Deserializable<Self, E> T: Deserializable<Self, E>
>(&mut self, token: Token) -> Result<Option<T>, E> { >(&mut self, token: Token) -> Result<option::Option<T>, E> {
match token { match token {
Option(false) => Ok(None), Option(false) => Ok(None),
Option(true) => { Option(true) => {
@@ -429,7 +431,7 @@ pub trait Deserializer<E>: Iterator<Result<Token, E>> {
#[inline] #[inline]
fn expect_seq_elt_or_end< fn expect_seq_elt_or_end<
T: Deserializable<Self, E> T: Deserializable<Self, E>
>(&mut self) -> Result<Option<T>, E> { >(&mut self) -> Result<option::Option<T>, E> {
match try!(self.expect_token()) { match try!(self.expect_token()) {
End => Ok(None), End => Ok(None),
token => { token => {
@@ -473,7 +475,7 @@ pub trait Deserializer<E>: Iterator<Result<Token, E>> {
fn expect_map_elt_or_end< fn expect_map_elt_or_end<
K: Deserializable<Self, E>, K: Deserializable<Self, E>,
V: Deserializable<Self, E> V: Deserializable<Self, E>
>(&mut self) -> Result<Option<(K, V)>, E> { >(&mut self) -> Result<option::Option<(K, V)>, E> {
match try!(self.expect_token()) { match try!(self.expect_token()) {
End => Ok(None), End => Ok(None),
token => { token => {
@@ -513,7 +515,7 @@ pub trait Deserializer<E>: Iterator<Result<Token, E>> {
struct SeqDeserializer<'a, D: 'a, E> { struct SeqDeserializer<'a, D: 'a, E> {
d: &'a mut D, d: &'a mut D,
len: uint, len: uint,
err: Option<E>, err: option::Option<E>,
} }
impl< impl<
@@ -523,7 +525,7 @@ impl<
T: Deserializable<D, E> T: Deserializable<D, E>
> Iterator<T> for SeqDeserializer<'a, D, E> { > Iterator<T> for SeqDeserializer<'a, D, E> {
#[inline] #[inline]
fn next(&mut self) -> 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() {
Ok(next) => next, Ok(next) => next,
Err(err) => { Err(err) => {
@@ -534,7 +536,7 @@ impl<
} }
#[inline] #[inline]
fn size_hint(&self) -> (uint, Option<uint>) { fn size_hint(&self) -> (uint, option::Option<uint>) {
(self.len, Some(self.len)) (self.len, Some(self.len))
} }
} }
@@ -544,7 +546,7 @@ impl<
struct MapDeserializer<'a, D:'a, E> { struct MapDeserializer<'a, D:'a, E> {
d: &'a mut D, d: &'a mut D,
len: uint, len: uint,
err: Option<E>, err: option::Option<E>,
} }
impl< impl<
@@ -555,7 +557,7 @@ impl<
V: Deserializable<D, E> V: Deserializable<D, E>
> Iterator<(K, V)> for MapDeserializer<'a, D, E> { > Iterator<(K, V)> for MapDeserializer<'a, D, E> {
#[inline] #[inline]
fn next(&mut self) -> 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() {
Ok(next) => next, Ok(next) => next,
Err(err) => { Err(err) => {
@@ -566,7 +568,7 @@ impl<
} }
#[inline] #[inline]
fn size_hint(&self) -> (uint, Option<uint>) { fn size_hint(&self) -> (uint, option::Option<uint>) {
(self.len, Some(self.len)) (self.len, Some(self.len))
} }
} }
@@ -611,7 +613,7 @@ impl_deserializable!(f32, expect_num)
impl_deserializable!(f64, expect_num) impl_deserializable!(f64, expect_num)
impl_deserializable!(char, expect_char) impl_deserializable!(char, expect_char)
impl_deserializable!(&'static str, expect_str) impl_deserializable!(&'static str, expect_str)
impl_deserializable!(String, expect_string) impl_deserializable!(string::String, expect_string)
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
@@ -665,9 +667,9 @@ impl<
D: Deserializer<E>, D: Deserializer<E>,
E, E,
T: Deserializable<D ,E> T: Deserializable<D ,E>
> Deserializable<D, E> for Option<T> { > Deserializable<D, E> for option::Option<T> {
#[inline] #[inline]
fn deserialize_token(d: &mut D, token: Token) -> Result<Option<T>, E> { fn deserialize_token(d: &mut D, token: Token) -> Result<option::Option<T>, E> {
d.expect_option(token) d.expect_option(token)
} }
} }
@@ -989,6 +991,7 @@ impl<D: Deserializer<E>, E> Deserializable<D, E> for GatherTokens {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::collections::TreeMap; use std::collections::TreeMap;
use std::{option, string};
use serialize::Decoder; use serialize::Decoder;
use super::{Deserializer, Deserializable, Token, TokenKind}; use super::{Deserializer, Deserializable, Token, TokenKind};
@@ -1033,7 +1036,7 @@ mod tests {
struct Inner { struct Inner {
a: (), a: (),
b: uint, b: uint,
c: TreeMap<String, Option<char>>, c: TreeMap<string::String, option::Option<char>>,
} }
impl< impl<
@@ -1073,7 +1076,7 @@ mod tests {
#[deriving(Clone, PartialEq, Show, Decodable)] #[deriving(Clone, PartialEq, Show, Decodable)]
enum Animal { enum Animal {
Dog, Dog,
Frog(String, int) Frog(string::String, int)
} }
impl<D: Deserializer<E>, E> Deserializable<D, E> for Animal { impl<D: Deserializer<E>, E> Deserializable<D, E> for Animal {
@@ -1124,7 +1127,7 @@ mod tests {
impl<Iter: Iterator<Token>> Iterator<Result<Token, Error>> for TokenDeserializer<Iter> { impl<Iter: Iterator<Token>> Iterator<Result<Token, Error>> for TokenDeserializer<Iter> {
#[inline] #[inline]
fn next(&mut self) -> Option<Result<Token, Error>> { fn next(&mut self) -> option::Option<Result<Token, Error>> {
match self.tokens.next() { match self.tokens.next() {
None => None, None => None,
Some(token) => Some(Ok(token)), Some(token) => Some(Ok(token)),
@@ -1164,7 +1167,7 @@ mod tests {
#[test] #[test]
fn $name() { fn $name() {
$( $(
let mut deserializer = TokenDeserializer::new($tokens.move_iter()); let mut deserializer = TokenDeserializer::new($tokens.into_iter());
let value: $ty = Deserializable::deserialize(&mut deserializer).unwrap(); let value: $ty = Deserializable::deserialize(&mut deserializer).unwrap();
assert_eq!(value, $value); assert_eq!(value, $value);
@@ -1191,7 +1194,7 @@ mod tests {
vec!(F64(5.0)) => 5.0: f64, vec!(F64(5.0)) => 5.0: f64,
vec!(Char('c')) => 'c': char, vec!(Char('c')) => 'c': char,
vec!(Str("abc")) => "abc": &str, vec!(Str("abc")) => "abc": &str,
vec!(String("abc".to_string())) => "abc".to_string(): String vec!(String("abc".to_string())) => "abc".to_string(): string::String
]) ])
test_value!(test_tuples, [ test_value!(test_tuples, [
@@ -1225,12 +1228,12 @@ mod tests {
]) ])
test_value!(test_options, [ test_value!(test_options, [
vec!(Option(false)) => None: Option<int>, vec!(Option(false)) => None: option::Option<int>,
vec!( vec!(
Option(true), Option(true),
Int(5), Int(5),
) => Some(5): Option<int> ) => Some(5): option::Option<int>
]) ])
test_value!(test_structs, [ test_value!(test_structs, [
@@ -1332,7 +1335,7 @@ mod tests {
vec!( vec!(
MapStart(0), MapStart(0),
End, End,
) => treemap!(): TreeMap<int, String>, ) => treemap!(): TreeMap<int, string::String>,
vec!( vec!(
MapStart(2), MapStart(2),
@@ -1342,6 +1345,7 @@ mod tests {
Int(6), Int(6),
String("b".to_string()), String("b".to_string()),
End, End,
) => treemap!(5i => "a".to_string(), 6i => "b".to_string()): TreeMap<int, String> ) => treemap!(5i => "a".to_string(), 6i => "b".to_string()): TreeMap<int, string::
String>
]) ])
} }
+2 -2
View File
@@ -11,7 +11,7 @@
use std::collections::TreeMap; use std::collections::TreeMap;
use std::str::StrAllocating; use std::str::StrAllocating;
use super::{Json, List, Object, ToJson}; use super::{Json, JsonObject, List, Object, ToJson};
pub struct ListBuilder { pub struct ListBuilder {
list: Vec<Json>, list: Vec<Json>,
@@ -44,7 +44,7 @@ impl ListBuilder {
} }
pub struct ObjectBuilder { pub struct ObjectBuilder {
object: Object, object: JsonObject,
} }
impl ObjectBuilder { impl ObjectBuilder {
+72 -60
View File
@@ -274,7 +274,7 @@ use std::num::{FPNaN, FPInfinite};
use std::num; use std::num;
use std::str::ScalarValue; use std::str::ScalarValue;
use std::str; use std::str;
use std::string::String; use std::string;
use std::vec::Vec; use std::vec::Vec;
use std::vec; use std::vec;
@@ -291,13 +291,13 @@ pub enum Json {
Boolean(bool), Boolean(bool),
Integer(i64), Integer(i64),
Floating(f64), Floating(f64),
String(String), String(string::String),
List(List), List(JsonList),
Object(Object), Object(JsonObject),
} }
pub type List = Vec<Json>; pub type JsonList = Vec<Json>;
pub type Object = TreeMap<String, Json>; pub type JsonObject = TreeMap<string::String, Json>;
impl Json { impl Json {
/// Serializes a json value into an io::writer. Uses a single line. /// Serializes a json value into an io::writer. Uses a single line.
@@ -314,7 +314,7 @@ impl Json {
} }
/// Serializes a json value into a string /// Serializes a json value into a string
pub fn to_pretty_string(&self) -> String { pub fn to_pretty_string(&self) -> string::String {
let mut wr = MemWriter::new(); let mut wr = MemWriter::new();
self.to_pretty_writer(wr.by_ref()).unwrap(); self.to_pretty_writer(wr.by_ref()).unwrap();
str::from_utf8(wr.unwrap().as_slice()).unwrap().to_string() str::from_utf8(wr.unwrap().as_slice()).unwrap().to_string()
@@ -322,7 +322,7 @@ impl Json {
/// If the Json value is an Object, returns the value associated with the provided key. /// If the Json value is an Object, returns the value associated with the provided key.
/// Otherwise, returns None. /// Otherwise, returns None.
pub fn find<'a>(&'a self, key: &String) -> Option<&'a Json>{ pub fn find<'a>(&'a self, key: &string::String) -> Option<&'a Json>{
match self { match self {
&Object(ref map) => map.find(key), &Object(ref map) => map.find(key),
_ => None _ => None
@@ -332,7 +332,7 @@ impl Json {
/// Attempts to get a nested Json Object for each key in `keys`. /// Attempts to get a nested Json Object for each key in `keys`.
/// If any key is found not to exist, find_path will return None. /// If any key is found not to exist, find_path will return None.
/// Otherwise, it will return the Json value associated with the final key. /// Otherwise, it will return the Json value associated with the final key.
pub fn find_path<'a>(&'a self, keys: &[&String]) -> Option<&'a Json>{ pub fn find_path<'a>(&'a self, keys: &[&string::String]) -> Option<&'a Json>{
let mut target = self; let mut target = self;
for key in keys.iter() { for key in keys.iter() {
match target.find(*key) { match target.find(*key) {
@@ -346,7 +346,7 @@ impl Json {
/// If the Json value is an Object, performs a depth-first search until /// If the Json value is an Object, performs a depth-first search until
/// a value associated with the provided key is found. If no value is found /// a value associated with the provided key is found. If no value is found
/// or the Json value is not an Object, returns None. /// or the Json value is not an Object, returns None.
pub fn search<'a>(&'a self, key: &String) -> Option<&'a Json> { pub fn search<'a>(&'a self, key: &string::String) -> Option<&'a Json> {
match self { match self {
&Object(ref map) => { &Object(ref map) => {
match map.find(key) { match map.find(key) {
@@ -374,7 +374,7 @@ impl Json {
/// If the Json value is an Object, returns the associated TreeMap. /// If the Json value is an Object, returns the associated TreeMap.
/// Returns None otherwise. /// Returns None otherwise.
pub fn as_object<'a>(&'a self) -> Option<&'a Object> { pub fn as_object<'a>(&'a self) -> Option<&'a JsonObject> {
match *self { match *self {
Object(ref map) => Some(map), Object(ref map) => Some(map),
_ => None _ => None
@@ -388,7 +388,7 @@ impl Json {
/// If the Json value is a List, returns the associated vector. /// If the Json value is a List, returns the associated vector.
/// Returns None otherwise. /// Returns None otherwise.
pub fn as_list<'a>(&'a self) -> Option<&'a List> { pub fn as_list<'a>(&'a self) -> Option<&'a JsonList> {
match *self { match *self {
List(ref list) => Some(list), List(ref list) => Some(list),
_ => None _ => None
@@ -482,10 +482,19 @@ impl Json {
} }
} }
struct WriterFormatter<'a, 'b: 'a>(&'a mut fmt::Formatter<'b>);
impl<'a, 'b> Writer for WriterFormatter<'a, 'b> {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let WriterFormatter(ref mut f) = *self;
f.write(buf).map_err(|_| io::IoError::last_error())
}
}
impl fmt::Show for Json { impl fmt::Show for Json {
/// 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(f as &mut Writer).map_err(|_| fmt::WriteError) self.to_writer(WriterFormatter(f)).map_err(|_| fmt::WriteError)
} }
} }
@@ -564,7 +573,7 @@ impl<D: de::Deserializer<E>, E> de::Deserializable<D, E> for Json {
enum JsonDeserializerState { enum JsonDeserializerState {
JsonDeserializerValueState(Json), JsonDeserializerValueState(Json),
JsonDeserializerListState(vec::MoveItems<Json>), JsonDeserializerListState(vec::MoveItems<Json>),
JsonDeserializerObjectState(treemap::MoveEntries<String, Json>), JsonDeserializerObjectState(treemap::MoveEntries<string::String, Json>),
JsonDeserializerEndState, JsonDeserializerEndState,
} }
@@ -595,12 +604,12 @@ impl Iterator<Result<de::Token, ParserError>> for JsonDeserializer {
String(x) => de::String(x), String(x) => de::String(x),
List(x) => { List(x) => {
let len = x.len(); let len = x.len();
self.stack.push(JsonDeserializerListState(x.move_iter())); self.stack.push(JsonDeserializerListState(x.into_iter()));
de::SeqStart(len) de::SeqStart(len)
} }
Object(x) => { Object(x) => {
let len = x.len(); let len = x.len();
self.stack.push(JsonDeserializerObjectState(x.move_iter())); self.stack.push(JsonDeserializerObjectState(x.into_iter()));
de::MapStart(len) de::MapStart(len)
} }
}; };
@@ -716,7 +725,7 @@ impl de::Deserializer<ParserError> for JsonDeserializer {
self.stack.push(JsonDeserializerEndState); self.stack.push(JsonDeserializerEndState);
for field in fields.move_iter().rev() { for field in fields.into_iter().rev() {
self.stack.push(JsonDeserializerValueState(field)); self.stack.push(JsonDeserializerValueState(field));
} }
@@ -786,9 +795,9 @@ pub enum ParserError {
/// msg, line, col /// msg, line, col
SyntaxError(ErrorCode, uint, uint), SyntaxError(ErrorCode, uint, uint),
IoError(io::IoErrorKind, &'static str), IoError(io::IoErrorKind, &'static str),
ExpectedError(String, String), ExpectedError(string::String, string::String),
MissingFieldError(String), MissingFieldError(string::String),
UnknownVariantError(String), UnknownVariantError(string::String),
} }
// Builder and Parser have the same errors. // Builder and Parser have the same errors.
@@ -1139,6 +1148,8 @@ impl<W: Writer> ser::Serializer<io::IoError> for Serializer<W> {
V: Serializable<Serializer<W>, io::IoError>, 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<()> {
//Warning: WriterFormatter was added to work around
// the stack overflow happening on this line
try!(self.wr.write_str("{")); try!(self.wr.write_str("{"));
let mut first = true; let mut first = true;
for (key, value) in iter { for (key, value) in iter {
@@ -1150,7 +1161,6 @@ impl<W: Writer> ser::Serializer<io::IoError> for Serializer<W> {
try!(key.serialize(self)); try!(key.serialize(self));
try!(self.wr.write_str(":")); try!(self.wr.write_str(":"));
try!(value.serialize(self)); try!(value.serialize(self));
} }
self.wr.write_str("}") self.wr.write_str("}")
} }
@@ -1422,9 +1432,9 @@ pub fn to_vec<
#[inline] #[inline]
pub fn to_string< pub fn to_string<
T: ser::Serializable<Serializer<MemWriter>, io::IoError> T: ser::Serializable<Serializer<MemWriter>, io::IoError>
>(value: &T) -> Result<String, Vec<u8>> { >(value: &T) -> Result<string::String, Vec<u8>> {
let buf = to_vec(value); let buf = to_vec(value);
String::from_utf8(buf) string::String::from_utf8(buf)
} }
/// Encode the specified struct into a json `[u8]` buffer. /// Encode the specified struct into a json `[u8]` buffer.
@@ -1440,9 +1450,9 @@ pub fn to_pretty_vec<
/// Encode the specified struct into a json `String` buffer. /// Encode the specified struct into a json `String` buffer.
pub fn to_pretty_string< pub fn to_pretty_string<
T: ser::Serializable<PrettySerializer<MemWriter>, io::IoError> T: ser::Serializable<PrettySerializer<MemWriter>, io::IoError>
>(value: &T) -> Result<String, Vec<u8>> { >(value: &T) -> Result<string::String, Vec<u8>> {
let buf = to_pretty_vec(value); let buf = to_pretty_vec(value);
String::from_utf8(buf) string::String::from_utf8(buf)
} }
/* /*
@@ -1748,14 +1758,14 @@ impl<Iter: Iterator<char>> Parser<Iter> {
// There can be only one leading '0'. // There can be only one leading '0'.
match self.ch_or_null() { match self.ch_or_null() {
'0' .. '9' => return self.error(InvalidNumber), '0' ... '9' => return self.error(InvalidNumber),
_ => () _ => ()
} }
}, },
'1' .. '9' => { '1' ... '9' => {
while !self.eof() { while !self.eof() {
match self.ch_or_null() { match self.ch_or_null() {
c @ '0' .. '9' => { c @ '0' ... '9' => {
res *= 10; res *= 10;
res += (c as i64) - ('0' as i64); res += (c as i64) - ('0' as i64);
self.bump(); self.bump();
@@ -1775,7 +1785,7 @@ impl<Iter: Iterator<char>> Parser<Iter> {
// Make sure a digit follows the decimal place. // Make sure a digit follows the decimal place.
match self.ch_or_null() { match self.ch_or_null() {
'0' .. '9' => (), '0' ... '9' => (),
_ => return self.error(InvalidNumber) _ => return self.error(InvalidNumber)
} }
@@ -1783,7 +1793,7 @@ impl<Iter: Iterator<char>> Parser<Iter> {
let mut dec = 1.0; let mut dec = 1.0;
while !self.eof() { while !self.eof() {
match self.ch_or_null() { match self.ch_or_null() {
c @ '0' .. '9' => { c @ '0' ... '9' => {
dec /= 10.0; dec /= 10.0;
res += (((c as int) - ('0' as int)) as f64) * dec; res += (((c as int) - ('0' as int)) as f64) * dec;
self.bump(); self.bump();
@@ -1810,12 +1820,12 @@ impl<Iter: Iterator<char>> Parser<Iter> {
// Make sure a digit follows the exponent place. // Make sure a digit follows the exponent place.
match self.ch_or_null() { match self.ch_or_null() {
'0' .. '9' => (), '0' ... '9' => (),
_ => return self.error(InvalidNumber) _ => return self.error(InvalidNumber)
} }
while !self.eof() { while !self.eof() {
match self.ch_or_null() { match self.ch_or_null() {
c @ '0' .. '9' => { c @ '0' ... '9' => {
exp *= 10; exp *= 10;
exp += (c as uint) - ('0' as uint); exp += (c as uint) - ('0' as uint);
@@ -1841,7 +1851,7 @@ impl<Iter: Iterator<char>> Parser<Iter> {
while i < 4u && !self.eof() { while i < 4u && !self.eof() {
self.bump(); self.bump();
n = match self.ch_or_null() { n = match self.ch_or_null() {
c @ '0' .. '9' => n * 16_u16 + ((c as u16) - ('0' as u16)), c @ '0' ... '9' => n * 16_u16 + ((c as u16) - ('0' as u16)),
'a' | 'A' => n * 16_u16 + 10_u16, 'a' | 'A' => n * 16_u16 + 10_u16,
'b' | 'B' => n * 16_u16 + 11_u16, 'b' | 'B' => n * 16_u16 + 11_u16,
'c' | 'C' => n * 16_u16 + 12_u16, 'c' | 'C' => n * 16_u16 + 12_u16,
@@ -1862,9 +1872,9 @@ impl<Iter: Iterator<char>> Parser<Iter> {
Ok(n) Ok(n)
} }
fn parse_string(&mut self) -> Result<String, ParserError> { fn parse_string(&mut self) -> Result<string::String, ParserError> {
let mut escape = false; let mut escape = false;
let mut res = String::new(); let mut res = string::String::new();
loop { loop {
self.bump(); self.bump();
@@ -1874,20 +1884,20 @@ impl<Iter: Iterator<char>> Parser<Iter> {
if escape { if escape {
match self.ch_or_null() { match self.ch_or_null() {
'"' => res.push_char('"'), '"' => res.push('"'),
'\\' => res.push_char('\\'), '\\' => res.push('\\'),
'/' => res.push_char('/'), '/' => res.push('/'),
'b' => res.push_char('\x08'), 'b' => res.push('\x08'),
'f' => res.push_char('\x0c'), 'f' => res.push('\x0c'),
'n' => res.push_char('\n'), 'n' => res.push('\n'),
'r' => res.push_char('\r'), 'r' => res.push('\r'),
't' => res.push_char('\t'), 't' => res.push('\t'),
'u' => match try!(self.decode_hex_escape()) { 'u' => match try!(self.decode_hex_escape()) {
0xDC00 .. 0xDFFF => return self.error(LoneLeadingSurrogateInHexEscape), 0xDC00 ... 0xDFFF => return self.error(LoneLeadingSurrogateInHexEscape),
// Non-BMP characters are encoded as a sequence of // Non-BMP characters are encoded as a sequence of
// two hex escapes, representing UTF-16 surrogates. // two hex escapes, representing UTF-16 surrogates.
n1 @ 0xD800 .. 0xDBFF => { n1 @ 0xD800 ... 0xDBFF => {
let c1 = self.next_char(); let c1 = self.next_char();
let c2 = self.next_char(); let c2 = self.next_char();
match (c1, c2) { match (c1, c2) {
@@ -1897,13 +1907,13 @@ impl<Iter: Iterator<char>> Parser<Iter> {
let buf = [n1, try!(self.decode_hex_escape())]; let buf = [n1, try!(self.decode_hex_escape())];
match str::utf16_items(buf.as_slice()).next() { match str::utf16_items(buf.as_slice()).next() {
Some(ScalarValue(c)) => res.push_char(c), Some(ScalarValue(c)) => res.push(c),
_ => return self.error(LoneLeadingSurrogateInHexEscape), _ => return self.error(LoneLeadingSurrogateInHexEscape),
} }
} }
n => match char::from_u32(n as u32) { n => match char::from_u32(n as u32) {
Some(c) => res.push_char(c), Some(c) => res.push(c),
None => return self.error(InvalidUnicodeCodePoint), None => return self.error(InvalidUnicodeCodePoint),
}, },
}, },
@@ -1918,7 +1928,7 @@ impl<Iter: Iterator<char>> Parser<Iter> {
self.bump(); self.bump();
return Ok(res); return Ok(res);
}, },
Some(c) => res.push_char(c), Some(c) => res.push(c),
None => unreachable!() None => unreachable!()
} }
} }
@@ -2024,7 +2034,7 @@ impl<Iter: Iterator<char>> Parser<Iter> {
'n' => self.parse_ident("ull", de::Null), 'n' => self.parse_ident("ull", de::Null),
't' => self.parse_ident("rue", de::Bool(true)), 't' => self.parse_ident("rue", de::Bool(true)),
'f' => self.parse_ident("alse", de::Bool(false)), 'f' => self.parse_ident("alse", de::Bool(false)),
'0' .. '9' | '-' => self.parse_number(), '0' ... '9' | '-' => self.parse_number(),
'"' => { '"' => {
let s = try!(self.parse_string()); let s = try!(self.parse_string());
Ok(de::String(s)) Ok(de::String(s))
@@ -2260,7 +2270,7 @@ impl<'a> ToJson for &'a str {
fn to_json(&self) -> Json { String(self.to_string()) } fn to_json(&self) -> Json { String(self.to_string()) }
} }
impl ToJson for String { impl ToJson for string::String {
fn to_json(&self) -> Json { String((*self).clone()) } fn to_json(&self) -> Json { String((*self).clone()) }
} }
@@ -2306,7 +2316,7 @@ impl<A:ToJson> ToJson for Vec<A> {
fn to_json(&self) -> Json { List(self.iter().map(|elt| elt.to_json()).collect()) } fn to_json(&self) -> Json { List(self.iter().map(|elt| elt.to_json()).collect()) }
} }
impl<A:ToJson> ToJson for TreeMap<String, A> { impl<A:ToJson> ToJson for TreeMap<string::String, A> {
fn to_json(&self) -> Json { fn to_json(&self) -> Json {
let mut d = TreeMap::new(); let mut d = TreeMap::new();
for (key, value) in self.iter() { for (key, value) in self.iter() {
@@ -2316,7 +2326,7 @@ impl<A:ToJson> ToJson for TreeMap<String, A> {
} }
} }
impl<A:ToJson> ToJson for HashMap<String, A> { impl<A:ToJson> ToJson for HashMap<string::String, A> {
fn to_json(&self) -> Json { fn to_json(&self) -> Json {
let mut d = TreeMap::new(); let mut d = TreeMap::new();
for (key, value) in self.iter() { for (key, value) in self.iter() {
@@ -2340,6 +2350,7 @@ mod tests {
use std::fmt::Show; use std::fmt::Show;
use std::io; use std::io;
use std::str; use std::str;
use std::string;
use std::collections::TreeMap; use std::collections::TreeMap;
use super::{Json, Null, Boolean, Floating, String, List, Object}; use super::{Json, Null, Boolean, Floating, String, List, Object};
@@ -2378,7 +2389,7 @@ mod tests {
#[deriving_deserializable] #[deriving_deserializable]
enum Animal { enum Animal {
Dog, Dog,
Frog(String, Vec<int>) Frog(string::String, Vec<int>)
} }
impl ToJson for Animal { impl ToJson for Animal {
@@ -2408,7 +2419,7 @@ mod tests {
struct Inner { struct Inner {
a: (), a: (),
b: uint, b: uint,
c: Vec<String>, c: Vec<string::String>,
} }
impl ToJson for Inner { impl ToJson for Inner {
@@ -2922,7 +2933,7 @@ mod tests {
#[test] #[test]
fn test_parse_string() { fn test_parse_string() {
test_parse_err::<String>([ test_parse_err::<string::String>([
("\"", SyntaxError(EOFWhileParsingString, 1, 2)), ("\"", SyntaxError(EOFWhileParsingString, 1, 2)),
("\"lol", SyntaxError(EOFWhileParsingString, 1, 5)), ("\"lol", SyntaxError(EOFWhileParsingString, 1, 5)),
("\"lol\"a", SyntaxError(TrailingCharacters, 1, 6)), ("\"lol\"a", SyntaxError(TrailingCharacters, 1, 6)),
@@ -3018,7 +3029,7 @@ mod tests {
#[test] #[test]
fn test_parse_object() { fn test_parse_object() {
test_parse_err::<TreeMap<String, int>>([ test_parse_err::<TreeMap<string::String, int>>([
("{", SyntaxError(EOFWhileParsingString, 1, 2)), ("{", SyntaxError(EOFWhileParsingString, 1, 2)),
("{ ", SyntaxError(EOFWhileParsingString, 1, 3)), ("{ ", SyntaxError(EOFWhileParsingString, 1, 3)),
("{1", SyntaxError(KeyMustBeAString, 1, 2)), ("{1", SyntaxError(KeyMustBeAString, 1, 2)),
@@ -3187,7 +3198,7 @@ mod tests {
#[test] #[test]
fn test_multiline_errors() { fn test_multiline_errors() {
test_parse_err::<TreeMap<String, String>>([ test_parse_err::<TreeMap<string::String, string::String>>([
("{\n \"foo\":\n \"bar\"", SyntaxError(EOFWhileParsingObject, 3u, 8u)), ("{\n \"foo\":\n \"bar\"", SyntaxError(EOFWhileParsingObject, 3u, 8u)),
]); ]);
} }
@@ -3283,7 +3294,7 @@ mod tests {
fn test_as_object() { fn test_as_object() {
let json_value: Json = from_str("{}").unwrap(); let json_value: Json = from_str("{}").unwrap();
let json_object = json_value.as_object(); let json_object = json_value.as_object();
let map = TreeMap::<String, Json>::new(); let map = TreeMap::<string::String, Json>::new();
assert_eq!(json_object, Some(&map)); assert_eq!(json_object, Some(&map));
} }
@@ -3717,6 +3728,7 @@ mod tests {
#[cfg(test)] #[cfg(test)]
mod bench { mod bench {
use std::collections::TreeMap; use std::collections::TreeMap;
use std::string;
use serialize; use serialize;
use test::Bencher; use test::Bencher;
@@ -3732,7 +3744,7 @@ mod bench {
}) })
} }
fn json_str(count: uint) -> String { fn json_str(count: uint) -> string::String {
let mut src = "[".to_string(); let mut src = "[".to_string();
for _ in range(0, count) { for _ in range(0, count) {
src.push_str(r#"{"a":true,"b":null,"c":3.1415,"d":"Hello world","e":[1,2,3]},"#); src.push_str(r#"{"a":true,"b":null,"c":3.1415,"d":"Hello world","e":[1,2,3]},"#);
@@ -3741,7 +3753,7 @@ mod bench {
src src
} }
fn pretty_json_str(count: uint) -> String { fn pretty_json_str(count: uint) -> string::String {
let mut src = "[\n".to_string(); let mut src = "[\n".to_string();
for _ in range(0, count) { for _ in range(0, count) {
src.push_str( src.push_str(
+19 -17
View File
@@ -321,6 +321,8 @@ impl_serialize_tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
mod tests { mod tests {
use std::collections::{HashMap, TreeMap}; use std::collections::{HashMap, TreeMap};
use std::{option, string};
use serialize::Decoder; use serialize::Decoder;
use super::{Serializer, Serializable}; use super::{Serializer, Serializable};
@@ -332,7 +334,7 @@ mod tests {
struct Inner { struct Inner {
a: (), a: (),
b: uint, b: uint,
c: HashMap<String, Option<char>>, c: HashMap<string::String, option::Option<char>>,
} }
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
@@ -535,7 +537,7 @@ mod tests {
fn serialize_option< fn serialize_option<
T: Serializable<AssertSerializer<Iter>, Error> T: Serializable<AssertSerializer<Iter>, Error>
>(&mut self, v: &Option<T>) -> Result<(), Error> { >(&mut self, v: &option::Option<T>) -> Result<(), Error> {
match *v { match *v {
Some(ref v) => { Some(ref v) => {
try!(self.serialize(Option(true))); try!(self.serialize(Option(true)));
@@ -581,7 +583,7 @@ mod tests {
let tokens = vec!( let tokens = vec!(
Int(5) Int(5)
); );
let mut serializer = AssertSerializer::new(tokens.move_iter()); let mut serializer = AssertSerializer::new(tokens.into_iter());
5i.serialize(&mut serializer).unwrap(); 5i.serialize(&mut serializer).unwrap();
assert_eq!(serializer.iter.next(), None); assert_eq!(serializer.iter.next(), None);
} }
@@ -592,7 +594,7 @@ mod tests {
Str("a"), Str("a"),
); );
let mut serializer = AssertSerializer::new(tokens.move_iter()); let mut serializer = AssertSerializer::new(tokens.into_iter());
"a".serialize(&mut serializer).unwrap(); "a".serialize(&mut serializer).unwrap();
assert_eq!(serializer.iter.next(), None); assert_eq!(serializer.iter.next(), None);
} }
@@ -603,7 +605,7 @@ mod tests {
Null, Null,
); );
let mut serializer = AssertSerializer::new(tokens.move_iter()); let mut serializer = AssertSerializer::new(tokens.into_iter());
().serialize(&mut serializer).unwrap(); ().serialize(&mut serializer).unwrap();
assert_eq!(serializer.iter.next(), None); assert_eq!(serializer.iter.next(), None);
} }
@@ -614,7 +616,7 @@ mod tests {
Option(false), Option(false),
); );
let mut serializer = AssertSerializer::new(tokens.move_iter()); let mut serializer = AssertSerializer::new(tokens.into_iter());
None::<int>.serialize(&mut serializer).unwrap(); None::<int>.serialize(&mut serializer).unwrap();
assert_eq!(serializer.iter.next(), None); assert_eq!(serializer.iter.next(), None);
} }
@@ -626,7 +628,7 @@ mod tests {
Int(5), Int(5),
); );
let mut serializer = AssertSerializer::new(tokens.move_iter()); let mut serializer = AssertSerializer::new(tokens.into_iter());
Some(5i).serialize(&mut serializer).unwrap(); Some(5i).serialize(&mut serializer).unwrap();
assert_eq!(serializer.iter.next(), None); assert_eq!(serializer.iter.next(), None);
} }
@@ -643,7 +645,7 @@ mod tests {
TupleEnd, TupleEnd,
); );
let mut serializer = AssertSerializer::new(tokens.move_iter()); let mut serializer = AssertSerializer::new(tokens.into_iter());
(5i, "a").serialize(&mut serializer).unwrap(); (5i, "a").serialize(&mut serializer).unwrap();
assert_eq!(serializer.iter.next(), None); assert_eq!(serializer.iter.next(), None);
} }
@@ -669,7 +671,7 @@ mod tests {
TupleEnd, TupleEnd,
); );
let mut serializer = AssertSerializer::new(tokens.move_iter()); let mut serializer = AssertSerializer::new(tokens.into_iter());
((), (), (5i, "a")).serialize(&mut serializer).unwrap(); ((), (), (5i, "a")).serialize(&mut serializer).unwrap();
assert_eq!(serializer.iter.next(), None); assert_eq!(serializer.iter.next(), None);
} }
@@ -684,7 +686,7 @@ mod tests {
StructEnd, StructEnd,
); );
let mut serializer = AssertSerializer::new(tokens.move_iter()); let mut serializer = AssertSerializer::new(tokens.into_iter());
Outer { inner: vec!() }.serialize(&mut serializer).unwrap(); Outer { inner: vec!() }.serialize(&mut serializer).unwrap();
assert_eq!(serializer.iter.next(), None); assert_eq!(serializer.iter.next(), None);
} }
@@ -713,7 +715,7 @@ mod tests {
StructEnd, StructEnd,
); );
let mut serializer = AssertSerializer::new(tokens.move_iter()); let mut serializer = AssertSerializer::new(tokens.into_iter());
let mut map = HashMap::new(); let mut map = HashMap::new();
map.insert("abc".to_string(), Some('c')); map.insert("abc".to_string(), Some('c'));
@@ -737,7 +739,7 @@ mod tests {
EnumEnd, EnumEnd,
); );
let mut serializer = AssertSerializer::new(tokens.move_iter()); let mut serializer = AssertSerializer::new(tokens.into_iter());
Dog.serialize(&mut serializer).unwrap(); Dog.serialize(&mut serializer).unwrap();
assert_eq!(serializer.iter.next(), None); assert_eq!(serializer.iter.next(), None);
@@ -751,7 +753,7 @@ mod tests {
EnumEnd, EnumEnd,
); );
let mut serializer = AssertSerializer::new(tokens.move_iter()); let mut serializer = AssertSerializer::new(tokens.into_iter());
Frog("Henry".to_string(), 349).serialize(&mut serializer).unwrap(); Frog("Henry".to_string(), 349).serialize(&mut serializer).unwrap();
assert_eq!(serializer.iter.next(), None); assert_eq!(serializer.iter.next(), None);
} }
@@ -763,7 +765,7 @@ mod tests {
SeqEnd, SeqEnd,
); );
let mut serializer = AssertSerializer::new(tokens.move_iter()); let mut serializer = AssertSerializer::new(tokens.into_iter());
let v: Vec<int> = vec!(); let v: Vec<int> = vec!();
v.serialize(&mut serializer).unwrap(); v.serialize(&mut serializer).unwrap();
assert_eq!(serializer.iter.next(), None); assert_eq!(serializer.iter.next(), None);
@@ -779,7 +781,7 @@ mod tests {
SeqEnd, SeqEnd,
); );
let mut serializer = AssertSerializer::new(tokens.move_iter()); let mut serializer = AssertSerializer::new(tokens.into_iter());
(vec!(5i, 6, 7)).serialize(&mut serializer).unwrap(); (vec!(5i, 6, 7)).serialize(&mut serializer).unwrap();
assert_eq!(serializer.iter.next(), None); assert_eq!(serializer.iter.next(), None);
} }
@@ -805,7 +807,7 @@ mod tests {
SeqEnd, SeqEnd,
); );
let mut serializer = AssertSerializer::new(tokens.move_iter()); let mut serializer = AssertSerializer::new(tokens.into_iter());
(vec!(vec!(1i), vec!(2, 3), vec!(4, 5, 6))).serialize(&mut serializer).unwrap(); (vec!(vec!(1i), vec!(2, 3), vec!(4, 5, 6))).serialize(&mut serializer).unwrap();
assert_eq!(serializer.iter.next(), None); assert_eq!(serializer.iter.next(), None);
} }
@@ -822,7 +824,7 @@ mod tests {
MapEnd, MapEnd,
); );
let mut serializer = AssertSerializer::new(tokens.move_iter()); let mut serializer = AssertSerializer::new(tokens.into_iter());
let mut map = TreeMap::new(); let mut map = TreeMap::new();
map.insert(5i, "a".to_string()); map.insert(5i, "a".to_string());