]> git.lizzy.rs Git - rust.git/commitdiff
don't ignore errors in encode and allow hashmaps with enum keys
authorOliver Schneider <git1984941651981@oli-obk.de>
Fri, 23 Jan 2015 09:52:58 +0000 (10:52 +0100)
committerOliver Schneider <git1984941651981@oli-obk.de>
Mon, 26 Jan 2015 15:27:28 +0000 (16:27 +0100)
closes #21470 on main rust repository
was fixed on rust-lang/rustc-serialize (see https://github.com/rust-lang/rustc-serialize/pull/32)

src/libserialize/json.rs

index 5f4ba8ef9fcc743393f4f0ad3077dd19b50c0482..d86bf8e48716fb6613b26e4f6a3fe7e27bb735e4 100644 (file)
@@ -97,7 +97,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();
 //!         uid: 1,
 //!         dsc: "test".to_string(),
 //!         val: num.to_json(),
-//!     });
+//!     }).unwrap();
 //!     println!("data: {}", data);
 //!     // 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`
-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::Display for ErrorCode {
@@ -536,7 +536,6 @@ fn emit_str(&mut self, v: &str) -> EncodeResult {
     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)
     }
 
@@ -550,10 +549,10 @@ fn emit_enum_variant<F>(&mut self,
         // 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\":["));
@@ -785,7 +784,6 @@ fn emit_str(&mut self, v: &str) -> EncodeResult {
     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)
     }
 
@@ -797,10 +795,10 @@ fn emit_enum_variant<F>(&mut self,
                             -> 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));
@@ -3537,6 +3535,24 @@ fn indents(source: &str) -> uint {
         }
     }
 
+    #[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_can_handle_double_quote_delimited_key() {
         use std::collections::HashMap;