1
Fork 0

Rollup merge of 21662 - oli-obk:hashmap_enum_json, r=alexcrichton

This commit is contained in:
Manish Goregaokar 2015-01-29 03:15:51 +05:30
commit 62b24c3dd5
5 changed files with 29 additions and 13 deletions

View file

@ -97,7 +97,7 @@
//! }; //! };
//! //!
//! // Serialize using `json::encode` //! // Serialize using `json::encode`
//! let encoded = json::encode(&object); //! let encoded = json::encode(&object).unwrap();
//! //!
//! // Deserialize using `json::decode` //! // Deserialize using `json::decode`
//! let decoded: TestStruct = json::decode(encoded.as_slice()).unwrap(); //! let decoded: TestStruct = json::decode(encoded.as_slice()).unwrap();
@ -143,7 +143,7 @@
//! uid: 1, //! uid: 1,
//! dsc: "test".to_string(), //! dsc: "test".to_string(),
//! val: num.to_json(), //! val: num.to_json(),
//! }); //! }).unwrap();
//! println!("data: {}", data); //! println!("data: {}", data);
//! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539j"}; //! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539j"};
//! } //! }
@ -316,13 +316,13 @@ pub fn decode<T: ::Decodable>(s: &str) -> DecodeResult<T> {
} }
/// Shortcut function to encode a `T` into a JSON `String` /// Shortcut function to encode a `T` into a JSON `String`
pub fn encode<T: ::Encodable>(object: &T) -> string::String { pub fn encode<T: ::Encodable>(object: &T) -> Result<string::String, EncoderError> {
let mut s = String::new(); let mut s = String::new();
{ {
let mut encoder = Encoder::new(&mut s); let mut encoder = Encoder::new(&mut s);
let _ = object.encode(&mut encoder); try!(object.encode(&mut encoder));
} }
s Ok(s)
} }
impl fmt::Display for ErrorCode { impl fmt::Display for ErrorCode {
@ -536,7 +536,6 @@ impl<'a> ::Encoder for Encoder<'a> {
fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult, F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{ {
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
f(self) f(self)
} }
@ -550,10 +549,10 @@ impl<'a> ::Encoder for Encoder<'a> {
// enums are encoded as strings or objects // enums are encoded as strings or objects
// Bunny => "Bunny" // Bunny => "Bunny"
// Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]} // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if cnt == 0 { if cnt == 0 {
escape_str(self.writer, name) escape_str(self.writer, name)
} else { } else {
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
try!(write!(self.writer, "{{\"variant\":")); try!(write!(self.writer, "{{\"variant\":"));
try!(escape_str(self.writer, name)); try!(escape_str(self.writer, name));
try!(write!(self.writer, ",\"fields\":[")); try!(write!(self.writer, ",\"fields\":["));
@ -785,7 +784,6 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{ {
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
f(self) f(self)
} }
@ -797,10 +795,10 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
-> EncodeResult where -> EncodeResult where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{ {
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if cnt == 0 { if cnt == 0 {
escape_str(self.writer, name) escape_str(self.writer, name)
} else { } else {
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
try!(write!(self.writer, "{{\n")); try!(write!(self.writer, "{{\n"));
self.curr_indent += self.indent; self.curr_indent += self.indent;
try!(spaces(self.writer, self.curr_indent)); try!(spaces(self.writer, self.curr_indent));
@ -3537,6 +3535,24 @@ mod tests {
} }
} }
#[test]
fn test_hashmap_with_enum_key() {
use std::collections::HashMap;
use json;
#[derive(RustcEncodable, Eq, Hash, PartialEq, RustcDecodable, Show)]
enum Enum {
Foo,
#[allow(dead_code)]
Bar,
}
let mut map = HashMap::new();
map.insert(Enum::Foo, 0);
let result = json::encode(&map).unwrap();
assert_eq!(&result[], r#"{"Foo":0}"#);
let decoded: HashMap<Enum, _> = json::decode(result.as_slice()).unwrap();
assert_eq!(map, decoded);
}
#[test] #[test]
fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() { fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
use std::collections::HashMap; use std::collections::HashMap;

View file

@ -854,7 +854,7 @@ mod test {
#[test] #[test]
fn string_to_tts_1 () { fn string_to_tts_1 () {
let tts = string_to_tts("fn a (b : i32) { b; }".to_string()); let tts = string_to_tts("fn a (b : i32) { b; }".to_string());
assert_eq!(json::encode(&tts), assert_eq!(json::encode(&tts).unwrap(),
"[\ "[\
{\ {\
\"variant\":\"TtToken\",\ \"variant\":\"TtToken\",\

View file

@ -24,7 +24,7 @@ struct A {
fn main() { fn main() {
let obj = A { foo: box [true, false] }; let obj = A { foo: box [true, false] };
let s = json::encode(&obj); let s = json::encode(&obj).unwrap();
let obj2: A = json::decode(s.as_slice()).unwrap(); let obj2: A = json::decode(s.as_slice()).unwrap();
assert!(obj.foo == obj2.foo); assert!(obj.foo == obj2.foo);
} }

View file

@ -35,7 +35,7 @@ fn main() {
foo: Cell::new(true), foo: Cell::new(true),
bar: RefCell::new( A { baz: 2 } ) bar: RefCell::new( A { baz: 2 } )
}; };
let s = json::encode(&obj); let s = json::encode(&obj).unwrap();
let obj2: B = json::decode(s.as_slice()).unwrap(); let obj2: B = json::decode(s.as_slice()).unwrap();
assert!(obj.foo.get() == obj2.foo.get()); assert!(obj.foo.get() == obj2.foo.get());
assert!(obj.bar.borrow().baz == obj2.bar.borrow().baz); assert!(obj.bar.borrow().baz == obj2.bar.borrow().baz);

View file

@ -20,7 +20,7 @@ struct UnitLikeStruct;
pub fn main() { pub fn main() {
let obj = UnitLikeStruct; let obj = UnitLikeStruct;
let json_str: String = json::encode(&obj); let json_str: String = json::encode(&obj).unwrap();
let json_object = json::from_str(json_str.as_slice()); let json_object = json::from_str(json_str.as_slice());
let mut decoder = json::Decoder::new(json_object.unwrap()); let mut decoder = json::Decoder::new(json_object.unwrap());