Skip to content

Commit 85b80aa

Browse files
author
Oliver Schneider
committed
don't ignore errors in encode and allow hashmaps with enum keys
closes #21470 on main rust repository was fixed on rust-lang/rustc-serialize (see rust-lang-deprecated/rustc-serialize#32)
1 parent 59dcba5 commit 85b80aa

File tree

1 file changed

+25
-9
lines changed

1 file changed

+25
-9
lines changed

src/libserialize/json.rs

+25-9
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@
9797
//! };
9898
//!
9999
//! // Serialize using `json::encode`
100-
//! let encoded = json::encode(&object);
100+
//! let encoded = json::encode(&object).unwrap();
101101
//!
102102
//! // Deserialize using `json::decode`
103103
//! let decoded: TestStruct = json::decode(encoded.as_slice()).unwrap();
@@ -143,7 +143,7 @@
143143
//! uid: 1,
144144
//! dsc: "test".to_string(),
145145
//! val: num.to_json(),
146-
//! });
146+
//! }).unwrap();
147147
//! println!("data: {}", data);
148148
//! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539j"};
149149
//! }
@@ -316,13 +316,13 @@ pub fn decode<T: ::Decodable>(s: &str) -> DecodeResult<T> {
316316
}
317317

318318
/// Shortcut function to encode a `T` into a JSON `String`
319-
pub fn encode<T: ::Encodable>(object: &T) -> string::String {
319+
pub fn encode<T: ::Encodable>(object: &T) -> Result<string::String, EncoderError> {
320320
let mut s = String::new();
321321
{
322322
let mut encoder = Encoder::new(&mut s);
323-
let _ = object.encode(&mut encoder);
323+
try!(object.encode(&mut encoder));
324324
}
325-
s
325+
Ok(s)
326326
}
327327

328328
impl fmt::Display for ErrorCode {
@@ -536,7 +536,6 @@ impl<'a> ::Encoder for Encoder<'a> {
536536
fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
537537
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
538538
{
539-
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
540539
f(self)
541540
}
542541

@@ -550,10 +549,10 @@ impl<'a> ::Encoder for Encoder<'a> {
550549
// enums are encoded as strings or objects
551550
// Bunny => "Bunny"
552551
// Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
553-
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
554552
if cnt == 0 {
555553
escape_str(self.writer, name)
556554
} else {
555+
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
557556
try!(write!(self.writer, "{{\"variant\":"));
558557
try!(escape_str(self.writer, name));
559558
try!(write!(self.writer, ",\"fields\":["));
@@ -785,7 +784,6 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
785784
fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
786785
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
787786
{
788-
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
789787
f(self)
790788
}
791789

@@ -797,10 +795,10 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
797795
-> EncodeResult where
798796
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
799797
{
800-
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
801798
if cnt == 0 {
802799
escape_str(self.writer, name)
803800
} else {
801+
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
804802
try!(write!(self.writer, "{{\n"));
805803
self.curr_indent += self.indent;
806804
try!(spaces(self.writer, self.curr_indent));
@@ -3537,6 +3535,24 @@ mod tests {
35373535
}
35383536
}
35393537

3538+
#[test]
3539+
fn test_hashmap_with_enum_key() {
3540+
use std::collections::HashMap;
3541+
use json;
3542+
#[derive(RustcEncodable, Eq, Hash, PartialEq, RustcDecodable, Show)]
3543+
enum Enum {
3544+
Foo,
3545+
#[allow(dead_code)]
3546+
Bar,
3547+
}
3548+
let mut map = HashMap::new();
3549+
map.insert(Enum::Foo, 0);
3550+
let result = json::encode(&map).unwrap();
3551+
assert_eq!(&result[], r#"{"Foo":0}"#);
3552+
let decoded: HashMap<Enum, _> = json::decode(result.as_slice()).unwrap();
3553+
assert_eq!(map, decoded);
3554+
}
3555+
35403556
#[test]
35413557
fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
35423558
use std::collections::HashMap;

0 commit comments

Comments
 (0)