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

Commit c9e1df1

Browse files
committed
Merge pull request #31 from oli-obk/dont_ignore_enc_fail
don't ignore encoder failures in json::encode
2 parents 1b97923 + c35ef51 commit c9e1df1

File tree

1 file changed

+25
-5
lines changed

1 file changed

+25
-5
lines changed

src/json.rs

+25-5
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@
105105
//! };
106106
//!
107107
//! // Serialize using `json::encode`
108-
//! let encoded = json::encode(&object);
108+
//! let encoded = json::encode(&object).unwrap();
109109
//!
110110
//! // Deserialize using `json::decode`
111111
//! let decoded: TestStruct = json::decode(encoded.as_slice()).unwrap();
@@ -151,7 +151,7 @@
151151
//! uid: 1,
152152
//! dsc: "test".to_string(),
153153
//! val: num.to_json(),
154-
//! });
154+
//! }).unwrap();
155155
//! println!("data: {}", data);
156156
//! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539j"};
157157
//! }
@@ -324,13 +324,13 @@ pub fn decode<T: ::Decodable>(s: &str) -> DecodeResult<T> {
324324
}
325325

326326
/// Shortcut function to encode a `T` into a JSON `String`
327-
pub fn encode<T: ::Encodable>(object: &T) -> string::String {
327+
pub fn encode<T: ::Encodable>(object: &T) -> Result<string::String, EncoderError> {
328328
let mut s = String::new();
329329
{
330330
let mut encoder = Encoder::new(&mut s);
331-
let _ = object.encode(&mut encoder);
331+
try!(object.encode(&mut encoder));
332332
}
333-
s
333+
Ok(s)
334334
}
335335

336336
impl fmt::Show for ErrorCode {
@@ -3552,6 +3552,26 @@ mod tests {
35523552
let _hm: HashMap<usize, bool> = Decodable::decode(&mut decoder).unwrap();
35533553
}
35543554

3555+
#[test]
3556+
fn test_hashmap_with_enum_key() {
3557+
use std::collections::HashMap;
3558+
use json;
3559+
#[derive(RustcEncodable, Eq, Hash, PartialEq)]
3560+
enum Enum {
3561+
Foo,
3562+
#[allow(dead_code)]
3563+
Bar,
3564+
}
3565+
let mut map = HashMap::new();
3566+
map.insert(Enum::Foo, 0);
3567+
let result = json::encode(&map);
3568+
match result.unwrap_err() {
3569+
EncoderError::BadHashmapKey => (),
3570+
_ => panic!("expected bad hash map key")
3571+
}
3572+
//assert_eq!(&enc[], r#"{"Foo": 0}"#);
3573+
}
3574+
35553575
#[test]
35563576
fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
35573577
use std::collections::HashMap;

0 commit comments

Comments
 (0)