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

don't ignore encoder failures in json::encode #31

Merged
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
30 changes: 25 additions & 5 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 @@ -3552,6 +3552,26 @@ 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)]
enum Enum {
Foo,
#[allow(dead_code)]
Bar,
}
let mut map = HashMap::new();
map.insert(Enum::Foo, 0);
let result = json::encode(&map);
match result.unwrap_err() {
EncoderError::BadHashmapKey => (),
_ => panic!("expected bad hash map key")
}
//assert_eq!(&enc[], r#"{"Foo": 0}"#);
}

#[test]
fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
use std::collections::HashMap;
Expand Down