Skip to content
This repository was archived by the owner on Dec 1, 2023. It is now read-only.

Allow enum variant as hashmap key #32

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 25 additions & 9 deletions src/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@
//! };
//!
//! // Serialize using `json::encode`
//! let encoded = json::encode(&object);
//! let encoded = json::encode(&object).unwrap();
//!
//! // Deserialize using `json::decode`
//! let decoded: TestStruct = json::decode(encoded.as_slice()).unwrap();
Expand Down Expand Up @@ -151,7 +151,7 @@
//! uid: 1,
//! dsc: "test".to_string(),
//! val: num.to_json(),
//! });
//! }).unwrap();
//! println!("data: {}", data);
//! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539j"};
//! }
Expand Down Expand Up @@ -324,13 +324,13 @@ pub fn decode<T: ::Decodable>(s: &str) -> DecodeResult<T> {
}

/// 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 encoder = Encoder::new(&mut s);
let _ = object.encode(&mut encoder);
try!(object.encode(&mut encoder));
}
s
Ok(s)
}

impl fmt::Show for ErrorCode {
Expand Down Expand Up @@ -538,7 +538,6 @@ impl<'a> ::Encoder for Encoder<'a> {
fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
f(self)
}

Expand All @@ -552,10 +551,10 @@ impl<'a> ::Encoder for Encoder<'a> {
// enums are encoded as strings or objects
// Bunny => "Bunny"
// Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if cnt == 0 {
escape_str(self.writer, name)
} else {
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
try!(write!(self.writer, "{{\"variant\":"));
try!(escape_str(self.writer, name));
try!(write!(self.writer, ",\"fields\":["));
Expand Down Expand Up @@ -787,7 +786,6 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
f(self)
}

Expand All @@ -799,10 +797,10 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
-> EncodeResult where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if cnt == 0 {
escape_str(self.writer, name)
} else {
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
try!(write!(self.writer, "{{\n"));
self.curr_indent += self.indent;
try!(spaces(self.writer, self.curr_indent));
Expand Down Expand Up @@ -3552,6 +3550,24 @@ mod tests {
let _hm: HashMap<usize, bool> = Decodable::decode(&mut decoder).unwrap();
}

#[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]
fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
use std::collections::HashMap;
Expand Down