version
stringclasses 2
values | instance_id
stringlengths 17
19
| pull_number
int64 31
1.18k
| issue_numbers
listlengths 1
2
| created_at
stringlengths 20
20
| hints_text
stringlengths 0
3.56k
| base_commit
stringlengths 40
40
| problem_statement
stringlengths 94
8.7k
| patch
stringlengths 441
52k
| test_patch
stringlengths 298
13k
| repo
stringclasses 1
value | environment_setup_commit
stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
1.0
|
serde-rs__json-1175
| 1,175
|
[
"877"
] |
2024-08-12T18:26:05Z
|
@dtolnay Have you had a chance to look into this? It'd be great to get your review.
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
Deserialize invalid UTF-8 into byte bufs as WTF-8
Previously #828 added support for deserializing lone leading and
trailing surrogates into WTF-8 encoded bytes when deserializing a string
as bytes. This commit extends this to cover the case of a leading
surrogate followed by code units that are not trailing surrogates. This
allows for deserialization of "\ud83c\ud83c" (two leading surrogates),
or "\ud83c\u0061" (a leading surrogate followed by "a").
The docs also now make it clear that we are serializing the invalid code
points as WTF-8. This reference to WTF-8 signals to the user that they
can use a WTF-8 parser on the bytes to construct a valid UTF-8 string.
Follow up to https://github.com/serde-rs/json/pull/830#pullrequestreview-880820431.
|
diff --git a/src/de.rs b/src/de.rs
index bfde371a1..bd6f2e50c 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -1575,7 +1575,10 @@ impl<'de, 'a, R: Read<'de>> de::Deserializer<'de> for &'a mut Deserializer<R> {
///
/// The behavior of serde_json is specified to fail on non-UTF-8 strings
/// when deserializing into Rust UTF-8 string types such as String, and
- /// succeed with non-UTF-8 bytes when deserializing using this method.
+ /// succeed with the bytes representing the [WTF-8] encoding of code points
+ /// when deserializing using this method.
+ ///
+ /// [WTF-8]: https://simonsapin.github.io/wtf-8
///
/// Escape sequences are processed as usual, and for `\uXXXX` escapes it is
/// still checked if the hex number represents a valid Unicode code point.
diff --git a/src/read.rs b/src/read.rs
index 6c663768e..9e8ffaacf 100644
--- a/src/read.rs
+++ b/src/read.rs
@@ -1,6 +1,5 @@
use crate::error::{Error, ErrorCode, Result};
use alloc::vec::Vec;
-use core::char;
use core::cmp;
use core::mem;
use core::ops::Deref;
@@ -882,88 +881,133 @@ fn parse_escape<'de, R: Read<'de>>(
b'n' => scratch.push(b'\n'),
b'r' => scratch.push(b'\r'),
b't' => scratch.push(b'\t'),
- b'u' => {
- fn encode_surrogate(scratch: &mut Vec<u8>, n: u16) {
- scratch.extend_from_slice(&[
- (n >> 12 & 0b0000_1111) as u8 | 0b1110_0000,
- (n >> 6 & 0b0011_1111) as u8 | 0b1000_0000,
- (n & 0b0011_1111) as u8 | 0b1000_0000,
- ]);
- }
+ b'u' => return parse_unicode_escape(read, validate, scratch),
+ _ => {
+ return error(read, ErrorCode::InvalidEscape);
+ }
+ }
- let c = match tri!(read.decode_hex_escape()) {
- n @ 0xDC00..=0xDFFF => {
- return if validate {
- error(read, ErrorCode::LoneLeadingSurrogateInHexEscape)
- } else {
- encode_surrogate(scratch, n);
- Ok(())
- };
- }
+ Ok(())
+}
- // Non-BMP characters are encoded as a sequence of two hex
- // escapes, representing UTF-16 surrogates. If deserializing a
- // utf-8 string the surrogates are required to be paired,
- // whereas deserializing a byte string accepts lone surrogates.
- n1 @ 0xD800..=0xDBFF => {
- if tri!(peek_or_eof(read)) == b'\\' {
- read.discard();
- } else {
- return if validate {
- read.discard();
- error(read, ErrorCode::UnexpectedEndOfHexEscape)
- } else {
- encode_surrogate(scratch, n1);
- Ok(())
- };
- }
+/// Parses a JSON \u escape and appends it into the scratch space. Assumes \u
+/// has just been read.
+#[cold]
+fn parse_unicode_escape<'de, R: Read<'de>>(
+ read: &mut R,
+ validate: bool,
+ scratch: &mut Vec<u8>,
+) -> Result<()> {
+ let mut n = tri!(read.decode_hex_escape());
+
+ // Non-BMP characters are encoded as a sequence of two hex
+ // escapes, representing UTF-16 surrogates. If deserializing a
+ // utf-8 string the surrogates are required to be paired,
+ // whereas deserializing a byte string accepts lone surrogates.
+ if validate && n >= 0xDC00 && n <= 0xDFFF {
+ // XXX: This is actually a trailing surrogate.
+ return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape);
+ }
+
+ loop {
+ if n < 0xD800 || n > 0xDBFF {
+ // Every u16 outside of the surrogate ranges is guaranteed to be a
+ // legal char.
+ push_wtf8_codepoint(n as u32, scratch);
+ return Ok(());
+ }
- if tri!(peek_or_eof(read)) == b'u' {
- read.discard();
- } else {
- return if validate {
- read.discard();
- error(read, ErrorCode::UnexpectedEndOfHexEscape)
- } else {
- encode_surrogate(scratch, n1);
- // The \ prior to this byte started an escape sequence,
- // so we need to parse that now. This recursive call
- // does not blow the stack on malicious input because
- // the escape is not \u, so it will be handled by one
- // of the easy nonrecursive cases.
- parse_escape(read, validate, scratch)
- };
- }
+ // n is a leading surrogate, we now expect a trailing surrogate.
+ let n1 = n;
- let n2 = tri!(read.decode_hex_escape());
+ if tri!(peek_or_eof(read)) == b'\\' {
+ read.discard();
+ } else {
+ return if validate {
+ read.discard();
+ error(read, ErrorCode::UnexpectedEndOfHexEscape)
+ } else {
+ push_wtf8_codepoint(n1 as u32, scratch);
+ Ok(())
+ };
+ }
- if n2 < 0xDC00 || n2 > 0xDFFF {
- return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape);
- }
+ if tri!(peek_or_eof(read)) == b'u' {
+ read.discard();
+ } else {
+ return if validate {
+ read.discard();
+ error(read, ErrorCode::UnexpectedEndOfHexEscape)
+ } else {
+ push_wtf8_codepoint(n1 as u32, scratch);
+ // The \ prior to this byte started an escape sequence,
+ // so we need to parse that now. This recursive call
+ // does not blow the stack on malicious input because
+ // the escape is not \u, so it will be handled by one
+ // of the easy nonrecursive cases.
+ parse_escape(read, validate, scratch)
+ };
+ }
- let n = (((n1 - 0xD800) as u32) << 10 | (n2 - 0xDC00) as u32) + 0x1_0000;
+ let n2 = tri!(read.decode_hex_escape());
- match char::from_u32(n) {
- Some(c) => c,
- None => {
- return error(read, ErrorCode::InvalidUnicodeCodePoint);
- }
- }
- }
+ if n2 < 0xDC00 || n2 > 0xDFFF {
+ if validate {
+ return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape);
+ }
+ push_wtf8_codepoint(n1 as u32, scratch);
+ // If n2 is a leading surrogate, we need to restart.
+ n = n2;
+ continue;
+ }
- // Every u16 outside of the surrogate ranges above is guaranteed
- // to be a legal char.
- n => char::from_u32(n as u32).unwrap(),
- };
+ // This value is in range U+10000..=U+10FFFF, which is always a
+ // valid codepoint.
+ let n = (((n1 - 0xD800) as u32) << 10 | (n2 - 0xDC00) as u32) + 0x1_0000;
+ push_wtf8_codepoint(n, scratch);
+ return Ok(());
+ }
+}
- scratch.extend_from_slice(c.encode_utf8(&mut [0_u8; 4]).as_bytes());
- }
- _ => {
- return error(read, ErrorCode::InvalidEscape);
- }
+/// Adds a WTF-8 codepoint to the end of the buffer. This is a more efficient
+/// implementation of String::push. The codepoint may be a surrogate.
+#[inline]
+fn push_wtf8_codepoint(n: u32, scratch: &mut Vec<u8>) {
+ if n < 0x80 {
+ scratch.push(n as u8);
+ return;
}
- Ok(())
+ scratch.reserve(4);
+
+ unsafe {
+ let ptr = scratch.as_mut_ptr().add(scratch.len());
+
+ let encoded_len = match n {
+ 0..=0x7F => unreachable!(),
+ 0x80..=0x7FF => {
+ ptr.write((n >> 6 & 0b0001_1111) as u8 | 0b1100_0000);
+ 2
+ }
+ 0x800..=0xFFFF => {
+ ptr.write((n >> 12 & 0b0000_1111) as u8 | 0b1110_0000);
+ ptr.add(1).write((n >> 6 & 0b0011_1111) as u8 | 0b1000_0000);
+ 3
+ }
+ 0x1_0000..=0x10_FFFF => {
+ ptr.write((n >> 18 & 0b0000_0111) as u8 | 0b1111_0000);
+ ptr.add(1)
+ .write((n >> 12 & 0b0011_1111) as u8 | 0b1000_0000);
+ ptr.add(2).write((n >> 6 & 0b0011_1111) as u8 | 0b1000_0000);
+ 4
+ }
+ 0x11_0000.. => unreachable!(),
+ };
+ ptr.add(encoded_len - 1)
+ .write((n & 0b0011_1111) as u8 | 0b1000_0000);
+
+ scratch.set_len(scratch.len() + encoded_len);
+ }
}
/// Parses a JSON escape sequence and discards the value. Assumes the previous
|
diff --git a/tests/test.rs b/tests/test.rs
index 9f2159513..4290cb3ef 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -1707,7 +1707,7 @@ fn test_byte_buf_de() {
}
#[test]
-fn test_byte_buf_de_lone_surrogate() {
+fn test_byte_buf_de_invalid_surrogates() {
let bytes = ByteBuf::from(vec![237, 160, 188]);
let v: ByteBuf = from_str(r#""\ud83c""#).unwrap();
assert_eq!(v, bytes);
@@ -1720,23 +1720,54 @@ fn test_byte_buf_de_lone_surrogate() {
let v: ByteBuf = from_str(r#""\ud83c ""#).unwrap();
assert_eq!(v, bytes);
- let bytes = ByteBuf::from(vec![237, 176, 129]);
- let v: ByteBuf = from_str(r#""\udc01""#).unwrap();
- assert_eq!(v, bytes);
-
let res = from_str::<ByteBuf>(r#""\ud83c\!""#);
assert!(res.is_err());
let res = from_str::<ByteBuf>(r#""\ud83c\u""#);
assert!(res.is_err());
- let res = from_str::<ByteBuf>(r#""\ud83c\ud83c""#);
- assert!(res.is_err());
+ // lone trailing surrogate
+ let bytes = ByteBuf::from(vec![237, 176, 129]);
+ let v: ByteBuf = from_str(r#""\udc01""#).unwrap();
+ assert_eq!(v, bytes);
+
+ // leading surrogate followed by other leading surrogate
+ let bytes = ByteBuf::from(vec![237, 160, 188, 237, 160, 188]);
+ let v: ByteBuf = from_str(r#""\ud83c\ud83c""#).unwrap();
+ assert_eq!(v, bytes);
+
+ // leading surrogate followed by "a" (U+0061) in \u encoding
+ let bytes = ByteBuf::from(vec![237, 160, 188, 97]);
+ let v: ByteBuf = from_str(r#""\ud83c\u0061""#).unwrap();
+ assert_eq!(v, bytes);
+
+ // leading surrogate followed by U+0080
+ let bytes = ByteBuf::from(vec![237, 160, 188, 194, 128]);
+ let v: ByteBuf = from_str(r#""\ud83c\u0080""#).unwrap();
+ assert_eq!(v, bytes);
+
+ // leading surrogate followed by U+FFFF
+ let bytes = ByteBuf::from(vec![237, 160, 188, 239, 191, 191]);
+ let v: ByteBuf = from_str(r#""\ud83c\uffff""#).unwrap();
+ assert_eq!(v, bytes);
+}
+
+#[test]
+fn test_byte_buf_de_surrogate_pair() {
+ // leading surrogate followed by trailing surrogate
+ let bytes = ByteBuf::from(vec![240, 159, 128, 128]);
+ let v: ByteBuf = from_str(r#""\ud83c\udc00""#).unwrap();
+ assert_eq!(v, bytes);
+
+ // leading surrogate followed by a surrogate pair
+ let bytes = ByteBuf::from(vec![237, 160, 188, 240, 159, 128, 128]);
+ let v: ByteBuf = from_str(r#""\ud83c\ud83c\udc00""#).unwrap();
+ assert_eq!(v, bytes);
}
#[cfg(feature = "raw_value")]
#[test]
-fn test_raw_de_lone_surrogate() {
+fn test_raw_de_invalid_surrogates() {
use serde_json::value::RawValue;
assert!(from_str::<Box<RawValue>>(r#""\ud83c""#).is_ok());
@@ -1746,6 +1777,17 @@ fn test_raw_de_lone_surrogate() {
assert!(from_str::<Box<RawValue>>(r#""\udc01\!""#).is_err());
assert!(from_str::<Box<RawValue>>(r#""\udc01\u""#).is_err());
assert!(from_str::<Box<RawValue>>(r#""\ud83c\ud83c""#).is_ok());
+ assert!(from_str::<Box<RawValue>>(r#""\ud83c\u0061""#).is_ok());
+ assert!(from_str::<Box<RawValue>>(r#""\ud83c\u0080""#).is_ok());
+ assert!(from_str::<Box<RawValue>>(r#""\ud83c\uffff""#).is_ok());
+}
+
+#[cfg(feature = "raw_value")]
+#[test]
+fn test_raw_de_surrogate_pair() {
+ use serde_json::value::RawValue;
+
+ assert!(from_str::<Box<RawValue>>(r#""\ud83c\udc00""#).is_ok());
}
#[test]
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
1.0
|
serde-rs__json-1055
| 1,055
|
[
"1054"
] |
2023-08-15T21:59:39Z
|
8652bf2bc5dac3b5496725452cfe14ca573f6232
|
Cannot deserialize to `HashMap<bool, _>`
JSON objects can only have string keys, although `HashMap`s can have many types of keys. In the case of `i32` keys (eg `HashMap<i32, i32>`), serde_json coerces the stringified integer key (eg `"1"`) into `1i32`. However, that fails in the case of `bool` keys; it raises an error when trying to coerce `"true"` or `"false"` into `true` or `false`:
```
Error("invalid type: string \"false\", expected a boolean", line: 0, column: 0)
```
I'm assuming the coercion behavior in the `bool` case should be similar to the `i32` case.
Playground reproduction is here: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=92d5a43496299513df591ec5a6f2832c
|
diff --git a/src/de.rs b/src/de.rs
index 7aad50b96..9975b40a5 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -2203,6 +2203,41 @@ where
deserialize_numeric_key!(deserialize_f32, deserialize_f32);
deserialize_numeric_key!(deserialize_f64);
+ fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
+ where
+ V: de::Visitor<'de>,
+ {
+ self.de.eat_char();
+
+ let peek = match tri!(self.de.next_char()) {
+ Some(b) => b,
+ None => {
+ return Err(self.de.peek_error(ErrorCode::EofWhileParsingValue));
+ }
+ };
+
+ let value = match peek {
+ b't' => {
+ tri!(self.de.parse_ident(b"rue\""));
+ visitor.visit_bool(true)
+ }
+ b'f' => {
+ tri!(self.de.parse_ident(b"alse\""));
+ visitor.visit_bool(false)
+ }
+ _ => {
+ self.de.scratch.clear();
+ let s = tri!(self.de.read.parse_str(&mut self.de.scratch));
+ Err(de::Error::invalid_type(Unexpected::Str(&s), &visitor))
+ }
+ };
+
+ match value {
+ Ok(value) => Ok(value),
+ Err(err) => Err(self.de.fix_position(err)),
+ }
+ }
+
#[inline]
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
where
@@ -2258,7 +2293,7 @@ where
}
forward_to_deserialize_any! {
- bool char str string unit unit_struct seq tuple tuple_struct map struct
+ char str string unit unit_struct seq tuple tuple_struct map struct
identifier ignored_any
}
}
diff --git a/src/ser.rs b/src/ser.rs
index 6bb6fd761..3742e0bef 100644
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -827,8 +827,21 @@ where
type SerializeStruct = Impossible<(), Error>;
type SerializeStructVariant = Impossible<(), Error>;
- fn serialize_bool(self, _value: bool) -> Result<()> {
- Err(key_must_be_a_string())
+ fn serialize_bool(self, value: bool) -> Result<()> {
+ tri!(self
+ .ser
+ .formatter
+ .begin_string(&mut self.ser.writer)
+ .map_err(Error::io));
+ tri!(self
+ .ser
+ .formatter
+ .write_bool(&mut self.ser.writer, value)
+ .map_err(Error::io));
+ self.ser
+ .formatter
+ .end_string(&mut self.ser.writer)
+ .map_err(Error::io)
}
fn serialize_i8(self, value: i8) -> Result<()> {
diff --git a/src/value/de.rs b/src/value/de.rs
index 2090dd009..1e8b5acbb 100644
--- a/src/value/de.rs
+++ b/src/value/de.rs
@@ -1183,6 +1183,22 @@ impl<'de> serde::Deserializer<'de> for MapKeyDeserializer<'de> {
deserialize_numeric_key!(deserialize_i128, do_deserialize_i128);
deserialize_numeric_key!(deserialize_u128, do_deserialize_u128);
+ fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Error>
+ where
+ V: Visitor<'de>,
+ {
+ if self.key == "true" {
+ visitor.visit_bool(true)
+ } else if self.key == "false" {
+ visitor.visit_bool(false)
+ } else {
+ Err(serde::de::Error::invalid_type(
+ Unexpected::Str(&self.key),
+ &visitor,
+ ))
+ }
+ }
+
#[inline]
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
where
@@ -1219,8 +1235,8 @@ impl<'de> serde::Deserializer<'de> for MapKeyDeserializer<'de> {
}
forward_to_deserialize_any! {
- bool char str string bytes byte_buf unit unit_struct seq tuple
- tuple_struct map struct identifier ignored_any
+ char str string bytes byte_buf unit unit_struct seq tuple tuple_struct
+ map struct identifier ignored_any
}
}
diff --git a/src/value/ser.rs b/src/value/ser.rs
index 6ca53d4c5..835fa9080 100644
--- a/src/value/ser.rs
+++ b/src/value/ser.rs
@@ -483,8 +483,8 @@ impl serde::Serializer for MapKeySerializer {
value.serialize(self)
}
- fn serialize_bool(self, _value: bool) -> Result<String> {
- Err(key_must_be_a_string())
+ fn serialize_bool(self, value: bool) -> Result<String> {
+ Ok(value.to_string())
}
fn serialize_i8(self, value: i8) -> Result<String> {
|
diff --git a/tests/test.rs b/tests/test.rs
index 8d9a5942a..e548b7dae 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -1654,17 +1654,6 @@ fn test_deserialize_from_stream() {
assert_eq!(request, response);
}
-#[test]
-fn test_serialize_rejects_bool_keys() {
- let map = treemap!(
- true => 2,
- false => 4,
- );
-
- let err = to_vec(&map).unwrap_err();
- assert_eq!(err.to_string(), "key must be a string");
-}
-
#[test]
fn test_serialize_rejects_adt_keys() {
let map = treemap!(
@@ -2018,6 +2007,14 @@ fn test_deny_non_finite_f64_key() {
assert!(serde_json::to_value(map).is_err());
}
+#[test]
+fn test_boolean_key() {
+ let map = treemap!(false => 0, true => 1);
+ let j = r#"{"false":0,"true":1}"#;
+ test_encode_ok(&[(&map, j)]);
+ test_parse_ok(vec![(j, map)]);
+}
+
#[test]
fn test_borrowed_key() {
let map: BTreeMap<&str, ()> = from_str("{\"borrowed\":null}").unwrap();
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
|
1.0
|
serde-rs__json-1045
| 1,045
|
[
"423"
] |
2023-07-26T19:15:09Z
|
8f90eacf6c6335fbd925b1d663e46f4a7592ebba
|
Implement IntoDeserializer for Value and &Value
An `IntoDeserializer` impl would provide a way to deserialize from these types while constructing exactly the right error type on failure, rather than constructing a `serde_json::Error` and mapping it to a custom error of the target type through its `Display` impl.
```rust
fn f<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
T: Deserialize<'de>,
D: Deserializer<'de>,
{
let mut v = Value::deserialize(deserializer)?;
/* some manipulation of v */
T::deserialize(v).map_err(serde::de::Error::custom)
}
```
```diff
- T::deserialize(v).map_err(serde::de::Error::custom)
+ T::deserialize(v.into_deserializer())
```
|
diff --git a/src/value/de.rs b/src/value/de.rs
index 3f14abb3b..2090dd009 100644
--- a/src/value/de.rs
+++ b/src/value/de.rs
@@ -482,6 +482,14 @@ impl<'de> IntoDeserializer<'de, Error> for Value {
}
}
+impl<'de> IntoDeserializer<'de, Error> for &'de Value {
+ type Deserializer = Self;
+
+ fn into_deserializer(self) -> Self::Deserializer {
+ self
+ }
+}
+
struct VariantDeserializer {
value: Option<Value>,
}
|
diff --git a/tests/test.rs b/tests/test.rs
index acf5de480..8d9a5942a 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -2472,6 +2472,12 @@ fn test_value_into_deserializer() {
let mut map = BTreeMap::new();
map.insert("inner", json!({ "string": "Hello World" }));
+ let outer = Outer::deserialize(serde::de::value::MapDeserializer::new(
+ map.iter().map(|(k, v)| (*k, v)),
+ ))
+ .unwrap();
+ assert_eq!(outer.inner.string, "Hello World");
+
let outer = Outer::deserialize(map.into_deserializer()).unwrap();
assert_eq!(outer.inner.string, "Hello World");
}
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
|
1.0
|
serde-rs__json-1005
| 1,005
|
[
"1004"
] |
2023-03-27T16:41:41Z
|
02e583360db1a4aa7d21db911a9b62f34161c386
|
`Number` loses precision on f32s
Hi there, I've gone through a couple of issues but haven't found anything that quite matches my problem, so if this is a duplicate, feel free to close this and direct me elsewhere :)
The following small snippet replicates my issue:
```rs
use serde::{Deserialize, Serialize};
use serde_json;
#[derive(Deserialize, Serialize, Debug, Clone)]
struct Test(f32);
fn main() {
let a = Test(5.55);
let value = serde_json::to_value(a.clone()).unwrap();
println!("{value:?}");
let serialized = serde_json::to_string(&value).unwrap();
println!("{serialized}");
let serialized = serde_json::to_string(&a).unwrap();
println!("{serialized}");
}
// Number(5.550000190734863)
// 5.550000190734863
// 5.55
```
I would expect the serialized values to be identical (and serialized to 5.55), but they aren't. This happens both with and without `arbitrary_precision` and `float_roundtrip` enabled. I would've expected this to be precisely 5.55, especially with `arbitrary_precision` enabled. When changing the type to an `f64`, it works as expected.
|
diff --git a/src/number.rs b/src/number.rs
index 21a76411c..5ecbde873 100644
--- a/src/number.rs
+++ b/src/number.rs
@@ -279,6 +279,35 @@ impl Number {
}
}
+ pub(crate) fn as_f32(&self) -> Option<f32> {
+ #[cfg(not(feature = "arbitrary_precision"))]
+ match self.n {
+ N::PosInt(n) => Some(n as f32),
+ N::NegInt(n) => Some(n as f32),
+ N::Float(n) => Some(n as f32),
+ }
+ #[cfg(feature = "arbitrary_precision")]
+ self.n.parse::<f32>().ok().filter(|float| float.is_finite())
+ }
+
+ pub(crate) fn from_f32(f: f32) -> Option<Number> {
+ if f.is_finite() {
+ let n = {
+ #[cfg(not(feature = "arbitrary_precision"))]
+ {
+ N::Float(f as f64)
+ }
+ #[cfg(feature = "arbitrary_precision")]
+ {
+ ryu::Buffer::new().format_finite(f).to_owned()
+ }
+ };
+ Some(Number { n })
+ } else {
+ None
+ }
+ }
+
#[cfg(feature = "arbitrary_precision")]
/// Not public API. Only tests use this.
#[doc(hidden)]
diff --git a/src/value/from.rs b/src/value/from.rs
index c5a6a3960..462ad3f51 100644
--- a/src/value/from.rs
+++ b/src/value/from.rs
@@ -40,7 +40,7 @@ impl From<f32> for Value {
/// let x: Value = f.into();
/// ```
fn from(f: f32) -> Self {
- From::from(f as f64)
+ Number::from_f32(f).map_or(Value::Null, Value::Number)
}
}
diff --git a/src/value/partial_eq.rs b/src/value/partial_eq.rs
index b4ef84c4f..6b2e350b6 100644
--- a/src/value/partial_eq.rs
+++ b/src/value/partial_eq.rs
@@ -9,6 +9,13 @@ fn eq_u64(value: &Value, other: u64) -> bool {
value.as_u64().map_or(false, |i| i == other)
}
+fn eq_f32(value: &Value, other: f32) -> bool {
+ match value {
+ Value::Number(n) => n.as_f32().map_or(false, |i| i == other),
+ _ => false,
+ }
+}
+
fn eq_f64(value: &Value, other: f64) -> bool {
value.as_f64().map_or(false, |i| i == other)
}
@@ -90,6 +97,7 @@ macro_rules! partialeq_numeric {
partialeq_numeric! {
eq_i64[i8 i16 i32 i64 isize]
eq_u64[u8 u16 u32 u64 usize]
- eq_f64[f32 f64]
+ eq_f32[f32]
+ eq_f64[f64]
eq_bool[bool]
}
diff --git a/src/value/ser.rs b/src/value/ser.rs
index a29814e92..875d22e24 100644
--- a/src/value/ser.rs
+++ b/src/value/ser.rs
@@ -1,6 +1,5 @@
use crate::error::{Error, ErrorCode, Result};
use crate::map::Map;
-use crate::number::Number;
use crate::value::{to_value, Value};
use alloc::borrow::ToOwned;
use alloc::string::{String, ToString};
@@ -149,13 +148,13 @@ impl serde::Serializer for Serializer {
}
#[inline]
- fn serialize_f32(self, value: f32) -> Result<Value> {
- self.serialize_f64(value as f64)
+ fn serialize_f32(self, float: f32) -> Result<Value> {
+ Ok(Value::from(float))
}
#[inline]
- fn serialize_f64(self, value: f64) -> Result<Value> {
- Ok(Number::from_f64(value).map_or(Value::Null, Value::Number))
+ fn serialize_f64(self, float: f64) -> Result<Value> {
+ Ok(Value::from(float))
}
#[inline]
|
diff --git a/tests/regression/issue1004.rs b/tests/regression/issue1004.rs
new file mode 100644
index 000000000..3f5bd96aa
--- /dev/null
+++ b/tests/regression/issue1004.rs
@@ -0,0 +1,12 @@
+#![cfg(feature = "arbitrary_precision")]
+
+#[test]
+fn test() {
+ let float = 5.55f32;
+ let value = serde_json::to_value(&float).unwrap();
+ let json = serde_json::to_string(&value).unwrap();
+
+ // If the f32 were cast to f64 by Value before serialization, then this
+ // would incorrectly serialize as 5.550000190734863.
+ assert_eq!(json, "5.55");
+}
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
|
1.0
|
serde-rs__json-956
| 956
|
[
"953"
] |
2022-11-22T06:28:36Z
|
586fefb5a1e619b0f1a82d94b52ce25754b73ea0
|
Invalid JSON values are accepted: numbers with trailing dot but only if greater than u64::MAX
According to JSON spec, both of these should be errors:
```rust
fn main() {
let x1: Result<serde_json::Value, _> = serde_json::from_str("18446744073709551615.");
assert!(x1.is_err());
let x2: Result<serde_json::Value, _> = serde_json::from_str("18446744073709551616.");
assert!(x2.is_err());
}
```
[Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1d630973bd212fafadea90f3d2eabcf5)
But this is the output, as of serde_json 1.0.88:
```
thread 'main' panicked at 'assertion failed: x2.is_err()', src/main.rs:5:5
```
|
diff --git a/src/de.rs b/src/de.rs
index 378b71062..88d0f2624 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -451,30 +451,33 @@ impl<'de, R: Read<'de>> Deserializer<R> {
&mut self,
positive: bool,
mut significand: u64,
- mut exponent: i32,
+ exponent_before_decimal_point: i32,
) -> Result<f64> {
self.eat_char();
+ let mut exponent_after_decimal_point = 0;
while let c @ b'0'..=b'9' = tri!(self.peek_or_null()) {
let digit = (c - b'0') as u64;
if overflow!(significand * 10 + digit, u64::max_value()) {
+ let exponent = exponent_before_decimal_point + exponent_after_decimal_point;
return self.parse_decimal_overflow(positive, significand, exponent);
}
self.eat_char();
significand = significand * 10 + digit;
- exponent -= 1;
+ exponent_after_decimal_point -= 1;
}
// Error if there is not at least one digit after the decimal point.
- if exponent == 0 {
+ if exponent_after_decimal_point == 0 {
match tri!(self.peek()) {
Some(_) => return Err(self.peek_error(ErrorCode::InvalidNumber)),
None => return Err(self.peek_error(ErrorCode::EofWhileParsingValue)),
}
}
+ let exponent = exponent_before_decimal_point + exponent_after_decimal_point;
match tri!(self.peek_or_null()) {
b'e' | b'E' => self.parse_exponent(positive, significand, exponent),
_ => self.f64_from_parts(positive, significand, exponent),
|
diff --git a/tests/regression/issue953.rs b/tests/regression/issue953.rs
new file mode 100644
index 000000000..771aa5287
--- /dev/null
+++ b/tests/regression/issue953.rs
@@ -0,0 +1,9 @@
+use serde_json::Value;
+
+#[test]
+fn test() {
+ let x1 = serde_json::from_str::<Value>("18446744073709551615.");
+ assert!(x1.is_err());
+ let x2 = serde_json::from_str::<Value>("18446744073709551616.");
+ assert!(x2.is_err());
+}
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
|
1.0
|
serde-rs__json-848
| 848
|
[
"845"
] |
2022-01-16T00:41:56Z
|
66919777d0c31addd190c7a48ec78145a270294d
|
`arbitrary_precision` Breaks Visitors
I'm not sure if I'm doing something wrong here, but I'm trying to write a type that can deserialize from either strings or integers.
Initially I did this using an `untagged` enumeration variant to do the heavy lifting - see [here](https://github.com/influxdata/pbjson/blob/2662672c38c4fe18cd5225ea44ea3fdc08dc9b8b/pbjson/src/lib.rs#L30).
This worked fine until an upstream crate enabled the `arbitrary_precision` feature. I found https://github.com/serde-rs/json/issues/559 and https://github.com/serde-rs/serde/issues/1183 on the topic, and so opted to implement a custom visitor as these seem to suggest the issue was in the untagged variant generation.
I therefore tried using a custom visitor
```
struct NumberVisitor<T> {
_phantom: PhantomData<T>,
}
impl<'de, T> serde::de::Visitor<'de> for NumberVisitor<T>
where
T: FromStr,
<T as FromStr>::Err: std::error::Error,
T: FromPrimitive,
{
type Value = NumberDeserialize<T>;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("an integer or string")
}
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
where
E: Error,
{
T::from_i64(v)
.map(NumberDeserialize)
.ok_or_else(|| serde::de::Error::custom("cannot parse from i64"))
}
fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
where
E: Error,
{
T::from_u64(v)
.map(NumberDeserialize)
.ok_or_else(|| serde::de::Error::custom("cannot parse from u64"))
}
fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
where
E: Error,
{
T::from_f64(v)
.map(NumberDeserialize)
.ok_or_else(|| serde::de::Error::custom("cannot parse from f64"))
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
v.parse()
.map(NumberDeserialize)
.map_err(serde::de::Error::custom)
}
}
impl<'de, T> serde::Deserialize<'de> for NumberDeserialize<T>
where
T: FromStr,
<T as FromStr>::Err: std::error::Error,
T: FromPrimitive,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_any(NumberVisitor {
_phantom: Default::default(),
})
}
}
```
However, this runs into an issue where with `arbitrary_precision`, rather than calling visit_i* or similar, it calls visit_map with a custom map visitor for numeric types?! It would appear this then has a special-cased key of `$serde_json::private::Number`.
I'm not really sure what I'm supposed to do here, it would appear enabling `arbitrary_precision` makes it so that serializers don't decode numbers as numbers? Any help would be most appreciated.
As an aside whilst messing around with this I noticed enabling `arbitrary_precision` makes this fail
```
let input = r#"{"$serde_json::private::Number":"hello"}"#;
let value = serde_json::from_str::<serde_json::Value>(input).unwrap();
```
|
diff --git a/src/de.rs b/src/de.rs
index b4c5ef7dc..bf103f04b 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -864,6 +864,15 @@ impl<'de, R: Read<'de>> Deserializer<R> {
buf.push('-');
}
self.scan_integer(&mut buf)?;
+ if positive {
+ if let Ok(unsigned) = buf.parse() {
+ return Ok(ParserNumber::U64(unsigned));
+ }
+ } else {
+ if let Ok(signed) = buf.parse() {
+ return Ok(ParserNumber::I64(signed));
+ }
+ }
Ok(ParserNumber::String(buf))
}
diff --git a/src/lib.rs b/src/lib.rs
index c36876da3..0a815747c 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -303,6 +303,7 @@
#![doc(html_root_url = "https://docs.rs/serde_json/1.0.74")]
// Ignored clippy lints
#![allow(
+ clippy::collapsible_else_if,
clippy::comparison_chain,
clippy::deprecated_cfg_attr,
clippy::doc_markdown,
|
diff --git a/tests/regression/issue845.rs b/tests/regression/issue845.rs
new file mode 100644
index 000000000..dcca55694
--- /dev/null
+++ b/tests/regression/issue845.rs
@@ -0,0 +1,72 @@
+use serde::{Deserialize, Deserializer};
+use std::convert::TryFrom;
+use std::fmt::{self, Display};
+use std::marker::PhantomData;
+use std::str::FromStr;
+
+pub struct NumberVisitor<T> {
+ marker: PhantomData<T>,
+}
+
+impl<'de, T> serde::de::Visitor<'de> for NumberVisitor<T>
+where
+ T: TryFrom<u64> + TryFrom<i64> + FromStr,
+ <T as TryFrom<u64>>::Error: Display,
+ <T as TryFrom<i64>>::Error: Display,
+ <T as FromStr>::Err: Display,
+{
+ type Value = T;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("an integer or string")
+ }
+
+ fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
+ where
+ E: serde::de::Error,
+ {
+ T::try_from(v).map_err(serde::de::Error::custom)
+ }
+
+ fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
+ where
+ E: serde::de::Error,
+ {
+ T::try_from(v).map_err(serde::de::Error::custom)
+ }
+
+ fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
+ where
+ E: serde::de::Error,
+ {
+ v.parse().map_err(serde::de::Error::custom)
+ }
+}
+
+fn deserialize_integer_or_string<'de, D, T>(deserializer: D) -> Result<T, D::Error>
+where
+ D: Deserializer<'de>,
+ T: TryFrom<u64> + TryFrom<i64> + FromStr,
+ <T as TryFrom<u64>>::Error: Display,
+ <T as TryFrom<i64>>::Error: Display,
+ <T as FromStr>::Err: Display,
+{
+ deserializer.deserialize_any(NumberVisitor {
+ marker: PhantomData,
+ })
+}
+
+#[derive(Deserialize, Debug)]
+pub struct Struct {
+ #[serde(deserialize_with = "deserialize_integer_or_string")]
+ pub i: i64,
+}
+
+#[test]
+fn test() {
+ let j = r#" {"i":100} "#;
+ println!("{:?}", serde_json::from_str::<Struct>(j).unwrap());
+
+ let j = r#" {"i":"100"} "#;
+ println!("{:?}", serde_json::from_str::<Struct>(j).unwrap());
+}
diff --git a/tests/test.rs b/tests/test.rs
index 054e96088..bfcb5290f 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -715,11 +715,7 @@ fn test_parse_char() {
),
(
"10",
- if cfg!(feature = "arbitrary_precision") {
- "invalid type: number, expected a character at line 1 column 2"
- } else {
- "invalid type: integer `10`, expected a character at line 1 column 2"
- },
+ "invalid type: integer `10`, expected a character at line 1 column 2",
),
]);
@@ -1203,11 +1199,7 @@ fn test_parse_struct() {
test_parse_err::<Outer>(&[
(
"5",
- if cfg!(feature = "arbitrary_precision") {
- "invalid type: number, expected struct Outer at line 1 column 1"
- } else {
- "invalid type: integer `5`, expected struct Outer at line 1 column 1"
- },
+ "invalid type: integer `5`, expected struct Outer at line 1 column 1",
),
(
"\"hello\"",
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
|
1.0
|
serde-rs__json-801
| 801
|
[
"799"
] |
2021-09-14T20:01:13Z
|
b419f2e0650ab959a3db0b0ca471269e81abf27f
|
Preserve sign on negative zero f32
`-0` is parsed as `0` for `f32` type.
Is it intentional? I know that this is an edge case, but this is somewhat important for my use case, because it technically two different values.
rustc 1.54.0, serde_json v1.0.67
|
diff --git a/src/de.rs b/src/de.rs
index 7cc9f9b8e..a2f34b908 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -434,8 +434,8 @@ impl<'de, R: Read<'de>> Deserializer<R> {
} else {
let neg = (significand as i64).wrapping_neg();
- // Convert into a float if we underflow.
- if neg > 0 {
+ // Convert into a float if we underflow, or on `-0`.
+ if neg >= 0 {
ParserNumber::F64(-(significand as f64))
} else {
ParserNumber::I64(neg)
|
diff --git a/tests/test.rs b/tests/test.rs
index 9fdf26cc7..d6a0e81c1 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -805,6 +805,7 @@ fn test_parse_u64() {
#[test]
fn test_parse_negative_zero() {
for negative_zero in &[
+ "-0",
"-0.0",
"-0e2",
"-0.0e2",
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
|
1.0
|
serde-rs__json-796
| 796
|
[
"795"
] |
2021-08-28T18:22:46Z
|
7b4585fbff5962f05ffb1d7b5a296cf35b69072e
|
Deserialization from Value fails to catch unknown fields in struct variant
This is an inconsistency between `from_str` and `from_value`. In general these are supposed to have the same behavior on identical input.
```rust
use serde::de::{
Deserialize, Deserializer, EnumAccess, IgnoredAny, MapAccess, VariantAccess, Visitor,
};
use serde_json::json;
use std::fmt;
#[derive(Debug)]
enum Enum {
Variant { x: u8 },
}
impl<'de> Deserialize<'de> for Enum {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct EnumVisitor;
impl<'de> Visitor<'de> for EnumVisitor {
type Value = Enum;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("enum Enum")
}
fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
where
A: EnumAccess<'de>,
{
let (IgnoredAny, variant) = data.variant()?;
variant.struct_variant(&["x"], self)
}
fn visit_map<A>(self, mut data: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut x = 0;
if let Some((IgnoredAny, value)) = data.next_entry()? {
x = value;
}
Ok(Enum::Variant { x })
}
}
deserializer.deserialize_enum("Enum", &["Variant"], EnumVisitor)
}
}
fn main() {
let s = r#" {"Variant":{"x":0,"y":0}} "#;
assert!(serde_json::from_str::<Enum>(s).is_err());
let j = json!({"Variant":{"x":0,"y":0}});
println!("{:?}", serde_json::from_value::<Enum>(j).unwrap());
}
```
|
diff --git a/src/value/de.rs b/src/value/de.rs
index 5ff011961..24ca82696 100644
--- a/src/value/de.rs
+++ b/src/value/de.rs
@@ -538,7 +538,7 @@ impl<'de> VariantAccess<'de> for VariantDeserializer {
V: Visitor<'de>,
{
match self.value {
- Some(Value::Object(v)) => visitor.visit_map(MapDeserializer::new(v)),
+ Some(Value::Object(v)) => visit_object(v, visitor),
Some(other) => Err(serde::de::Error::invalid_type(
other.unexpected(),
&"struct variant",
@@ -1021,7 +1021,7 @@ impl<'de> VariantAccess<'de> for VariantRefDeserializer<'de> {
V: Visitor<'de>,
{
match self.value {
- Some(&Value::Object(ref v)) => visitor.visit_map(MapRefDeserializer::new(v)),
+ Some(&Value::Object(ref v)) => visit_object_ref(v, visitor),
Some(other) => Err(serde::de::Error::invalid_type(
other.unexpected(),
&"struct variant",
|
diff --git a/tests/regression/issue795.rs b/tests/regression/issue795.rs
new file mode 100644
index 000000000..43198a33d
--- /dev/null
+++ b/tests/regression/issue795.rs
@@ -0,0 +1,57 @@
+use serde::de::{
+ Deserialize, Deserializer, EnumAccess, IgnoredAny, MapAccess, VariantAccess, Visitor,
+};
+use serde_json::json;
+use std::fmt;
+
+#[derive(Debug)]
+enum Enum {
+ Variant { x: u8 },
+}
+
+impl<'de> Deserialize<'de> for Enum {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ struct EnumVisitor;
+
+ impl<'de> Visitor<'de> for EnumVisitor {
+ type Value = Enum;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("enum Enum")
+ }
+
+ fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
+ where
+ A: EnumAccess<'de>,
+ {
+ let (IgnoredAny, variant) = data.variant()?;
+ variant.struct_variant(&["x"], self)
+ }
+
+ fn visit_map<A>(self, mut data: A) -> Result<Self::Value, A::Error>
+ where
+ A: MapAccess<'de>,
+ {
+ let mut x = 0;
+ if let Some((IgnoredAny, value)) = data.next_entry()? {
+ x = value;
+ }
+ Ok(Enum::Variant { x })
+ }
+ }
+
+ deserializer.deserialize_enum("Enum", &["Variant"], EnumVisitor)
+ }
+}
+
+#[test]
+fn test() {
+ let s = r#" {"Variant":{"x":0,"y":0}} "#;
+ assert!(serde_json::from_str::<Enum>(s).is_err());
+
+ let j = json!({"Variant":{"x":0,"y":0}});
+ assert!(serde_json::from_value::<Enum>(j).is_err());
+}
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
|
1.0
|
serde-rs__json-786
| 786
|
[
"785"
] |
2021-07-17T03:32:52Z
|
ea39063f9c8c7dde4ac43bbd9843287bece59b1a
|
With feature "arbitrary_precision" exponent marker get converted to lowercase
Comment in [`Cargo.toml`](https://github.com/serde-rs/json/blob/ea39063f9c8c7dde4ac43bbd9843287bece59b1a/Cargo.toml#L71) for feature `arbitrary_precision` states:
> This feature makes `JSON` -> `serde_json::Number` -> `JSON` produce output identical to the input.
But in [`serde_json::de::scan_exponent`](https://github.com/serde-rs/json/blob/ea39063f9c8c7dde4ac43bbd9843287bece59b1a/src/de.rs#L934), for the exponent marker (`e` or `E`), a lowercase `e` is inserted unconditionally to the internal representation. Therefore, for an input JSON `1.9E10` for example, a "`JSON` -> `serde_json::Number` -> `JSON`" roundtrip results in JSON `1.9e10`, which is different from the input JSON.
Is this behaviour intended? If no other code rely on `e` being lowercase, I suggest we insert an `e` or `E` based on the input. Some specification requires some fields always treated as string, and in case they are presented as numbers in JSON, they should be converted to strings *verbatim*. `arbitrary_precision` is the only method I found for such circumstances, and I believe it should behave as described in `Cargo.toml`.
P.S. If you see the above-mentioned change appropriate, I can make a PR for this.
|
diff --git a/src/de.rs b/src/de.rs
index 15c8236b6..1824117a0 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -898,7 +898,7 @@ impl<'de, R: Read<'de>> Deserializer<R> {
fn scan_number(&mut self, buf: &mut String) -> Result<()> {
match tri!(self.peek_or_null()) {
b'.' => self.scan_decimal(buf),
- b'e' | b'E' => self.scan_exponent(buf),
+ c @ (b'e' | b'E') => self.scan_exponent(c as char, buf),
_ => Ok(()),
}
}
@@ -923,19 +923,20 @@ impl<'de, R: Read<'de>> Deserializer<R> {
}
match tri!(self.peek_or_null()) {
- b'e' | b'E' => self.scan_exponent(buf),
+ c @ (b'e' | b'E') => self.scan_exponent(c as char, buf),
_ => Ok(()),
}
}
#[cfg(feature = "arbitrary_precision")]
- fn scan_exponent(&mut self, buf: &mut String) -> Result<()> {
+ fn scan_exponent(&mut self, e: char, buf: &mut String) -> Result<()> {
self.eat_char();
- buf.push('e');
+ buf.push(e);
match tri!(self.peek_or_null()) {
b'+' => {
self.eat_char();
+ buf.push('+');
}
b'-' => {
self.eat_char();
|
diff --git a/tests/test.rs b/tests/test.rs
index 2fe7c560a..3d701d827 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -1007,8 +1007,14 @@ fn test_parse_number() {
#[cfg(feature = "arbitrary_precision")]
test_parse_ok(vec![
("1e999", Number::from_string_unchecked("1e999".to_owned())),
+ ("1e+999", Number::from_string_unchecked("1e+999".to_owned())),
("-1e999", Number::from_string_unchecked("-1e999".to_owned())),
("1e-999", Number::from_string_unchecked("1e-999".to_owned())),
+ ("1E999", Number::from_string_unchecked("1E999".to_owned())),
+ ("1E+999", Number::from_string_unchecked("1E+999".to_owned())),
+ ("-1E999", Number::from_string_unchecked("-1E999".to_owned())),
+ ("1E-999", Number::from_string_unchecked("1E-999".to_owned())),
+ ("1E+000", Number::from_string_unchecked("1E+000".to_owned())),
(
"2.3e999",
Number::from_string_unchecked("2.3e999".to_owned()),
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
|
1.0
|
serde-rs__json-757
| 757
|
[
"755"
] |
2021-02-28T04:47:02Z
|
9bcb08fd926c1c727cb1343363d41c25f2e6025d
|
Panic on input that is not valid UTF8 when deserializing to a RawValue
Very similar to this issue: https://github.com/serde-rs/json/issues/99
However, I ran into this problem when deserializing to a RawValue.
```
let json_str2 = &[ b'"', b'\xCE', b'\xF8', b'"'];
let v2: serde_json::Result<Box<serde_json::value::RawValue>> = serde_json::from_slice(json_str2);
```
I get this kind of backtrace:
```
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Utf8Error { valid_up_to: 1, error_len: Some(1) }', C:\Users\X\.cargo\registry\src\github.com-1ecc6299db9ec823\serde_json-1.0.63\src\read.rs:590:39
stack backtrace:
0: std::panicking::begin_panic_handler
at /rustc/cb75ad5db02783e8b0222fee363c5f63f7e2cf5b\/library\std\src\panicking.rs:493
1: core::panicking::panic_fmt
at /rustc/cb75ad5db02783e8b0222fee363c5f63f7e2cf5b\/library\core\src\panicking.rs:92
2: core::option::expect_none_failed
at /rustc/cb75ad5db02783e8b0222fee363c5f63f7e2cf5b\/library\core\src\option.rs:1268
3: core::result::Result<str, core::str::error::Utf8Error>::unwrap<str,core::str::error::Utf8Error>
at C:\Users\X\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\core\src\result.rs:973
4: serde_json::read::{{impl}}::end_raw_buffering<serde_json::raw::{{impl}}::deserialize::BoxedVisitor>
at C:\Users\X\.cargo\registry\src\github.com-1ecc6299db9ec823\serde_json-1.0.63\src\read.rs:590
5: serde_json::de::Deserializer<serde_json::read::SliceRead>::deserialize_raw_value<serde_json::read::SliceRead,serde_json::raw::{{impl}}::deserialize::BoxedVisitor>
at C:\Users\X\.cargo\registry\src\github.com-1ecc6299db9ec823\serde_json-1.0.63\src\de.rs:1194
6: serde_json::de::{{impl}}::deserialize_newtype_struct<serde_json::read::SliceRead,serde_json::raw::{{impl}}::deserialize::BoxedVisitor>
at C:\Users\X\.cargo\registry\src\github.com-1ecc6299db9ec823\serde_json-1.0.63\src\de.rs:1695
7: serde_json::raw::{{impl}}::deserialize<mut serde_json::de::Deserializer<serde_json::read::SliceRead>*>
at C:\Users\X\.cargo\registry\src\github.com-1ecc6299db9ec823\serde_json-1.0.63\src\raw.rs:347
8: serde_json::de::from_trait<serde_json::read::SliceRead,alloc::boxed::Box<serde_json::raw::RawValue, alloc::alloc::Global>>
at C:\Users\X\.cargo\registry\src\github.com-1ecc6299db9ec823\serde_json-1.0.63\src\de.rs:2386
9: serde_json::de::from_slice<alloc::boxed::Box<serde_json::raw::RawValue, alloc::alloc::Global>>
at C:\Users\X\.cargo\registry\src\github.com-1ecc6299db9ec823\serde_json-1.0.63\src\de.rs:2544
10: gltf_data_packer::main
at .\src\main.rs:34
11: core::ops::function::FnOnce::call_once<fn(),tuple<>>
at C:\Users\X\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\core\src\ops\function.rs:227
```
I encountered this issue when parsing a glTF-file: https://github.com/gltf-rs/gltf/issues/298
|
diff --git a/src/read.rs b/src/read.rs
index 522c0e011..574857cd8 100644
--- a/src/read.rs
+++ b/src/read.rs
@@ -587,7 +587,10 @@ impl<'a> Read<'a> for SliceRead<'a> {
V: Visitor<'a>,
{
let raw = &self.slice[self.raw_buffering_start_index..self.index];
- let raw = str::from_utf8(raw).unwrap();
+ let raw = match str::from_utf8(raw) {
+ Ok(raw) => raw,
+ Err(_) => return error(self, ErrorCode::InvalidUnicodeCodePoint),
+ };
visitor.visit_map(BorrowedRawDeserializer {
raw_value: Some(raw),
})
|
diff --git a/tests/test.rs b/tests/test.rs
index ffe58c979..2fe7c560a 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -2201,6 +2201,25 @@ fn test_boxed_raw_value() {
assert_eq!(r#"["a",42,{"foo": "bar"},null]"#, array_to_string);
}
+#[cfg(feature = "raw_value")]
+#[test]
+fn test_raw_invalid_utf8() {
+ use serde_json::value::RawValue;
+
+ let j = &[b'"', b'\xCE', b'\xF8', b'"'];
+ let value_err = serde_json::from_slice::<Value>(j).unwrap_err();
+ let raw_value_err = serde_json::from_slice::<Box<RawValue>>(j).unwrap_err();
+
+ assert_eq!(
+ value_err.to_string(),
+ "invalid unicode code point at line 1 column 4",
+ );
+ assert_eq!(
+ raw_value_err.to_string(),
+ "invalid unicode code point at line 1 column 4",
+ );
+}
+
#[test]
fn test_borrow_in_map_key() {
#[derive(Deserialize, Debug)]
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
|
1.0
|
serde-rs__json-648
| 648
|
[
"647"
] |
2020-04-04T23:17:05Z
|
fd6741f4b0b3fc90a58a6f578e33a9adc6403f3f
|
StreamDeserializer enters a busy-loop for malformed input
See the test in
https://github.com/oli-obk/cargo_metadata/pull/106/commits/ea84dc353dc4367c507eec0f4fd1f73892cf4d28
There, the `for message in stream_deserilizer` loop loops infinitelly, because serde repeteadly tries to parse the same invalid portion of input.
I *think* the correct behavior here is to "poison" the Iterator after the first error and return `None`. I can also imagine some error-recovey strategy (like skipping to the next utf8 codepoint), but poisoning seems more reliable to me.
|
diff --git a/src/de.rs b/src/de.rs
index 1a7192672..890a51687 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -151,6 +151,7 @@ impl<'de, R: Read<'de>> Deserializer<R> {
StreamDeserializer {
de: self,
offset: offset,
+ failed: false,
output: PhantomData,
lifetime: PhantomData,
}
@@ -2046,6 +2047,7 @@ where
pub struct StreamDeserializer<'de, R, T> {
de: Deserializer<R>,
offset: usize,
+ failed: bool,
output: PhantomData<T>,
lifetime: PhantomData<&'de ()>,
}
@@ -2068,6 +2070,7 @@ where
StreamDeserializer {
de: Deserializer::new(read),
offset: offset,
+ failed: false,
output: PhantomData,
lifetime: PhantomData,
}
@@ -2132,6 +2135,10 @@ where
type Item = Result<T>;
fn next(&mut self) -> Option<Result<T>> {
+ if R::should_early_return_if_failed && self.failed {
+ return None;
+ }
+
// skip whitespaces, if any
// this helps with trailing whitespaces, since whitespaces between
// values are handled for us.
@@ -2160,10 +2167,16 @@ where
self.peek_end_of_value().map(|_| value)
}
}
- Err(e) => Err(e),
+ Err(e) => {
+ self.de.read.set_failed(&mut self.failed);
+ Err(e)
+ }
})
}
- Err(e) => Some(Err(e)),
+ Err(e) => {
+ self.de.read.set_failed(&mut self.failed);
+ Some(Err(e))
+ }
}
}
}
diff --git a/src/lib.rs b/src/lib.rs
index 8114f3a3a..a276b3887 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -337,6 +337,7 @@
clippy::missing_errors_doc,
clippy::must_use_candidate,
)]
+#![allow(non_upper_case_globals)]
#![deny(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
diff --git a/src/read.rs b/src/read.rs
index 89ed6e6c7..01d30682c 100644
--- a/src/read.rs
+++ b/src/read.rs
@@ -97,6 +97,18 @@ pub trait Read<'de>: private::Sealed {
fn end_raw_buffering<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: Visitor<'de>;
+
+ /// Whether StreamDeserializer::next needs to check the failed flag. True
+ /// for IoRead, false for StrRead and SliceRead which can track failure by
+ /// truncating their input slice to avoid the extra check on every next
+ /// call.
+ #[doc(hidden)]
+ const should_early_return_if_failed: bool;
+
+ /// Mark a persistent failure of StreamDeserializer, either by setting the
+ /// flag or by truncating the input data.
+ #[doc(hidden)]
+ fn set_failed(&mut self, failed: &mut bool);
}
pub struct Position {
@@ -379,6 +391,13 @@ where
raw_value: Some(raw),
})
}
+
+ const should_early_return_if_failed: bool = true;
+
+ #[inline]
+ fn set_failed(&mut self, failed: &mut bool) {
+ *failed = true;
+ }
}
//////////////////////////////////////////////////////////////////////////////
@@ -590,6 +609,13 @@ impl<'a> Read<'a> for SliceRead<'a> {
raw_value: Some(raw),
})
}
+
+ const should_early_return_if_failed: bool = false;
+
+ #[inline]
+ fn set_failed(&mut self, _failed: &mut bool) {
+ self.slice = &self.slice[..self.index];
+ }
}
//////////////////////////////////////////////////////////////////////////////
@@ -681,6 +707,13 @@ impl<'a> Read<'a> for StrRead<'a> {
raw_value: Some(raw),
})
}
+
+ const should_early_return_if_failed: bool = false;
+
+ #[inline]
+ fn set_failed(&mut self, failed: &mut bool) {
+ self.delegate.set_failed(failed);
+ }
}
//////////////////////////////////////////////////////////////////////////////
|
diff --git a/tests/stream.rs b/tests/stream.rs
index 9fabe0de2..ca54e9a15 100644
--- a/tests/stream.rs
+++ b/tests/stream.rs
@@ -169,3 +169,14 @@ fn test_json_stream_invalid_number() {
assert_eq!(second.to_string(), "trailing characters at line 1 column 2");
});
}
+
+#[test]
+fn test_error() {
+ let data = "true wrong false";
+
+ test_stream!(data, Value, |stream| {
+ assert_eq!(stream.next().unwrap().unwrap(), true);
+ assert!(stream.next().unwrap().is_err());
+ assert!(stream.next().is_none());
+ });
+}
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
|
1.0
|
serde-rs__json-525
| 525
|
[
"524"
] |
2019-03-19T09:15:01Z
|
Thanks, I would accept a PR to return an EOF error in this case.
|
e6b02d1b53cf1c685db9e20f6a300e8f22a9bf00
|
StreamDeserializer errors on cut-off decimal numbers
Simple example:
```rust
fn main() {
dbg!(serde_json::Deserializer::from_slice(b"[1.").into_iter::<Vec<f64>>().next());
}
```
I'd expect that to return None or an EOF error - the array is not finished yet and the number is valid if it's followed by more digits. But instead it returns an early parse error:
```rust
serde_json::Deserializer::from_slice(b"[1.").into_iter::<Vec<f64>>().next() = Some(
Err(
Error("invalid number", line: 1, column: 3)
)
)
```
(What I'm really doing is using a StreamDeserializer with a little bit of custom parsing to parse a large array of values, so my problem would also be solved with #404 )
|
diff --git a/src/de.rs b/src/de.rs
index e3effc365..f8d4ace53 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -380,7 +380,14 @@ impl<'de, R: Read<'de>> Deserializer<R> {
}
fn parse_integer(&mut self, positive: bool) -> Result<ParserNumber> {
- match try!(self.next_char_or_null()) {
+ let next = match try!(self.next_char()) {
+ Some(b) => b,
+ None => {
+ return Err(self.error(ErrorCode::EofWhileParsingValue));
+ }
+ };
+
+ match next {
b'0' => {
// There can be only one leading '0'.
match try!(self.peek_or_null()) {
@@ -496,7 +503,10 @@ impl<'de, R: Read<'de>> Deserializer<R> {
}
if !at_least_one_digit {
- return Err(self.peek_error(ErrorCode::InvalidNumber));
+ match try!(self.peek()) {
+ Some(_) => return Err(self.peek_error(ErrorCode::InvalidNumber)),
+ None => return Err(self.peek_error(ErrorCode::EofWhileParsingValue)),
+ }
}
match try!(self.peek_or_null()) {
@@ -525,8 +535,15 @@ impl<'de, R: Read<'de>> Deserializer<R> {
_ => true,
};
+ let next = match try!(self.next_char()) {
+ Some(b) => b,
+ None => {
+ return Err(self.error(ErrorCode::EofWhileParsingValue));
+ }
+ };
+
// Make sure a digit follows the exponent place.
- let mut exp = match try!(self.next_char_or_null()) {
+ let mut exp = match next {
c @ b'0'...b'9' => (c - b'0') as i32,
_ => {
return Err(self.error(ErrorCode::InvalidNumber));
@@ -623,19 +640,19 @@ impl<'de, R: Read<'de>> Deserializer<R> {
}
#[cfg(feature = "arbitrary_precision")]
- fn scan_or_null(&mut self, buf: &mut String) -> Result<u8> {
+ fn scan_or_eof(&mut self, buf: &mut String) -> Result<u8> {
match try!(self.next_char()) {
Some(b) => {
buf.push(b as char);
Ok(b)
}
- None => Ok(b'\x00'),
+ None => Err(self.error(ErrorCode::EofWhileParsingValue))
}
}
#[cfg(feature = "arbitrary_precision")]
fn scan_integer(&mut self, buf: &mut String) -> Result<()> {
- match try!(self.scan_or_null(buf)) {
+ match try!(self.scan_or_eof(buf)) {
b'0' => {
// There can be only one leading '0'.
match try!(self.peek_or_null()) {
@@ -680,7 +697,10 @@ impl<'de, R: Read<'de>> Deserializer<R> {
}
if !at_least_one_digit {
- return Err(self.peek_error(ErrorCode::InvalidNumber));
+ match try!(self.peek()) {
+ Some(_) => return Err(self.peek_error(ErrorCode::InvalidNumber)),
+ None => return Err(self.peek_error(ErrorCode::EofWhileParsingValue)),
+ }
}
match try!(self.peek_or_null()) {
@@ -706,7 +726,7 @@ impl<'de, R: Read<'de>> Deserializer<R> {
}
// Make sure a digit follows the exponent place.
- match try!(self.scan_or_null(buf)) {
+ match try!(self.scan_or_eof(buf)) {
b'0'...b'9' => {}
_ => {
return Err(self.error(ErrorCode::InvalidNumber));
|
diff --git a/tests/stream.rs b/tests/stream.rs
index 7127b2534..88a395294 100644
--- a/tests/stream.rs
+++ b/tests/stream.rs
@@ -81,6 +81,36 @@ fn test_json_stream_truncated() {
});
}
+#[test]
+fn test_json_stream_truncated_decimal() {
+ let data = "{\"x\":4.";
+
+ test_stream!(data, Value, |stream| {
+ assert!(stream.next().unwrap().unwrap_err().is_eof());
+ assert_eq!(stream.byte_offset(), 0);
+ });
+}
+
+#[test]
+fn test_json_stream_truncated_negative() {
+ let data = "{\"x\":-";
+
+ test_stream!(data, Value, |stream| {
+ assert!(stream.next().unwrap().unwrap_err().is_eof());
+ assert_eq!(stream.byte_offset(), 0);
+ });
+}
+
+#[test]
+fn test_json_stream_truncated_exponent() {
+ let data = "{\"x\":4e";
+
+ test_stream!(data, Value, |stream| {
+ assert!(stream.next().unwrap().unwrap_err().is_eof());
+ assert_eq!(stream.byte_offset(), 0);
+ });
+}
+
#[test]
fn test_json_stream_empty() {
let data = "";
diff --git a/tests/test.rs b/tests/test.rs
index 6948ee280..afa6a01fe 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -737,15 +737,15 @@ fn test_parse_number_errors() {
test_parse_err::<f64>(&[
("+", "expected value at line 1 column 1"),
(".", "expected value at line 1 column 1"),
- ("-", "invalid number at line 1 column 1"),
+ ("-", "EOF while parsing a value at line 1 column 1"),
("00", "invalid number at line 1 column 2"),
("0x80", "trailing characters at line 1 column 2"),
("\\0", "expected value at line 1 column 1"),
- ("1.", "invalid number at line 1 column 2"),
+ ("1.", "EOF while parsing a value at line 1 column 2"),
("1.a", "invalid number at line 1 column 3"),
("1.e1", "invalid number at line 1 column 3"),
- ("1e", "invalid number at line 1 column 2"),
- ("1e+", "invalid number at line 1 column 3"),
+ ("1e", "EOF while parsing a value at line 1 column 2"),
+ ("1e+", "EOF while parsing a value at line 1 column 3"),
("1a", "trailing characters at line 1 column 2"),
(
"100e777777777777777777777777777",
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
1.0
|
serde-rs__json-521
| 521
|
[
"520"
] |
2019-02-28T08:59:36Z
|
6ac689b2b327ed00e8a56d812a5c860177ab10dd
|
Error roundtripping (regression from 1.0.25 to 1.0.38)
We need to roundtrip an enum that has an element `Float(f32)`. That used to work with 1.0.25, but fails with 1.0.38. [This gist](https://gist.github.com/lutter/2820e2c98331d5b5b6b95d62912e2e0f) has complete code that demonstrates the problem.
What happens is that the enum can be turned into a `serde_json::Value`, but trying to get the enum back from that causes the error `invalid type: map, expected f32`.
This is somewhat urgent, as it keeps us from updating other dependencies that use newer versions of serde_json (and we really need to update those).
For completeness sake, here is the `serde_json::Value` that fails to parse back to a `Float(f32)` and the error from my test program:
```
[src/main.rs:20] serde_json::to_value(v).unwrap() = Object(
{
"data": Number(159.10000610351562),
"type": String(
"Float"
)
}
)
[src/main.rs:25] serde_json::from_value::<Value>(jv) = Err(
Error("invalid type: map, expected f32", line: 0, column: 0)
)
```
|
diff --git a/Cargo.toml b/Cargo.toml
index 168a40df3..dd912d69c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -22,6 +22,7 @@ itoa = "0.4.3"
ryu = "0.2"
[dev-dependencies]
+automod = "0.1"
compiletest_rs = { version = "0.3", features = ["stable"] }
serde_bytes = "0.10"
serde_derive = "1.0"
diff --git a/src/number.rs b/src/number.rs
index b6ff8ff77..70a8f6d65 100644
--- a/src/number.rs
+++ b/src/number.rs
@@ -473,7 +473,7 @@ macro_rules! deserialize_any {
} else if let Some(i) = self.as_i64() {
return visitor.visit_i64(i);
} else if let Some(f) = self.as_f64() {
- if f.to_string() == self.n {
+ if ryu::Buffer::new().format(f) == self.n || f.to_string() == self.n {
return visitor.visit_f64(f);
}
}
|
diff --git a/tests/regression.rs b/tests/regression.rs
new file mode 100644
index 000000000..eff29ff6c
--- /dev/null
+++ b/tests/regression.rs
@@ -0,0 +1,6 @@
+extern crate automod;
+extern crate serde;
+extern crate serde_derive;
+
+#[path = "regression/mod.rs"]
+mod regression;
diff --git a/tests/regression/issue520.rs b/tests/regression/issue520.rs
new file mode 100644
index 000000000..6befd494c
--- /dev/null
+++ b/tests/regression/issue520.rs
@@ -0,0 +1,18 @@
+use serde_derive::{Serialize, Deserialize};
+
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(tag = "type", content = "data")]
+enum E {
+ Float(f32),
+}
+
+#[test]
+fn test() {
+ let e = E::Float(159.1);
+ let v = serde_json::to_value(e).unwrap();
+ let e = serde_json::from_value::<E>(v).unwrap();
+
+ match e {
+ E::Float(f) => assert_eq!(f, 159.1),
+ }
+}
diff --git a/tests/regression/mod.rs b/tests/regression/mod.rs
new file mode 100644
index 000000000..830175fc2
--- /dev/null
+++ b/tests/regression/mod.rs
@@ -0,0 +1,1 @@
+automod::dir!("tests/regression");
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
|
1.0
|
serde-rs__json-512
| 512
|
[
"511"
] |
2019-01-16T21:56:30Z
|
Forgot to mention, works ok for u64
|
22c0c7e92fe93d0c0f8ee1a1fcf3588290975d53
|
u128 as hashmap key results in invalid json
See example output here being invalid json (key not quoted): [playground link](https://play.integer32.com/?version=stable&mode=debug&edition=2018&gist=c026aab61d8559c539d5742cb3b498ee)
|
diff --git a/src/ser.rs b/src/ser.rs
index d0fc66a4b..463c15a16 100644
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -987,10 +987,22 @@ where
serde_if_integer128! {
fn serialize_i128(self, value: i128) -> Result<()> {
- self.ser
+ try!(self
+ .ser
+ .formatter
+ .begin_string(&mut self.ser.writer)
+ .map_err(Error::io));
+ try!(self
+ .ser
.formatter
.write_number_str(&mut self.ser.writer, &value.to_string())
- .map_err(Error::io)
+ .map_err(Error::io));
+ try!(self
+ .ser
+ .formatter
+ .end_string(&mut self.ser.writer)
+ .map_err(Error::io));
+ Ok(())
}
}
@@ -1072,10 +1084,22 @@ where
serde_if_integer128! {
fn serialize_u128(self, value: u128) -> Result<()> {
- self.ser
+ try!(self
+ .ser
+ .formatter
+ .begin_string(&mut self.ser.writer)
+ .map_err(Error::io));
+ try!(self
+ .ser
.formatter
.write_number_str(&mut self.ser.writer, &value.to_string())
- .map_err(Error::io)
+ .map_err(Error::io));
+ try!(self
+ .ser
+ .formatter
+ .end_string(&mut self.ser.writer)
+ .map_err(Error::io));
+ Ok(())
}
}
|
diff --git a/tests/test.rs b/tests/test.rs
index 46b3396eb..548f71a32 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -1782,6 +1782,16 @@ fn test_integer_key() {
)]);
}
+#[test]
+fn test_integer128_key() {
+ let map = treemap! {
+ 100000000000000000000000000000000000000u128 => ()
+ };
+ let j = r#"{"100000000000000000000000000000000000000":null}"#;
+ assert_eq!(to_string(&map).unwrap(), j);
+ assert_eq!(from_str::<BTreeMap<u128, ()>>(j).unwrap(), map);
+}
+
#[test]
fn test_deny_float_key() {
#[derive(Eq, PartialEq, Ord, PartialOrd)]
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
1.0
|
serde-rs__json-506
| 506
|
[
"502"
] |
2018-12-29T09:22:21Z
|
Thanks! I would accept a PR to support u128 => Value in the case that arbitrary_precision is enabled.
|
32f1568c2a280d3456c566c811680f5bd65fd7f3
|
u128 doesn't work for Value
Looks like there's a bug in serde_json. This program:
```
#[macro_use]
extern crate serde_json;
use std::str::FromStr;
fn main() {
let string = format!("{}", u128::max_value());
println!("{}", string);
let val = serde_json::value::Value::from_str(&string);
let val2 = serde_json::to_value(u128::max_value());
println!("{:#?}, {:#?}", val, val2);
}
```
outputs:
```
340282366920938463463374607431768211455
Ok(
Number(
340282366920938500000000000000000000000.0
)
), Err(
Error("u128 is not supported", line: 0, column: 0)
)
```
[playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=4b3d4b4c201c7a8dc5d3e4f93c1f8bae)
if you put arbitrary_precision feature, then Value works 100% without cutting precision, if you do it via `u128` => `String` => `Value`. However direct conversion `u128` => `Value` with `to_value` results in error.
|
diff --git a/src/value/ser.rs b/src/value/ser.rs
index 172784cce..c377b533d 100644
--- a/src/value/ser.rs
+++ b/src/value/ser.rs
@@ -77,6 +77,13 @@ impl serde::Serializer for Serializer {
Ok(Value::Number(value.into()))
}
+ serde_if_integer128! {
+ #[cfg(feature = "arbitrary_precision")]
+ fn serialize_i128(self, value: i128) -> Result<Value, Error> {
+ Ok(Value::Number(Number::from_string_unchecked(value.to_string())))
+ }
+ }
+
#[inline]
fn serialize_u8(self, value: u8) -> Result<Value, Error> {
self.serialize_u64(value as u64)
@@ -97,6 +104,13 @@ impl serde::Serializer for Serializer {
Ok(Value::Number(value.into()))
}
+ serde_if_integer128! {
+ #[cfg(feature = "arbitrary_precision")]
+ fn serialize_u128(self, value: u128) -> Result<Value, Error> {
+ Ok(Value::Number(Number::from_string_unchecked(value.to_string())))
+ }
+ }
+
#[inline]
fn serialize_f32(self, value: f32) -> Result<Value, Error> {
self.serialize_f64(value as f64)
|
diff --git a/tests/test.rs b/tests/test.rs
index 97da8133a..c08645a02 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -1909,6 +1909,13 @@ fn test_partialeq_number() {
);
}
+#[test]
+#[cfg(integer128)]
+#[cfg(feature = "arbitrary_precision")]
+fn test_partialeq_integer128() {
+ number_partialeq_ok!(i128::MIN i128::MAX u128::MIN u128::MAX)
+}
+
#[test]
fn test_partialeq_string() {
let v = to_value("42").unwrap();
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
1.0
|
serde-rs__json-493
| 493
|
[
"492"
] |
2018-10-04T05:25:14Z
|
805f394f8b4165e4f365c27068eedc1d9cb6ac52
|
Malformed number causes panic in de.rs
The following test case demonstrates the problem. This could be used for DOSing Rust web apps.
```rust
extern crate serde_json;
#[test]
fn parse_json() {
let f: Result<f64, _> = serde_json::from_str("3.5E-2147483647");
}
```
```
stack backtrace:
0: std::sys::unix::backtrace::tracing::imp::unwind_backtrace
at libstd/sys/unix/backtrace/tracing/gcc_s.rs:49
1: std::sys_common::backtrace::print
at libstd/sys_common/backtrace.rs:71
at libstd/sys_common/backtrace.rs:59
2: std::panicking::default_hook::{{closure}}
at libstd/panicking.rs:211
3: std::panicking::default_hook
at libstd/panicking.rs:227
4: std::panicking::rust_panic_with_hook
at libstd/panicking.rs:475
5: std::panicking::continue_panic_fmt
at libstd/panicking.rs:390
6: rust_begin_unwind
at libstd/panicking.rs:325
7: core::panicking::panic_fmt
at libcore/panicking.rs:77
8: core::panicking::panic
at libcore/panicking.rs:52
9: core::num::<impl i32>::abs
at /checkout/src/libcore/num/mod.rs:1824
10: <serde_json::de::Deserializer<R>>::f64_from_parts
at /home/mw/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_json-1.0.31/src/de.rs:679
11: <serde_json::de::Deserializer<R>>::parse_exponent
at /home/mw/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_json-1.0.31/src/de.rs:500
12: <serde_json::de::Deserializer<R>>::parse_decimal
at /home/mw/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_json-1.0.31/src/de.rs:450
13: <serde_json::de::Deserializer<R>>::parse_number
at /home/mw/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_json-1.0.31/src/de.rs:399
14: <serde_json::de::Deserializer<R>>::parse_integer
at /home/mw/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_json-1.0.31/src/de.rs:361
15: <serde_json::de::Deserializer<R>>::deserialize_prim_number
at /home/mw/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_json-1.0.31/src/de.rs:267
16: <&'a mut serde_json::de::Deserializer<R> as serde::de::Deserializer<'de>>::deserialize_f64
at /home/mw/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_json-1.0.31/src/de.rs:989
17: serde::de::impls::<impl serde::de::Deserialize<'de> for f64>::deserialize
at /home/mw/.cargo/registry/src/github.com-1ecc6299db9ec823/serde-1.0.79/src/de/impls.rs:141
18: serde_json::de::from_trait
at /home/mw/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_json-1.0.31/src/de.rs:2115
19: serde_json::de::from_str
at /home/mw/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_json-1.0.31/src/de.rs:2260
```
|
diff --git a/src/de.rs b/src/de.rs
index 70ebf0d5e..020869a64 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -676,7 +676,7 @@ impl<'de, R: Read<'de>> Deserializer<R> {
) -> Result<f64> {
let mut f = significand as f64;
loop {
- match POW10.get(exponent.abs() as usize) {
+ match POW10.get(exponent.wrapping_abs() as usize) {
Some(&pow) => {
if exponent >= 0 {
f *= pow;
|
diff --git a/tests/test.rs b/tests/test.rs
index 954ac901b..688dfe5db 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -860,6 +860,7 @@ fn test_parse_f64() {
("0.00e00", 0.0),
("0.00e+00", 0.0),
("0.00e-00", 0.0),
+ ("3.5E-2147483647", 0.0),
(
&format!("{}", (i64::MIN as f64) - 1.0),
(i64::MIN as f64) - 1.0,
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
|
1.0
|
serde-rs__json-485
| 485
|
[
"355"
] |
2018-09-20T08:49:13Z
|
@dtolnay mentions that the work happening in #416 might lay some groundwork for such a change to take place.
Yeah, this sounds useful. Ideally we could get some of the building blocks for this sort of thing (custom 'built-in' types) integrated into serde itself, in time.
I need this for a project I'm working on, and would be happy to give it shot following the same approach as #416. Is this something that you'd accept a PR for?
Yes I would like a PR for this. When you say you need this feature, is it because deserializing to serde_json::Value is too slow in your project and you are expecting this to have better performance, or some other reason?
Yeah, I've got an http web server that's backed by a postgres database which stores JSONB values, and would like to shuffle data back and forth (and embed into other payloads) with as few allocations as possible.
As a first step, please put together a short benchmark that you trust as reasonably representative of the shuffling data back and forth piece of your application. Ideally it would depend on serde / serde_derive / serde_json but nothing else -- so no postgres or http stuff. Focus on the data structures so that they have the same ratio and pattern of raw vs meaningful content as your real use case. Write it using serde_json::Value for now, and then the goal will be to swap in a raw value once it's implemented and observe a speedup.
Wrote a small microbenchmark here: https://gist.github.com/srijs/7fe21b43c2cf5d2ceeb593ae4591c6f5
Please let me know if this is what you had in mind!
:+1: looks good, let's make it work.
|
b0e3a9798b95ea95d7fcc5d38b9e62010d367557
|
Add a RawValue type
It would be helpful to have a type similar to Go's [`json.RawMessage`](https://golang.org/pkg/encoding/json/#RawMessage) that is not tokenized during deserialization, but rather its raw contents stored as a `Vec<u8>` or `&'de [u8]`.
The following pseudo-code demonstrates the idea.
```rust
#[derive(Deserialize)]
struct Struct {
/// Deserialized normally.
core_data: Vec<i32>,
/// Contents of `user_data` are copied / borrowed directly from the input
/// with no modification.
///
/// `RawValue<'static>` is akin to `Vec<u8>`.
/// `RawValue<'a>` is akin to `&'a [u8]`.
user_data: serde_json::RawValue<'static>,
}
fn main() {
let json = r#"
{
"core_data": [1, 2, 3],
"user_data": { "foo": {}, "bar": 123, "baz": "abc" }
}
"#;
let s: Struct = serde_json::from_bytes(&json).unwrap();
println!("{}", s.user_data); // "{ \"foo\": {}, \"bar\": 123, \"baz\": \"abc\" }"
}
```
The main advantage of this is would be to have 'lazily-deserialized' values.
|
diff --git a/Cargo.toml b/Cargo.toml
index 2f8ebe5ca..0ccec383a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -26,6 +26,12 @@ compiletest_rs = "0.3"
serde_bytes = "0.10"
serde_derive = "1.0"
+[package.metadata.docs.rs]
+features = ["raw_value"]
+
+[package.metadata.playground]
+features = ["raw_value"]
+
### FEATURES #################################################################
@@ -41,3 +47,6 @@ preserve_order = ["indexmap"]
# allows JSON numbers of arbitrary size/precision to be read into a Number and
# written back to a JSON string without loss of precision.
arbitrary_precision = []
+
+# Provide a RawValue type that can hold unprocessed JSON during deserialization.
+raw_value = []
diff --git a/src/de.rs b/src/de.rs
index f1c5c3cff..7e44968e2 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -946,6 +946,17 @@ impl<'de, R: Read<'de>> Deserializer<R> {
}
}
}
+
+ #[cfg(feature = "raw_value")]
+ fn deserialize_raw_value<V>(&mut self, visitor: V) -> Result<V::Value>
+ where
+ V: de::Visitor<'de>,
+ {
+ self.parse_whitespace()?;
+ self.read.begin_raw_buffering();
+ self.ignore_value()?;
+ self.read.end_raw_buffering(visitor)
+ }
}
impl FromStr for Number {
@@ -1412,10 +1423,18 @@ impl<'de, 'a, R: Read<'de>> de::Deserializer<'de> for &'a mut Deserializer<R> {
/// Parses a newtype struct as the underlying value.
#[inline]
- fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value>
+ fn deserialize_newtype_struct<V>(self, name: &str, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
+ #[cfg(feature = "raw_value")]
+ {
+ if name == ::raw::TOKEN {
+ return self.deserialize_raw_value(visitor);
+ }
+ }
+
+ let _ = name;
visitor.visit_newtype_struct(self)
}
diff --git a/src/lib.rs b/src/lib.rs
index d9b79175e..79513b320 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -389,3 +389,6 @@ pub mod value;
mod iter;
mod number;
mod read;
+
+#[cfg(feature = "raw_value")]
+mod raw;
diff --git a/src/number.rs b/src/number.rs
index cc6bccb6c..fcf98ee78 100644
--- a/src/number.rs
+++ b/src/number.rs
@@ -26,12 +26,7 @@ use error::ErrorCode;
#[cfg(feature = "arbitrary_precision")]
/// Not public API. Should be pub(crate).
#[doc(hidden)]
-pub const SERDE_STRUCT_FIELD_NAME: &'static str = "$__serde_private_number";
-
-#[cfg(feature = "arbitrary_precision")]
-/// Not public API. Should be pub(crate).
-#[doc(hidden)]
-pub const SERDE_STRUCT_NAME: &'static str = "$__serde_private_Number";
+pub const TOKEN: &'static str = "$serde_json::private::Number";
/// Represents a JSON number, whether integer or floating point.
#[derive(Clone, PartialEq)]
@@ -346,8 +341,8 @@ impl Serialize for Number {
{
use serde::ser::SerializeStruct;
- let mut s = serializer.serialize_struct(SERDE_STRUCT_NAME, 1)?;
- s.serialize_field(SERDE_STRUCT_FIELD_NAME, &self.n)?;
+ let mut s = serializer.serialize_struct(TOKEN, 1)?;
+ s.serialize_field(TOKEN, &self.n)?;
s.end()
}
}
@@ -426,7 +421,7 @@ impl<'de> de::Deserialize<'de> for NumberKey {
where
E: de::Error,
{
- if s == SERDE_STRUCT_FIELD_NAME {
+ if s == TOKEN {
Ok(())
} else {
Err(de::Error::custom("expected field with custom name"))
@@ -638,7 +633,7 @@ impl<'de> Deserializer<'de> for NumberFieldDeserializer {
where
V: de::Visitor<'de>,
{
- visitor.visit_borrowed_str(SERDE_STRUCT_FIELD_NAME)
+ visitor.visit_borrowed_str(TOKEN)
}
forward_to_deserialize_any! {
diff --git a/src/raw.rs b/src/raw.rs
new file mode 100644
index 000000000..54b85c79c
--- /dev/null
+++ b/src/raw.rs
@@ -0,0 +1,445 @@
+use std::fmt::{self, Debug, Display};
+use std::mem;
+
+use serde::ser::{Serialize, Serializer, SerializeStruct};
+use serde::de::{self, Deserialize, Deserializer, DeserializeSeed, IntoDeserializer, MapAccess, Unexpected, Visitor};
+use serde::de::value::BorrowedStrDeserializer;
+
+use error::Error;
+
+/// Reference to a range of bytes encompassing a single valid JSON value in the
+/// input data.
+///
+/// A `RawValue` can be used to defer parsing parts of a payload until later,
+/// or to avoid parsing it at all in the case that part of the payload just
+/// needs to be transferred verbatim into a different output object.
+///
+/// When serializing, a value of this type will retain its original formatting
+/// and will not be minified or pretty-printed.
+///
+/// # Example
+///
+/// ```
+/// #[macro_use]
+/// extern crate serde_derive;
+/// extern crate serde_json;
+///
+/// use serde_json::{Result, value::RawValue};
+///
+/// #[derive(Deserialize)]
+/// struct Input<'a> {
+/// code: u32,
+/// #[serde(borrow)]
+/// payload: &'a RawValue,
+/// }
+///
+/// #[derive(Serialize)]
+/// struct Output<'a> {
+/// info: (u32, &'a RawValue),
+/// }
+///
+/// // Efficiently rearrange JSON input containing separate "code" and "payload"
+/// // keys into a single "info" key holding an array of code and payload.
+/// //
+/// // This could be done equivalently using serde_json::Value as the type for
+/// // payload, but &RawValue will perform netter because it does not require
+/// // memory allocation. The correct range of bytes is borrowed from the input
+/// // data and pasted verbatim into the output.
+/// fn rearrange(input: &str) -> Result<String> {
+/// let input: Input = serde_json::from_str(input)?;
+///
+/// let output = Output {
+/// info: (input.code, input.payload),
+/// };
+///
+/// serde_json::to_string(&output)
+/// }
+///
+/// fn main() -> Result<()> {
+/// let out = rearrange(r#" {"code": 200, "payload": {}} "#)?;
+///
+/// assert_eq!(out, r#"{"info":[200,{}]}"#);
+///
+/// Ok(())
+/// }
+/// ```
+///
+/// # Ownership
+///
+/// The typical usage of `RawValue` will be in the borrowed form:
+///
+/// ```
+/// # #[macro_use]
+/// # extern crate serde_derive;
+/// # extern crate serde_json;
+/// #
+/// # use serde_json::value::RawValue;
+/// #
+/// #[derive(Deserialize)]
+/// struct SomeStruct<'a> {
+/// #[serde(borrow)]
+/// raw_value: &'a RawValue,
+/// }
+/// #
+/// # fn main() {}
+/// ```
+///
+/// The borrowed form is suitable when deserializing through
+/// [`serde_json::from_str`] and [`serde_json::from_slice`] which support
+/// borrowing from the input data without memory allocation.
+///
+/// When deserializing through [`serde_json::from_reader`] you will need to use
+/// the boxed form of `RawValue` instead. This is almost as efficient but
+/// involves buffering the raw value from the I/O stream into memory.
+///
+/// [`serde_json::from_str`]: ../fn.from_str.html
+/// [`serde_json::from_slice`]: ../fn.from_slice.html
+/// [`serde_json::from_reader`]: ../fn.from_reader.html
+///
+/// ```
+/// # #[macro_use]
+/// # extern crate serde_derive;
+/// # extern crate serde_json;
+/// #
+/// # use serde_json::value::RawValue;
+/// #
+/// #[derive(Deserialize)]
+/// struct SomeStruct {
+/// raw_value: Box<RawValue>,
+/// }
+/// #
+/// # fn main() {}
+/// ```
+///
+/// # Note
+///
+/// `RawValue` is only available if serde\_json is built with the `"raw_value"`
+/// feature.
+///
+/// ```toml
+/// [dependencies]
+/// serde_json = { version = "1.0", features = ["raw_value"] }
+/// ```
+#[repr(C)]
+pub struct RawValue {
+ json: str,
+}
+
+impl RawValue {
+ fn from_borrowed(json: &str) -> &Self {
+ unsafe { mem::transmute::<&str, &RawValue>(json) }
+ }
+
+ fn from_owned(json: Box<str>) -> Box<Self> {
+ unsafe { mem::transmute::<Box<str>, Box<RawValue>>(json) }
+ }
+}
+
+impl Clone for Box<RawValue> {
+ fn clone(&self) -> Self {
+ (**self).to_owned()
+ }
+}
+
+impl ToOwned for RawValue {
+ type Owned = Box<RawValue>;
+
+ fn to_owned(&self) -> Self::Owned {
+ RawValue::from_owned(self.json.to_owned().into_boxed_str())
+ }
+}
+
+impl Debug for RawValue {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter
+ .debug_tuple("RawValue")
+ .field(&format_args!("{}", &self.json))
+ .finish()
+ }
+}
+
+impl Display for RawValue {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.write_str(&self.json)
+ }
+}
+
+impl RawValue {
+ /// Access the JSON text underlying a raw value.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// #[macro_use]
+ /// extern crate serde_derive;
+ /// extern crate serde_json;
+ ///
+ /// use serde_json::{Result, value::RawValue};
+ ///
+ /// #[derive(Deserialize)]
+ /// struct Response<'a> {
+ /// code: u32,
+ /// #[serde(borrow)]
+ /// payload: &'a RawValue,
+ /// }
+ ///
+ /// fn process(input: &str) -> Result<()> {
+ /// let response: Response = serde_json::from_str(input)?;
+ ///
+ /// let payload = response.payload.get();
+ /// if payload.starts_with('{') {
+ /// // handle a payload which is a JSON map
+ /// } else {
+ /// // handle any other type
+ /// }
+ ///
+ /// Ok(())
+ /// }
+ ///
+ /// fn main() -> Result<()> {
+ /// process(r#" {"code": 200, "payload": {}} "#)?;
+ /// Ok(())
+ /// }
+ /// ```
+ pub fn get(&self) -> &str {
+ &self.json
+ }
+}
+
+pub const TOKEN: &'static str = "$serde_json::private::RawValue";
+
+impl Serialize for RawValue {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let mut s = serializer.serialize_struct(TOKEN, 1)?;
+ s.serialize_field(TOKEN, &self.json)?;
+ s.end()
+ }
+}
+
+impl<'de: 'a, 'a> Deserialize<'de> for &'a RawValue {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ struct ReferenceVisitor;
+
+ impl<'de> Visitor<'de> for ReferenceVisitor {
+ type Value = &'de RawValue;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ write!(formatter, "any valid JSON value")
+ }
+
+ fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
+ where
+ V: MapAccess<'de>,
+ {
+ let value = visitor.next_key::<RawKey>()?;
+ if value.is_none() {
+ return Err(de::Error::invalid_type(Unexpected::Map, &self));
+ }
+ visitor.next_value_seed(ReferenceFromString)
+ }
+ }
+
+ deserializer.deserialize_newtype_struct(TOKEN, ReferenceVisitor)
+ }
+}
+
+impl<'de> Deserialize<'de> for Box<RawValue> {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ struct BoxedVisitor;
+
+ impl<'de> Visitor<'de> for BoxedVisitor {
+ type Value = Box<RawValue>;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ write!(formatter, "any valid JSON value")
+ }
+
+ fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
+ where
+ V: MapAccess<'de>,
+ {
+ let value = visitor.next_key::<RawKey>()?;
+ if value.is_none() {
+ return Err(de::Error::invalid_type(Unexpected::Map, &self));
+ }
+ visitor.next_value_seed(BoxedFromString)
+ }
+ }
+
+ deserializer.deserialize_newtype_struct(TOKEN, BoxedVisitor)
+ }
+}
+
+struct RawKey;
+
+impl<'de> Deserialize<'de> for RawKey {
+ fn deserialize<D>(deserializer: D) -> Result<RawKey, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ struct FieldVisitor;
+
+ impl<'de> Visitor<'de> for FieldVisitor {
+ type Value = ();
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("raw value")
+ }
+
+ fn visit_str<E>(self, s: &str) -> Result<(), E>
+ where
+ E: de::Error,
+ {
+ if s == TOKEN {
+ Ok(())
+ } else {
+ Err(de::Error::custom("unexpected raw value"))
+ }
+ }
+ }
+
+ deserializer.deserialize_identifier(FieldVisitor)?;
+ Ok(RawKey)
+ }
+}
+
+pub struct ReferenceFromString;
+
+impl<'de> DeserializeSeed<'de> for ReferenceFromString {
+ type Value = &'de RawValue;
+
+ fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ deserializer.deserialize_str(self)
+ }
+}
+
+impl<'de> Visitor<'de> for ReferenceFromString {
+ type Value = &'de RawValue;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("raw value")
+ }
+
+ fn visit_borrowed_str<E>(self, s: &'de str) -> Result<Self::Value, E>
+ where
+ E: de::Error,
+ {
+ Ok(RawValue::from_borrowed(s))
+ }
+}
+
+pub struct BoxedFromString;
+
+impl<'de> DeserializeSeed<'de> for BoxedFromString {
+ type Value = Box<RawValue>;
+
+ fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ deserializer.deserialize_str(self)
+ }
+}
+
+impl<'de> Visitor<'de> for BoxedFromString {
+ type Value = Box<RawValue>;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("raw value")
+ }
+
+ fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
+ where
+ E: de::Error,
+ {
+ self.visit_string(s.to_owned())
+ }
+
+ fn visit_string<E>(self, s: String) -> Result<Self::Value, E>
+ where
+ E: de::Error,
+ {
+ Ok(RawValue::from_owned(s.into_boxed_str()))
+ }
+}
+
+struct RawKeyDeserializer;
+
+impl<'de> Deserializer<'de> for RawKeyDeserializer {
+ type Error = Error;
+
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
+ where
+ V: de::Visitor<'de>,
+ {
+ visitor.visit_borrowed_str(TOKEN)
+ }
+
+ forward_to_deserialize_any! {
+ bool u8 u16 u32 u64 u128 i8 i16 i32 i64 i128 f32 f64 char str string seq
+ bytes byte_buf map struct option unit newtype_struct ignored_any
+ unit_struct tuple_struct tuple enum identifier
+ }
+}
+
+pub struct OwnedRawDeserializer {
+ pub raw_value: Option<String>,
+}
+
+impl<'de> MapAccess<'de> for OwnedRawDeserializer {
+ type Error = Error;
+
+ fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
+ where
+ K: de::DeserializeSeed<'de>,
+ {
+ if self.raw_value.is_none() {
+ return Ok(None);
+ }
+ seed.deserialize(RawKeyDeserializer).map(Some)
+ }
+
+ fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
+ where
+ V: de::DeserializeSeed<'de>,
+ {
+ seed.deserialize(self.raw_value.take().unwrap().into_deserializer())
+ }
+}
+
+pub struct BorrowedRawDeserializer<'de> {
+ pub raw_value: Option<&'de str>,
+}
+
+impl<'de> MapAccess<'de> for BorrowedRawDeserializer<'de> {
+ type Error = Error;
+
+ fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
+ where
+ K: de::DeserializeSeed<'de>,
+ {
+ if self.raw_value.is_none() {
+ return Ok(None);
+ }
+ seed.deserialize(RawKeyDeserializer).map(Some)
+ }
+
+ fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
+ where
+ V: de::DeserializeSeed<'de>,
+ {
+ seed.deserialize(BorrowedStrDeserializer::new(self.raw_value.take().unwrap()))
+ }
+}
diff --git a/src/read.rs b/src/read.rs
index f2cc9f93b..fba1dd9f9 100644
--- a/src/read.rs
+++ b/src/read.rs
@@ -9,9 +9,15 @@
use std::ops::Deref;
use std::{char, cmp, io, str};
+#[cfg(feature = "raw_value")]
+use serde::de::Visitor;
+
use iter::LineColIterator;
-use super::error::{Error, ErrorCode, Result};
+use error::{Error, ErrorCode, Result};
+
+#[cfg(feature = "raw_value")]
+use raw::{BorrowedRawDeserializer, OwnedRawDeserializer};
/// Trait used by the deserializer for iterating over input. This is manually
/// "specialized" for iterating over &[u8]. Once feature(specialization) is
@@ -76,6 +82,21 @@ pub trait Read<'de>: private::Sealed {
/// string until the next quotation mark but discards the data.
#[doc(hidden)]
fn ignore_str(&mut self) -> Result<()>;
+
+ /// Switch raw buffering mode on.
+ ///
+ /// This is used when deserializing `RawValue`.
+ #[cfg(feature = "raw_value")]
+ #[doc(hidden)]
+ fn begin_raw_buffering(&mut self);
+
+ /// Switch raw buffering mode off and provides the raw buffered data to the
+ /// given visitor.
+ #[cfg(feature = "raw_value")]
+ #[doc(hidden)]
+ fn end_raw_buffering<V>(&mut self, visitor: V) -> Result<V::Value>
+ where
+ V: Visitor<'de>;
}
pub struct Position {
@@ -107,6 +128,8 @@ where
iter: LineColIterator<io::Bytes<R>>,
/// Temporary storage of peeked byte.
ch: Option<u8>,
+ #[cfg(feature = "raw_value")]
+ raw_buffer: Option<Vec<u8>>,
}
/// JSON input source that reads from a slice of bytes.
@@ -117,6 +140,8 @@ pub struct SliceRead<'a> {
slice: &'a [u8],
/// Index of the *next* byte that will be returned by next() or peek().
index: usize,
+ #[cfg(feature = "raw_value")]
+ raw_buffering_start_index: usize,
}
/// JSON input source that reads from a UTF-8 string.
@@ -124,6 +149,8 @@ pub struct SliceRead<'a> {
// Able to elide UTF-8 checks by assuming that the input is valid UTF-8.
pub struct StrRead<'a> {
delegate: SliceRead<'a>,
+ #[cfg(feature = "raw_value")]
+ data: &'a str,
}
// Prevent users from implementing the Read trait.
@@ -139,9 +166,20 @@ where
{
/// Create a JSON input source to read from a std::io input stream.
pub fn new(reader: R) -> Self {
- IoRead {
- iter: LineColIterator::new(reader.bytes()),
- ch: None,
+ #[cfg(not(feature = "raw_value"))]
+ {
+ IoRead {
+ iter: LineColIterator::new(reader.bytes()),
+ ch: None,
+ }
+ }
+ #[cfg(feature = "raw_value")]
+ {
+ IoRead {
+ iter: LineColIterator::new(reader.bytes()),
+ ch: None,
+ raw_buffer: None,
+ }
}
}
}
@@ -193,10 +231,26 @@ where
#[inline]
fn next(&mut self) -> io::Result<Option<u8>> {
match self.ch.take() {
- Some(ch) => Ok(Some(ch)),
+ Some(ch) => {
+ #[cfg(feature = "raw_value")]
+ {
+ if let Some(ref mut buf) = self.raw_buffer {
+ buf.push(ch);
+ }
+ }
+ Ok(Some(ch))
+ }
None => match self.iter.next() {
Some(Err(err)) => Err(err),
- Some(Ok(ch)) => Ok(Some(ch)),
+ Some(Ok(ch)) => {
+ #[cfg(feature = "raw_value")]
+ {
+ if let Some(ref mut buf) = self.raw_buffer {
+ buf.push(ch);
+ }
+ }
+ Ok(Some(ch))
+ }
None => Ok(None),
},
}
@@ -217,11 +271,21 @@ where
}
}
+ #[cfg(not(feature = "raw_value"))]
#[inline]
fn discard(&mut self) {
self.ch = None;
}
+ #[cfg(feature = "raw_value")]
+ fn discard(&mut self) {
+ if let Some(ch) = self.ch.take() {
+ if let Some(ref mut buf) = self.raw_buffer {
+ buf.push(ch);
+ }
+ }
+ }
+
fn position(&self) -> Position {
Position {
line: self.iter.line(),
@@ -274,6 +338,21 @@ where
}
}
}
+
+ #[cfg(feature = "raw_value")]
+ fn begin_raw_buffering(&mut self) {
+ self.raw_buffer = Some(Vec::new());
+ }
+
+ #[cfg(feature = "raw_value")]
+ fn end_raw_buffering<V>(&mut self, visitor: V) -> Result<V::Value>
+ where
+ V: Visitor<'de>,
+ {
+ let raw = self.raw_buffer.take().unwrap();
+ let raw = String::from_utf8(raw).unwrap();
+ visitor.visit_map(OwnedRawDeserializer { raw_value: Some(raw) })
+ }
}
//////////////////////////////////////////////////////////////////////////////
@@ -281,9 +360,20 @@ where
impl<'a> SliceRead<'a> {
/// Create a JSON input source to read from a slice of bytes.
pub fn new(slice: &'a [u8]) -> Self {
- SliceRead {
- slice: slice,
- index: 0,
+ #[cfg(not(feature = "raw_value"))]
+ {
+ SliceRead {
+ slice: slice,
+ index: 0,
+ }
+ }
+ #[cfg(feature = "raw_value")]
+ {
+ SliceRead {
+ slice: slice,
+ index: 0,
+ raw_buffering_start_index: 0,
+ }
}
}
@@ -437,6 +527,21 @@ impl<'a> Read<'a> for SliceRead<'a> {
}
}
}
+
+ #[cfg(feature = "raw_value")]
+ fn begin_raw_buffering(&mut self) {
+ self.raw_buffering_start_index = self.index;
+ }
+
+ #[cfg(feature = "raw_value")]
+ fn end_raw_buffering<V>(&mut self, visitor: V) -> Result<V::Value>
+ where
+ V: Visitor<'a>,
+ {
+ let raw = &self.slice[self.raw_buffering_start_index..self.index];
+ let raw = str::from_utf8(raw).unwrap();
+ visitor.visit_map(BorrowedRawDeserializer { raw_value: Some(raw) })
+ }
}
//////////////////////////////////////////////////////////////////////////////
@@ -444,8 +549,18 @@ impl<'a> Read<'a> for SliceRead<'a> {
impl<'a> StrRead<'a> {
/// Create a JSON input source to read from a UTF-8 string.
pub fn new(s: &'a str) -> Self {
- StrRead {
- delegate: SliceRead::new(s.as_bytes()),
+ #[cfg(not(feature = "raw_value"))]
+ {
+ StrRead {
+ delegate: SliceRead::new(s.as_bytes()),
+ }
+ }
+ #[cfg(feature = "raw_value")]
+ {
+ StrRead {
+ delegate: SliceRead::new(s.as_bytes()),
+ data: s,
+ }
}
}
}
@@ -498,6 +613,20 @@ impl<'a> Read<'a> for StrRead<'a> {
fn ignore_str(&mut self) -> Result<()> {
self.delegate.ignore_str()
}
+
+ #[cfg(feature = "raw_value")]
+ fn begin_raw_buffering(&mut self) {
+ self.delegate.begin_raw_buffering()
+ }
+
+ #[cfg(feature = "raw_value")]
+ fn end_raw_buffering<V>(&mut self, visitor: V) -> Result<V::Value>
+ where
+ V: Visitor<'a>,
+ {
+ let raw = &self.data[self.delegate.raw_buffering_start_index..self.delegate.index];
+ visitor.visit_map(BorrowedRawDeserializer { raw_value: Some(raw) })
+ }
}
//////////////////////////////////////////////////////////////////////////////
diff --git a/src/ser.rs b/src/ser.rs
index ca9b637ee..eceb4e6b4 100644
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -14,14 +14,11 @@ use std::num::FpCategory;
use std::str;
use super::error::{Error, ErrorCode, Result};
-use serde::ser::{self, Impossible};
+use serde::ser::{self, Impossible, Serialize};
use itoa;
use ryu;
-#[cfg(feature = "arbitrary_precision")]
-use serde::Serialize;
-
/// A structure for serializing Rust values into JSON.
pub struct Serializer<W, F = CompactFormatter> {
writer: W,
@@ -288,7 +285,7 @@ where
#[inline]
fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<()>
where
- T: ser::Serialize,
+ T: Serialize,
{
value.serialize(self)
}
@@ -302,7 +299,7 @@ where
value: &T,
) -> Result<()>
where
- T: ser::Serialize,
+ T: Serialize,
{
try!(
self.formatter
@@ -347,7 +344,7 @@ where
#[inline]
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<()>
where
- T: ser::Serialize,
+ T: Serialize,
{
value.serialize(self)
}
@@ -462,7 +459,9 @@ where
fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
match name {
#[cfg(feature = "arbitrary_precision")]
- ::number::SERDE_STRUCT_NAME => Ok(Compound::Number { ser: self }),
+ ::number::TOKEN => Ok(Compound::Number { ser: self }),
+ #[cfg(feature = "raw_value")]
+ ::raw::TOKEN => Ok(Compound::RawValue { ser: self }),
_ => self.serialize_map(Some(len)),
}
}
@@ -573,6 +572,8 @@ pub enum Compound<'a, W: 'a, F: 'a> {
},
#[cfg(feature = "arbitrary_precision")]
Number { ser: &'a mut Serializer<W, F> },
+ #[cfg(feature = "raw_value")]
+ RawValue { ser: &'a mut Serializer<W, F> },
}
impl<'a, W, F> ser::SerializeSeq for Compound<'a, W, F>
@@ -586,7 +587,7 @@ where
#[inline]
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
where
- T: ser::Serialize,
+ T: Serialize,
{
match *self {
Compound::Map {
@@ -609,6 +610,8 @@ where
}
#[cfg(feature = "arbitrary_precision")]
Compound::Number { .. } => unreachable!(),
+ #[cfg(feature = "raw_value")]
+ Compound::RawValue { .. } => unreachable!(),
}
}
@@ -624,6 +627,8 @@ where
}
#[cfg(feature = "arbitrary_precision")]
Compound::Number { .. } => unreachable!(),
+ #[cfg(feature = "raw_value")]
+ Compound::RawValue { .. } => unreachable!(),
}
}
}
@@ -639,7 +644,7 @@ where
#[inline]
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
where
- T: ser::Serialize,
+ T: Serialize,
{
ser::SerializeSeq::serialize_element(self, value)
}
@@ -661,7 +666,7 @@ where
#[inline]
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
where
- T: ser::Serialize,
+ T: Serialize,
{
ser::SerializeSeq::serialize_element(self, value)
}
@@ -683,7 +688,7 @@ where
#[inline]
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
where
- T: ser::Serialize,
+ T: Serialize,
{
ser::SerializeSeq::serialize_element(self, value)
}
@@ -706,6 +711,8 @@ where
}
#[cfg(feature = "arbitrary_precision")]
Compound::Number { .. } => unreachable!(),
+ #[cfg(feature = "raw_value")]
+ Compound::RawValue { .. } => unreachable!(),
}
}
}
@@ -721,7 +728,7 @@ where
#[inline]
fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<()>
where
- T: ser::Serialize,
+ T: Serialize,
{
match *self {
Compound::Map {
@@ -746,13 +753,15 @@ where
}
#[cfg(feature = "arbitrary_precision")]
Compound::Number { .. } => unreachable!(),
+ #[cfg(feature = "raw_value")]
+ Compound::RawValue { .. } => unreachable!(),
}
}
#[inline]
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<()>
where
- T: ser::Serialize,
+ T: Serialize,
{
match *self {
Compound::Map { ref mut ser, .. } => {
@@ -771,6 +780,8 @@ where
}
#[cfg(feature = "arbitrary_precision")]
Compound::Number { .. } => unreachable!(),
+ #[cfg(feature = "raw_value")]
+ Compound::RawValue { .. } => unreachable!(),
}
}
@@ -786,6 +797,8 @@ where
}
#[cfg(feature = "arbitrary_precision")]
Compound::Number { .. } => unreachable!(),
+ #[cfg(feature = "raw_value")]
+ Compound::RawValue { .. } => unreachable!(),
}
}
}
@@ -801,7 +814,7 @@ where
#[inline]
fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()>
where
- T: ser::Serialize,
+ T: Serialize,
{
match *self {
Compound::Map { .. } => {
@@ -810,13 +823,22 @@ where
}
#[cfg(feature = "arbitrary_precision")]
Compound::Number { ref mut ser, .. } => {
- if key == ::number::SERDE_STRUCT_FIELD_NAME {
+ if key == ::number::TOKEN {
try!(value.serialize(NumberStrEmitter(&mut *ser)));
Ok(())
} else {
Err(invalid_number())
}
}
+ #[cfg(feature = "raw_value")]
+ Compound::RawValue { ref mut ser, .. } => {
+ if key == ::raw::TOKEN {
+ try!(value.serialize(RawValueStrEmitter(&mut *ser)));
+ Ok(())
+ } else {
+ Err(invalid_raw_value())
+ }
+ }
}
}
@@ -826,6 +848,8 @@ where
Compound::Map { .. } => ser::SerializeMap::end(self),
#[cfg(feature = "arbitrary_precision")]
Compound::Number { .. } => Ok(()),
+ #[cfg(feature = "raw_value")]
+ Compound::RawValue { .. } => Ok(()),
}
}
}
@@ -841,12 +865,14 @@ where
#[inline]
fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()>
where
- T: ser::Serialize,
+ T: Serialize,
{
match *self {
Compound::Map { .. } => ser::SerializeStruct::serialize_field(self, key, value),
#[cfg(feature = "arbitrary_precision")]
Compound::Number { .. } => unreachable!(),
+ #[cfg(feature = "raw_value")]
+ Compound::RawValue { .. } => unreachable!(),
}
}
@@ -868,6 +894,8 @@ where
}
#[cfg(feature = "arbitrary_precision")]
Compound::Number { .. } => unreachable!(),
+ #[cfg(feature = "raw_value")]
+ Compound::RawValue { .. } => unreachable!(),
}
}
}
@@ -881,6 +909,11 @@ fn invalid_number() -> Error {
Error::syntax(ErrorCode::InvalidNumber, 0, 0)
}
+#[cfg(feature = "raw_value")]
+fn invalid_raw_value() -> Error {
+ Error::syntax(ErrorCode::ExpectedSomeValue, 0, 0)
+}
+
fn key_must_be_a_string() -> Error {
Error::syntax(ErrorCode::KeyMustBeAString, 0, 0)
}
@@ -911,7 +944,7 @@ where
#[inline]
fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<()>
where
- T: ser::Serialize,
+ T: Serialize,
{
value.serialize(self)
}
@@ -1154,7 +1187,7 @@ where
_value: &T,
) -> Result<()>
where
- T: ser::Serialize,
+ T: Serialize,
{
Err(key_must_be_a_string())
}
@@ -1165,7 +1198,7 @@ where
fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<()>
where
- T: ser::Serialize,
+ T: Serialize,
{
Err(key_must_be_a_string())
}
@@ -1400,6 +1433,191 @@ impl<'a, W: io::Write, F: Formatter> ser::Serializer for NumberStrEmitter<'a, W,
}
}
+#[cfg(feature = "raw_value")]
+struct RawValueStrEmitter<'a, W: 'a + io::Write, F: 'a + Formatter>(&'a mut Serializer<W, F>);
+
+#[cfg(feature = "raw_value")]
+impl<'a, W: io::Write, F: Formatter> ser::Serializer for RawValueStrEmitter<'a, W, F> {
+ type Ok = ();
+ type Error = Error;
+
+ type SerializeSeq = Impossible<(), Error>;
+ type SerializeTuple = Impossible<(), Error>;
+ type SerializeTupleStruct = Impossible<(), Error>;
+ type SerializeTupleVariant = Impossible<(), Error>;
+ type SerializeMap = Impossible<(), Error>;
+ type SerializeStruct = Impossible<(), Error>;
+ type SerializeStructVariant = Impossible<(), Error>;
+
+ fn serialize_bool(self, _v: bool) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_i8(self, _v: i8) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_i16(self, _v: i16) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_i32(self, _v: i32) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_i64(self, _v: i64) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ serde_if_integer128! {
+ fn serialize_i128(self, _v: i128) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+ }
+
+ fn serialize_u8(self, _v: u8) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_u16(self, _v: u16) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_u32(self, _v: u32) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_u64(self, _v: u64) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ serde_if_integer128! {
+ fn serialize_u128(self, _v: u128) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+ }
+
+ fn serialize_f32(self, _v: f32) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_f64(self, _v: f64) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_char(self, _v: char) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_str(self, value: &str) -> Result<Self::Ok> {
+ let RawValueStrEmitter(serializer) = self;
+ serializer
+ .formatter
+ .write_raw_fragment(&mut serializer.writer, value)
+ .map_err(Error::io)
+ }
+
+ fn serialize_bytes(self, _value: &[u8]) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_none(self) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<Self::Ok>
+ where
+ T: Serialize,
+ {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_unit(self) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_unit_variant(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ _variant: &'static str,
+ ) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_newtype_struct<T: ?Sized>(
+ self,
+ _name: &'static str,
+ _value: &T,
+ ) -> Result<Self::Ok>
+ where
+ T: Serialize,
+ {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_newtype_variant<T: ?Sized>(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ _variant: &'static str,
+ _value: &T,
+ ) -> Result<Self::Ok>
+ where
+ T: Serialize,
+ {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_tuple_struct(
+ self,
+ _name: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeTupleStruct> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_tuple_variant(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ _variant: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeTupleVariant> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_struct_variant(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ _variant: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeStructVariant> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+}
+
/// Represents a character escape code in a type-safe manner.
pub enum CharEscape {
/// An escaped quote `"`
@@ -1743,6 +1961,16 @@ pub trait Formatter {
{
Ok(())
}
+
+ /// Writes a raw JSON fragment that doesn't need any escaping to the
+ /// specified writer.
+ #[inline]
+ fn write_raw_fragment<W: ?Sized>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()>
+ where
+ W: io::Write,
+ {
+ writer.write_all(fragment.as_bytes())
+ }
}
/// This structure compacts a JSON value with no extra whitespace.
@@ -1979,7 +2207,7 @@ static ESCAPE: [u8; 256] = [
pub fn to_writer<W, T: ?Sized>(writer: W, value: &T) -> Result<()>
where
W: io::Write,
- T: ser::Serialize,
+ T: Serialize,
{
let mut ser = Serializer::new(writer);
try!(value.serialize(&mut ser));
@@ -1997,7 +2225,7 @@ where
pub fn to_writer_pretty<W, T: ?Sized>(writer: W, value: &T) -> Result<()>
where
W: io::Write,
- T: ser::Serialize,
+ T: Serialize,
{
let mut ser = Serializer::pretty(writer);
try!(value.serialize(&mut ser));
@@ -2013,7 +2241,7 @@ where
#[inline]
pub fn to_vec<T: ?Sized>(value: &T) -> Result<Vec<u8>>
where
- T: ser::Serialize,
+ T: Serialize,
{
let mut writer = Vec::with_capacity(128);
try!(to_writer(&mut writer, value));
@@ -2029,7 +2257,7 @@ where
#[inline]
pub fn to_vec_pretty<T: ?Sized>(value: &T) -> Result<Vec<u8>>
where
- T: ser::Serialize,
+ T: Serialize,
{
let mut writer = Vec::with_capacity(128);
try!(to_writer_pretty(&mut writer, value));
@@ -2045,7 +2273,7 @@ where
#[inline]
pub fn to_string<T: ?Sized>(value: &T) -> Result<String>
where
- T: ser::Serialize,
+ T: Serialize,
{
let vec = try!(to_vec(value));
let string = unsafe {
@@ -2064,7 +2292,7 @@ where
#[inline]
pub fn to_string_pretty<T: ?Sized>(value: &T) -> Result<String>
where
- T: ser::Serialize,
+ T: Serialize,
{
let vec = try!(to_vec_pretty(value));
let string = unsafe {
diff --git a/src/value/de.rs b/src/value/de.rs
index dc8dbc6be..ba99840c5 100644
--- a/src/value/de.rs
+++ b/src/value/de.rs
@@ -116,7 +116,12 @@ impl<'de> Deserialize<'de> for Value {
#[cfg(feature = "arbitrary_precision")]
Some(KeyClass::Number) => {
let number: NumberFromString = visitor.next_value()?;
- return Ok(Value::Number(number.value));
+ Ok(Value::Number(number.value))
+ }
+ #[cfg(feature = "raw_value")]
+ Some(KeyClass::RawValue) => {
+ let value = visitor.next_value_seed(::raw::BoxedFromString)?;
+ ::from_str(value.get()).map_err(de::Error::custom)
}
Some(KeyClass::Map(first_key)) => {
let mut values = Map::new();
@@ -300,12 +305,22 @@ impl<'de> serde::Deserializer<'de> for Value {
#[inline]
fn deserialize_newtype_struct<V>(
self,
- _name: &'static str,
+ name: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
+ #[cfg(feature = "raw_value")]
+ {
+ if name == ::raw::TOKEN {
+ return visitor.visit_map(::raw::OwnedRawDeserializer {
+ raw_value: Some(self.to_string()),
+ });
+ }
+ }
+
+ let _ = name;
visitor.visit_newtype_struct(self)
}
@@ -829,12 +844,22 @@ impl<'de> serde::Deserializer<'de> for &'de Value {
#[inline]
fn deserialize_newtype_struct<V>(
self,
- _name: &'static str,
+ name: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
+ #[cfg(feature = "raw_value")]
+ {
+ if name == ::raw::TOKEN {
+ return visitor.visit_map(::raw::OwnedRawDeserializer {
+ raw_value: Some(self.to_string()),
+ });
+ }
+ }
+
+ let _ = name;
visitor.visit_newtype_struct(self)
}
@@ -1292,6 +1317,8 @@ enum KeyClass {
Map(String),
#[cfg(feature = "arbitrary_precision")]
Number,
+ #[cfg(feature = "raw_value")]
+ RawValue,
}
impl<'de> DeserializeSeed<'de> for KeyClassifier {
@@ -1318,7 +1345,9 @@ impl<'de> Visitor<'de> for KeyClassifier {
{
match s {
#[cfg(feature = "arbitrary_precision")]
- ::number::SERDE_STRUCT_FIELD_NAME => Ok(KeyClass::Number),
+ ::number::TOKEN => Ok(KeyClass::Number),
+ #[cfg(feature = "raw_value")]
+ ::raw::TOKEN => Ok(KeyClass::RawValue),
_ => Ok(KeyClass::Map(s.to_owned())),
}
}
@@ -1329,7 +1358,9 @@ impl<'de> Visitor<'de> for KeyClassifier {
{
match s.as_str() {
#[cfg(feature = "arbitrary_precision")]
- ::number::SERDE_STRUCT_FIELD_NAME => Ok(KeyClass::Number),
+ ::number::TOKEN => Ok(KeyClass::Number),
+ #[cfg(feature = "raw_value")]
+ ::raw::TOKEN => Ok(KeyClass::RawValue),
_ => Ok(KeyClass::Map(s)),
}
}
diff --git a/src/value/mod.rs b/src/value/mod.rs
index f5e33b457..c976af501 100644
--- a/src/value/mod.rs
+++ b/src/value/mod.rs
@@ -119,6 +119,9 @@ use error::Error;
pub use map::Map;
pub use number::Number;
+#[cfg(feature = "raw_value")]
+pub use raw::RawValue;
+
pub use self::index::Index;
use self::ser::Serializer;
diff --git a/src/value/ser.rs b/src/value/ser.rs
index d3f71b373..172784cce 100644
--- a/src/value/ser.rs
+++ b/src/value/ser.rs
@@ -14,9 +14,6 @@ use map::Map;
use number::Number;
use value::{to_value, Value};
-#[cfg(feature = "arbitrary_precision")]
-use serde::ser;
-
impl Serialize for Value {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
@@ -232,7 +229,9 @@ impl serde::Serializer for Serializer {
) -> Result<Self::SerializeStruct, Error> {
match name {
#[cfg(feature = "arbitrary_precision")]
- ::number::SERDE_STRUCT_NAME => Ok(SerializeMap::Number { out_value: None }),
+ ::number::TOKEN => Ok(SerializeMap::Number { out_value: None }),
+ #[cfg(feature = "raw_value")]
+ ::raw::TOKEN => Ok(SerializeMap::RawValue { out_value: None }),
_ => self.serialize_map(Some(len)),
}
}
@@ -267,6 +266,8 @@ pub enum SerializeMap {
},
#[cfg(feature = "arbitrary_precision")]
Number { out_value: Option<Value> },
+ #[cfg(feature = "raw_value")]
+ RawValue { out_value: Option<Value> },
}
pub struct SerializeStructVariant {
@@ -361,6 +362,8 @@ impl serde::ser::SerializeMap for SerializeMap {
}
#[cfg(feature = "arbitrary_precision")]
SerializeMap::Number { .. } => unreachable!(),
+ #[cfg(feature = "raw_value")]
+ SerializeMap::RawValue { .. } => unreachable!(),
}
}
@@ -382,6 +385,8 @@ impl serde::ser::SerializeMap for SerializeMap {
}
#[cfg(feature = "arbitrary_precision")]
SerializeMap::Number { .. } => unreachable!(),
+ #[cfg(feature = "raw_value")]
+ SerializeMap::RawValue { .. } => unreachable!(),
}
}
@@ -390,6 +395,8 @@ impl serde::ser::SerializeMap for SerializeMap {
SerializeMap::Map { map, .. } => Ok(Value::Object(map)),
#[cfg(feature = "arbitrary_precision")]
SerializeMap::Number { .. } => unreachable!(),
+ #[cfg(feature = "raw_value")]
+ SerializeMap::RawValue { .. } => unreachable!(),
}
}
}
@@ -592,13 +599,22 @@ impl serde::ser::SerializeStruct for SerializeMap {
}
#[cfg(feature = "arbitrary_precision")]
SerializeMap::Number { ref mut out_value } => {
- if key == ::number::SERDE_STRUCT_FIELD_NAME {
+ if key == ::number::TOKEN {
*out_value = Some(value.serialize(NumberValueEmitter)?);
Ok(())
} else {
Err(invalid_number())
}
}
+ #[cfg(feature = "raw_value")]
+ SerializeMap::RawValue { ref mut out_value } => {
+ if key == ::raw::TOKEN {
+ *out_value = Some(value.serialize(RawValueEmitter)?);
+ Ok(())
+ } else {
+ Err(invalid_raw_value())
+ }
+ }
}
}
@@ -609,6 +625,10 @@ impl serde::ser::SerializeStruct for SerializeMap {
SerializeMap::Number { out_value, .. } => {
Ok(out_value.expect("number value was not emitted"))
}
+ #[cfg(feature = "raw_value")]
+ SerializeMap::RawValue { out_value, .. } => {
+ Ok(out_value.expect("raw value was not emitted"))
+ }
}
}
}
@@ -643,7 +663,7 @@ fn invalid_number() -> Error {
}
#[cfg(feature = "arbitrary_precision")]
-impl ser::Serializer for NumberValueEmitter {
+impl serde::ser::Serializer for NumberValueEmitter {
type Ok = Value;
type Error = Error;
@@ -812,3 +832,181 @@ impl ser::Serializer for NumberValueEmitter {
Err(invalid_number())
}
}
+
+#[cfg(feature = "raw_value")]
+struct RawValueEmitter;
+
+#[cfg(feature = "raw_value")]
+fn invalid_raw_value() -> Error {
+ Error::syntax(ErrorCode::ExpectedSomeValue, 0, 0)
+}
+
+#[cfg(feature = "raw_value")]
+impl serde::ser::Serializer for RawValueEmitter {
+ type Ok = Value;
+ type Error = Error;
+
+ type SerializeSeq = Impossible<Value, Error>;
+ type SerializeTuple = Impossible<Value, Error>;
+ type SerializeTupleStruct = Impossible<Value, Error>;
+ type SerializeTupleVariant = Impossible<Value, Error>;
+ type SerializeMap = Impossible<Value, Error>;
+ type SerializeStruct = Impossible<Value, Error>;
+ type SerializeStructVariant = Impossible<Value, Error>;
+
+ fn serialize_bool(self, _v: bool) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_i8(self, _v: i8) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_i16(self, _v: i16) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_i32(self, _v: i32) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_i64(self, _v: i64) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_u8(self, _v: u8) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_u16(self, _v: u16) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_u32(self, _v: u32) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_u64(self, _v: u64) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_f32(self, _v: f32) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_f64(self, _v: f64) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_char(self, _v: char) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error> {
+ ::from_str(value)
+ }
+
+ fn serialize_bytes(self, _value: &[u8]) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<Self::Ok, Self::Error>
+ where
+ T: Serialize,
+ {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_unit_variant(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ _variant: &'static str,
+ ) -> Result<Self::Ok, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_newtype_struct<T: ?Sized>(
+ self,
+ _name: &'static str,
+ _value: &T,
+ ) -> Result<Self::Ok, Self::Error>
+ where
+ T: Serialize,
+ {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_newtype_variant<T: ?Sized>(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ _variant: &'static str,
+ _value: &T,
+ ) -> Result<Self::Ok, Self::Error>
+ where
+ T: Serialize,
+ {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_tuple_struct(
+ self,
+ _name: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeTupleStruct, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_tuple_variant(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ _variant: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeTupleVariant, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_struct(
+ self,
+ _name: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeStruct, Self::Error> {
+ Err(invalid_raw_value())
+ }
+
+ fn serialize_struct_variant(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ _variant: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeStructVariant, Self::Error> {
+ Err(invalid_raw_value())
+ }
+}
|
diff --git a/tests/test.rs b/tests/test.rs
index 08d038837..ec2de425e 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -938,9 +938,9 @@ fn test_serialize_char() {
#[test]
fn test_malicious_number() {
#[derive(Serialize)]
- #[serde(rename = "$__serde_private_Number")]
+ #[serde(rename = "$serde_json::private::Number")]
struct S {
- #[serde(rename = "$__serde_private_number")]
+ #[serde(rename = "$serde_json::private::Number")]
f: &'static str,
}
@@ -2039,3 +2039,88 @@ fn test_integer128() {
),
]);
}
+
+#[cfg(feature = "raw_value")]
+#[test]
+fn test_borrowed_raw_value() {
+ use serde_json::value::RawValue;
+
+ #[derive(Serialize, Deserialize)]
+ struct Wrapper<'a> {
+ a: i8,
+ #[serde(borrow)]
+ b: &'a RawValue,
+ c: i8,
+ };
+
+ let wrapper_from_str: Wrapper =
+ serde_json::from_str(r#"{"a": 1, "b": {"foo": 2}, "c": 3}"#).unwrap();
+ assert_eq!(r#"{"foo": 2}"#, wrapper_from_str.b.get());
+
+ let wrapper_to_string = serde_json::to_string(&wrapper_from_str).unwrap();
+ assert_eq!(r#"{"a":1,"b":{"foo": 2},"c":3}"#, wrapper_to_string);
+
+ let wrapper_to_value = serde_json::to_value(&wrapper_from_str).unwrap();
+ assert_eq!(json!({"a": 1, "b": {"foo": 2}, "c": 3}), wrapper_to_value);
+
+ let array_from_str: Vec<&RawValue> =
+ serde_json::from_str(r#"["a", 42, {"foo": "bar"}, null]"#).unwrap();
+ assert_eq!(r#""a""#, array_from_str[0].get());
+ assert_eq!(r#"42"#, array_from_str[1].get());
+ assert_eq!(r#"{"foo": "bar"}"#, array_from_str[2].get());
+ assert_eq!(r#"null"#, array_from_str[3].get());
+
+ let array_to_string = serde_json::to_string(&array_from_str).unwrap();
+ assert_eq!(r#"["a",42,{"foo": "bar"},null]"#, array_to_string);
+}
+
+#[cfg(feature = "raw_value")]
+#[test]
+fn test_boxed_raw_value() {
+ use serde_json::value::RawValue;
+
+ #[derive(Serialize, Deserialize)]
+ struct Wrapper {
+ a: i8,
+ b: Box<RawValue>,
+ c: i8,
+ };
+
+ let wrapper_from_str: Wrapper =
+ serde_json::from_str(r#"{"a": 1, "b": {"foo": 2}, "c": 3}"#).unwrap();
+ assert_eq!(r#"{"foo": 2}"#, wrapper_from_str.b.get());
+
+ let wrapper_from_reader: Wrapper = serde_json::from_reader(
+ br#"{"a": 1, "b": {"foo": 2}, "c": 3}"#.as_ref(),
+ ).unwrap();
+ assert_eq!(r#"{"foo": 2}"#, wrapper_from_reader.b.get());
+
+ let wrapper_from_value: Wrapper =
+ serde_json::from_value(json!({"a": 1, "b": {"foo": 2}, "c": 3}))
+ .unwrap();
+ assert_eq!(r#"{"foo":2}"#, wrapper_from_value.b.get());
+
+ let wrapper_to_string = serde_json::to_string(&wrapper_from_str).unwrap();
+ assert_eq!(r#"{"a":1,"b":{"foo": 2},"c":3}"#, wrapper_to_string);
+
+ let wrapper_to_value = serde_json::to_value(&wrapper_from_str).unwrap();
+ assert_eq!(json!({"a": 1, "b": {"foo": 2}, "c": 3}), wrapper_to_value);
+
+ let array_from_str: Vec<Box<RawValue>> =
+ serde_json::from_str(r#"["a", 42, {"foo": "bar"}, null]"#).unwrap();
+ assert_eq!(r#""a""#, array_from_str[0].get());
+ assert_eq!(r#"42"#, array_from_str[1].get());
+ assert_eq!(r#"{"foo": "bar"}"#, array_from_str[2].get());
+ assert_eq!(r#"null"#, array_from_str[3].get());
+
+ let array_from_reader: Vec<Box<RawValue>> = serde_json::from_reader(
+ br#"["a", 42, {"foo": "bar"}, null]"#.as_ref(),
+ ).unwrap();
+ assert_eq!(r#""a""#, array_from_reader[0].get());
+ assert_eq!(r#"42"#, array_from_reader[1].get());
+ assert_eq!(r#"{"foo": "bar"}"#, array_from_reader[2].get());
+ assert_eq!(r#"null"#, array_from_reader[3].get());
+
+ let array_to_string = serde_json::to_string(&array_from_str).unwrap();
+ assert_eq!(r#"["a",42,{"foo": "bar"},null]"#, array_to_string);
+}
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
1.0
|
serde-rs__json-480
| 480
|
[
"355"
] |
2018-09-14T10:25:28Z
|
@dtolnay mentions that the work happening in #416 might lay some groundwork for such a change to take place.
Yeah, this sounds useful. Ideally we could get some of the building blocks for this sort of thing (custom 'built-in' types) integrated into serde itself, in time.
I need this for a project I'm working on, and would be happy to give it shot following the same approach as #416. Is this something that you'd accept a PR for?
Yes I would like a PR for this. When you say you need this feature, is it because deserializing to serde_json::Value is too slow in your project and you are expecting this to have better performance, or some other reason?
Yeah, I've got an http web server that's backed by a postgres database which stores JSONB values, and would like to shuffle data back and forth (and embed into other payloads) with as few allocations as possible.
As a first step, please put together a short benchmark that you trust as reasonably representative of the shuffling data back and forth piece of your application. Ideally it would depend on serde / serde_derive / serde_json but nothing else -- so no postgres or http stuff. Focus on the data structures so that they have the same ratio and pattern of raw vs meaningful content as your real use case. Write it using serde_json::Value for now, and then the goal will be to swap in a raw value once it's implemented and observe a speedup.
Wrote a small microbenchmark here: https://gist.github.com/srijs/7fe21b43c2cf5d2ceeb593ae4591c6f5
Please let me know if this is what you had in mind!
:+1: looks good, let's make it work.
|
d4612639020d4e744cb755e63430b7f95e566c7a
|
Add a RawValue type
It would be helpful to have a type similar to Go's [`json.RawMessage`](https://golang.org/pkg/encoding/json/#RawMessage) that is not tokenized during deserialization, but rather its raw contents stored as a `Vec<u8>` or `&'de [u8]`.
The following pseudo-code demonstrates the idea.
```rust
#[derive(Deserialize)]
struct Struct {
/// Deserialized normally.
core_data: Vec<i32>,
/// Contents of `user_data` are copied / borrowed directly from the input
/// with no modification.
///
/// `RawValue<'static>` is akin to `Vec<u8>`.
/// `RawValue<'a>` is akin to `&'a [u8]`.
user_data: serde_json::RawValue<'static>,
}
fn main() {
let json = r#"
{
"core_data": [1, 2, 3],
"user_data": { "foo": {}, "bar": 123, "baz": "abc" }
}
"#;
let s: Struct = serde_json::from_bytes(&json).unwrap();
println!("{}", s.user_data); // "{ \"foo\": {}, \"bar\": 123, \"baz\": \"abc\" }"
}
```
The main advantage of this is would be to have 'lazily-deserialized' values.
|
diff --git a/src/de.rs b/src/de.rs
index f1c5c3cff..0ad91a2a8 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -8,6 +8,7 @@
//! Deserialize JSON data to a Rust data structure.
+use std::borrow::Cow;
use std::io;
use std::marker::PhantomData;
use std::result;
@@ -946,6 +947,22 @@ impl<'de, R: Read<'de>> Deserializer<R> {
}
}
}
+
+ fn deserialize_raw_value<V>(&mut self, visitor: V) -> Result<V::Value>
+ where
+ V: de::Visitor<'de>,
+ {
+ if let None = try!(self.parse_whitespace()) {
+ return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
+ }
+
+ self.read.toggle_raw_buffering();
+ de::Deserializer::deserialize_any(&mut *self, de::IgnoredAny)?;
+ match self.read.toggle_raw_buffering().unwrap() {
+ Cow::Owned(byte_buf) => visitor.visit_byte_buf(byte_buf),
+ Cow::Borrowed(bytes) => visitor.visit_borrowed_bytes(bytes),
+ }
+ }
}
impl FromStr for Number {
@@ -1412,10 +1429,14 @@ impl<'de, 'a, R: Read<'de>> de::Deserializer<'de> for &'a mut Deserializer<R> {
/// Parses a newtype struct as the underlying value.
#[inline]
- fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value>
+ fn deserialize_newtype_struct<V>(self, name: &str, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
+ if name == ::raw::SERDE_STRUCT_NAME {
+ return self.deserialize_raw_value(visitor);
+ }
+
visitor.visit_newtype_struct(self)
}
diff --git a/src/lib.rs b/src/lib.rs
index d9b79175e..e0b7a0b77 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -364,7 +364,7 @@ pub use self::ser::{
to_string, to_string_pretty, to_vec, to_vec_pretty, to_writer, to_writer_pretty, Serializer,
};
#[doc(inline)]
-pub use self::value::{from_value, to_value, Map, Number, Value};
+pub use self::value::{from_value, to_value, Map, Number, RawValue, Value};
// We only use our own error type; no need for From conversions provided by the
// standard library's try! macro. This reduces lines of LLVM IR by 4%.
@@ -388,4 +388,5 @@ pub mod value;
mod iter;
mod number;
+mod raw;
mod read;
diff --git a/src/raw.rs b/src/raw.rs
new file mode 100644
index 000000000..74d2c7a00
--- /dev/null
+++ b/src/raw.rs
@@ -0,0 +1,93 @@
+use std::borrow::Cow;
+use std::fmt;
+
+use serde::de::Visitor;
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
+
+/// Represents any valid JSON value as a series of raw bytes.
+///
+/// This type can be used to defer parsing parts of a payload until later,
+/// or to embed it verbatim into another JSON payload.
+///
+/// When serializing, a value of this type will retain its original formatting
+/// and will not be minified or pretty-printed.
+///
+/// When deserializing, this type can not be used with the `#[serde(flatten)]` attribute,
+/// as it relies on the original input buffer.
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct RawValue<'a>(Cow<'a, str>);
+
+impl<'a> AsRef<str> for RawValue<'a> {
+ fn as_ref(&self) -> &str {
+ &self.0
+ }
+}
+
+impl<'a> fmt::Display for RawValue<'a> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+/// Not public API. Should be pub(crate).
+#[doc(hidden)]
+pub const SERDE_STRUCT_NAME: &'static str = "$__serde_private_RawValue";
+
+impl<'a> Serialize for RawValue<'a> {
+ #[inline]
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ serializer.serialize_newtype_struct(SERDE_STRUCT_NAME, &self.0)
+ }
+}
+
+impl<'a, 'de> Deserialize<'de> for RawValue<'a>
+where
+ 'de: 'a,
+{
+ #[inline]
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ struct RawValueVisitor;
+
+ impl<'de> Visitor<'de> for RawValueVisitor {
+ type Value = RawValue<'de>;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ write!(formatter, "a deserializable RawValue")
+ }
+
+ fn visit_string<E>(self, s: String) -> Result<Self::Value, E>
+ where
+ E: ::serde::de::Error,
+ {
+ Ok(RawValue(Cow::Owned(s)))
+ }
+
+ fn visit_byte_buf<E>(self, b: Vec<u8>) -> Result<Self::Value, E>
+ where
+ E: ::serde::de::Error,
+ {
+ String::from_utf8(b)
+ .map(|s| RawValue(Cow::Owned(s)))
+ .map_err(|err| ::serde::de::Error::custom(err))
+ }
+
+ fn visit_borrowed_bytes<E>(self, b: &'de [u8]) -> Result<Self::Value, E>
+ where
+ E: ::serde::de::Error,
+ {
+ ::std::str::from_utf8(b)
+ .map(|s| RawValue(Cow::Borrowed(s)))
+ .map_err(|err| ::serde::de::Error::custom(err))
+ }
+ }
+
+ deserializer.deserialize_newtype_struct(SERDE_STRUCT_NAME, RawValueVisitor)
+ }
+}
diff --git a/src/read.rs b/src/read.rs
index f2cc9f93b..8084f40ba 100644
--- a/src/read.rs
+++ b/src/read.rs
@@ -6,6 +6,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+use std::borrow::Cow;
use std::ops::Deref;
use std::{char, cmp, io, str};
@@ -76,6 +77,13 @@ pub trait Read<'de>: private::Sealed {
/// string until the next quotation mark but discards the data.
#[doc(hidden)]
fn ignore_str(&mut self) -> Result<()>;
+
+ /// Switch raw buffering mode on/off. When switching off, returns a copy-on-write
+ /// buffer with the captured data.
+ ///
+ /// This is used to deserialize `RawValue`.
+ #[doc(hidden)]
+ fn toggle_raw_buffering(&mut self) -> Option<Cow<'de, [u8]>>;
}
pub struct Position {
@@ -107,6 +115,7 @@ where
iter: LineColIterator<io::Bytes<R>>,
/// Temporary storage of peeked byte.
ch: Option<u8>,
+ raw_buffer: Option<Vec<u8>>,
}
/// JSON input source that reads from a slice of bytes.
@@ -117,6 +126,7 @@ pub struct SliceRead<'a> {
slice: &'a [u8],
/// Index of the *next* byte that will be returned by next() or peek().
index: usize,
+ raw_buffering_start_index: Option<usize>,
}
/// JSON input source that reads from a UTF-8 string.
@@ -142,6 +152,7 @@ where
IoRead {
iter: LineColIterator::new(reader.bytes()),
ch: None,
+ raw_buffer: None,
}
}
}
@@ -193,10 +204,20 @@ where
#[inline]
fn next(&mut self) -> io::Result<Option<u8>> {
match self.ch.take() {
- Some(ch) => Ok(Some(ch)),
+ Some(ch) => {
+ if let Some(ref mut buf) = self.raw_buffer {
+ buf.push(ch);
+ }
+ Ok(Some(ch))
+ }
None => match self.iter.next() {
Some(Err(err)) => Err(err),
- Some(Ok(ch)) => Ok(Some(ch)),
+ Some(Ok(ch)) => {
+ if let Some(ref mut buf) = self.raw_buffer {
+ buf.push(ch);
+ }
+ Ok(Some(ch))
+ }
None => Ok(None),
},
}
@@ -219,7 +240,11 @@ where
#[inline]
fn discard(&mut self) {
- self.ch = None;
+ if let Some(ch) = self.ch.take() {
+ if let Some(ref mut buf) = self.raw_buffer {
+ buf.push(ch);
+ }
+ }
}
fn position(&self) -> Position {
@@ -274,6 +299,15 @@ where
}
}
}
+
+ fn toggle_raw_buffering(&mut self) -> Option<Cow<'de, [u8]>> {
+ if let Some(buffer) = self.raw_buffer.take() {
+ Some(Cow::Owned(buffer))
+ } else {
+ self.raw_buffer = Some(Vec::new());
+ None
+ }
+ }
}
//////////////////////////////////////////////////////////////////////////////
@@ -284,6 +318,7 @@ impl<'a> SliceRead<'a> {
SliceRead {
slice: slice,
index: 0,
+ raw_buffering_start_index: None,
}
}
@@ -437,6 +472,15 @@ impl<'a> Read<'a> for SliceRead<'a> {
}
}
}
+
+ fn toggle_raw_buffering(&mut self) -> Option<Cow<'a, [u8]>> {
+ if let Some(start_index) = self.raw_buffering_start_index.take() {
+ Some(Cow::Borrowed(&self.slice[start_index..self.index]))
+ } else {
+ self.raw_buffering_start_index = Some(self.index);
+ None
+ }
+ }
}
//////////////////////////////////////////////////////////////////////////////
@@ -498,6 +542,10 @@ impl<'a> Read<'a> for StrRead<'a> {
fn ignore_str(&mut self) -> Result<()> {
self.delegate.ignore_str()
}
+
+ fn toggle_raw_buffering(&mut self) -> Option<Cow<'a, [u8]>> {
+ self.delegate.toggle_raw_buffering()
+ }
}
//////////////////////////////////////////////////////////////////////////////
diff --git a/src/ser.rs b/src/ser.rs
index ca9b637ee..af53c8cae 100644
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -14,14 +14,11 @@ use std::num::FpCategory;
use std::str;
use super::error::{Error, ErrorCode, Result};
-use serde::ser::{self, Impossible};
+use serde::ser::{self, Impossible, Serialize};
use itoa;
use ryu;
-#[cfg(feature = "arbitrary_precision")]
-use serde::Serialize;
-
/// A structure for serializing Rust values into JSON.
pub struct Serializer<W, F = CompactFormatter> {
writer: W,
@@ -286,10 +283,14 @@ where
/// Serialize newtypes without an object wrapper.
#[inline]
- fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<()>
+ fn serialize_newtype_struct<T: ?Sized>(self, name: &'static str, value: &T) -> Result<()>
where
T: ser::Serialize,
{
+ if name == ::raw::SERDE_STRUCT_NAME {
+ return value.serialize(RawValueStrEmitter(self));
+ }
+
value.serialize(self)
}
@@ -1400,6 +1401,189 @@ impl<'a, W: io::Write, F: Formatter> ser::Serializer for NumberStrEmitter<'a, W,
}
}
+struct RawValueStrEmitter<'a, W: 'a + io::Write, F: 'a + Formatter>(&'a mut Serializer<W, F>);
+
+impl<'a, W: io::Write, F: Formatter> ser::Serializer for RawValueStrEmitter<'a, W, F> {
+ type Ok = ();
+ type Error = Error;
+
+ type SerializeSeq = Impossible<(), Error>;
+ type SerializeTuple = Impossible<(), Error>;
+ type SerializeTupleStruct = Impossible<(), Error>;
+ type SerializeTupleVariant = Impossible<(), Error>;
+ type SerializeMap = Impossible<(), Error>;
+ type SerializeStruct = Impossible<(), Error>;
+ type SerializeStructVariant = Impossible<(), Error>;
+
+ fn serialize_bool(self, _v: bool) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_i8(self, _v: i8) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_i16(self, _v: i16) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_i32(self, _v: i32) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_i64(self, _v: i64) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ serde_if_integer128! {
+ fn serialize_i128(self, _v: i128) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+ }
+
+ fn serialize_u8(self, _v: u8) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_u16(self, _v: u16) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_u32(self, _v: u32) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_u64(self, _v: u64) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ serde_if_integer128! {
+ fn serialize_u128(self, _v: u128) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+ }
+
+ fn serialize_f32(self, _v: f32) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_f64(self, _v: f64) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_char(self, _v: char) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_str(self, value: &str) -> Result<Self::Ok> {
+ let RawValueStrEmitter(serializer) = self;
+ serializer
+ .formatter
+ .write_raw_fragment(&mut serializer.writer, value)
+ .map_err(Error::io)
+ }
+
+ fn serialize_bytes(self, _value: &[u8]) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_none(self) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<Self::Ok>
+ where
+ T: Serialize,
+ {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_unit(self) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_unit_variant(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ _variant: &'static str,
+ ) -> Result<Self::Ok> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_newtype_struct<T: ?Sized>(
+ self,
+ _name: &'static str,
+ _value: &T,
+ ) -> Result<Self::Ok>
+ where
+ T: Serialize,
+ {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_newtype_variant<T: ?Sized>(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ _variant: &'static str,
+ _value: &T,
+ ) -> Result<Self::Ok>
+ where
+ T: Serialize,
+ {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_tuple_struct(
+ self,
+ _name: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeTupleStruct> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_tuple_variant(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ _variant: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeTupleVariant> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_struct_variant(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ _variant: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeStructVariant> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+}
+
/// Represents a character escape code in a type-safe manner.
pub enum CharEscape {
/// An escaped quote `"`
@@ -1743,6 +1927,16 @@ pub trait Formatter {
{
Ok(())
}
+
+ /// Writes a raw json fragment that doesn't need any escaping to the
+ /// specified writer.
+ #[inline]
+ fn write_raw_fragment<W: ?Sized>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()>
+ where
+ W: io::Write,
+ {
+ writer.write_all(fragment.as_bytes())
+ }
}
/// This structure compacts a JSON value with no extra whitespace.
diff --git a/src/value/de.rs b/src/value/de.rs
index dc8dbc6be..73dfb8bce 100644
--- a/src/value/de.rs
+++ b/src/value/de.rs
@@ -300,12 +300,16 @@ impl<'de> serde::Deserializer<'de> for Value {
#[inline]
fn deserialize_newtype_struct<V>(
self,
- _name: &'static str,
+ name: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
+ if name == ::raw::SERDE_STRUCT_NAME {
+ return visitor.visit_string(self.to_string());
+ }
+
visitor.visit_newtype_struct(self)
}
diff --git a/src/value/mod.rs b/src/value/mod.rs
index f5e33b457..155874a9c 100644
--- a/src/value/mod.rs
+++ b/src/value/mod.rs
@@ -118,6 +118,7 @@ use serde::ser::Serialize;
use error::Error;
pub use map::Map;
pub use number::Number;
+pub use raw::RawValue;
pub use self::index::Index;
diff --git a/src/value/ser.rs b/src/value/ser.rs
index d3f71b373..54ce18db8 100644
--- a/src/value/ser.rs
+++ b/src/value/ser.rs
@@ -6,7 +6,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use serde::ser::Impossible;
+use serde::ser::{self, Impossible};
use serde::{self, Serialize};
use error::{Error, ErrorCode};
@@ -14,9 +14,6 @@ use map::Map;
use number::Number;
use value::{to_value, Value};
-#[cfg(feature = "arbitrary_precision")]
-use serde::ser;
-
impl Serialize for Value {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
@@ -150,12 +147,16 @@ impl serde::Serializer for Serializer {
#[inline]
fn serialize_newtype_struct<T: ?Sized>(
self,
- _name: &'static str,
+ name: &'static str,
value: &T,
) -> Result<Value, Error>
where
T: Serialize,
{
+ if name == ::raw::SERDE_STRUCT_NAME {
+ return value.serialize(RawValueEmitter);
+ }
+
value.serialize(self)
}
@@ -812,3 +813,186 @@ impl ser::Serializer for NumberValueEmitter {
Err(invalid_number())
}
}
+
+struct RawValueEmitter;
+
+impl ser::Serializer for RawValueEmitter {
+ type Ok = Value;
+ type Error = Error;
+
+ type SerializeSeq = Impossible<Value, Error>;
+ type SerializeTuple = Impossible<Value, Error>;
+ type SerializeTupleStruct = Impossible<Value, Error>;
+ type SerializeTupleVariant = Impossible<Value, Error>;
+ type SerializeMap = Impossible<Value, Error>;
+ type SerializeStruct = Impossible<Value, Error>;
+ type SerializeStructVariant = Impossible<Value, Error>;
+
+ fn serialize_bool(self, _v: bool) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_i8(self, _v: i8) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_i16(self, _v: i16) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_i32(self, _v: i32) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_i64(self, _v: i64) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ serde_if_integer128! {
+ fn serialize_i128(self, _v: i128) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+ }
+
+ fn serialize_u8(self, _v: u8) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_u16(self, _v: u16) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_u32(self, _v: u32) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_u64(self, _v: u64) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ serde_if_integer128! {
+ fn serialize_u128(self, _v: u128) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+ }
+
+ fn serialize_f32(self, _v: f32) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_f64(self, _v: f64) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_char(self, _v: char) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error> {
+ ::from_str(value)
+ }
+
+ fn serialize_bytes(self, _value: &[u8]) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<Self::Ok, Self::Error>
+ where
+ T: Serialize,
+ {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_unit_variant(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ _variant: &'static str,
+ ) -> Result<Self::Ok, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_newtype_struct<T: ?Sized>(
+ self,
+ _name: &'static str,
+ _value: &T,
+ ) -> Result<Self::Ok, Self::Error>
+ where
+ T: Serialize,
+ {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_newtype_variant<T: ?Sized>(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ _variant: &'static str,
+ _value: &T,
+ ) -> Result<Self::Ok, Self::Error>
+ where
+ T: Serialize,
+ {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_tuple_struct(
+ self,
+ _name: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeTupleStruct, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_tuple_variant(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ _variant: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeTupleVariant, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_struct(
+ self,
+ _name: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeStruct, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+
+ fn serialize_struct_variant(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ _variant: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeStructVariant, Self::Error> {
+ Err(ser::Error::custom("expected RawValue"))
+ }
+}
|
diff --git a/tests/test.rs b/tests/test.rs
index 08d038837..09c51a62d 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -44,7 +44,7 @@ use serde_bytes::{ByteBuf, Bytes};
use serde_json::{
from_reader, from_slice, from_str, from_value, to_string, to_string_pretty, to_value, to_vec,
- to_writer, Deserializer, Number, Value,
+ to_writer, Deserializer, Number, RawValue, Value,
};
macro_rules! treemap {
@@ -2039,3 +2039,52 @@ fn test_integer128() {
),
]);
}
+
+#[test]
+fn test_raw_value() {
+ #[derive(Serialize, Deserialize)]
+ struct Wrapper<'a> {
+ a: i8,
+ #[serde(borrow)]
+ b: RawValue<'a>,
+ c: i8,
+ };
+
+ let wrapper_from_str =
+ serde_json::from_str::<Wrapper>(r#"{"a": 1, "b": {"foo": 2}, "c": 3}"#).unwrap();
+ assert_eq!(r#"{"foo": 2}"#, wrapper_from_str.b.as_ref());
+
+ let wrapper_from_reader = serde_json::from_reader::<_, Wrapper<'static>>(
+ br#"{"a": 1, "b": {"foo": 2}, "c": 3}"#.as_ref(),
+ ).unwrap();
+ assert_eq!(r#"{"foo": 2}"#, wrapper_from_reader.b.as_ref());
+
+ let wrapper_from_value =
+ serde_json::from_value::<Wrapper<'static>>(json!({"a": 1, "b": {"foo": 2}, "c": 3}))
+ .unwrap();
+ assert_eq!(r#"{"foo":2}"#, wrapper_from_value.b.as_ref());
+
+ let wrapper_to_string = serde_json::to_string(&wrapper_from_str).unwrap();
+ assert_eq!(r#"{"a":1,"b":{"foo": 2},"c":3}"#, wrapper_to_string);
+
+ let wrapper_to_value = serde_json::to_value(&wrapper_from_str).unwrap();
+ assert_eq!(json!({"a": 1, "b": {"foo": 2}, "c": 3}), wrapper_to_value);
+
+ let array_from_str =
+ serde_json::from_str::<Vec<RawValue>>(r#"["a", 42, {"foo": "bar"}, null]"#).unwrap();
+ assert_eq!(r#""a""#, array_from_str[0].as_ref());
+ assert_eq!(r#"42"#, array_from_str[1].as_ref());
+ assert_eq!(r#"{"foo": "bar"}"#, array_from_str[2].as_ref());
+ assert_eq!(r#"null"#, array_from_str[3].as_ref());
+
+ let array_from_reader = serde_json::from_reader::<_, Vec<RawValue<'static>>>(
+ br#"["a", 42, {"foo": "bar"}, null]"#.as_ref(),
+ ).unwrap();
+ assert_eq!(r#""a""#, array_from_reader[0].as_ref());
+ assert_eq!(r#"42"#, array_from_reader[1].as_ref());
+ assert_eq!(r#"{"foo": "bar"}"#, array_from_reader[2].as_ref());
+ assert_eq!(r#"null"#, array_from_reader[3].as_ref());
+
+ let array_to_string = serde_json::to_string(&array_from_str).unwrap();
+ assert_eq!(r#"["a",42,{"foo": "bar"},null]"#, array_to_string);
+}
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
1.0
|
serde-rs__json-462
| 462
|
[
"461"
] |
2018-07-16T16:38:33Z
|
1b36cec484a24dc8d1700cf2ef0577a96d4d7b6f
|
Unused result warning in json! macro.
Stumbled upon a warning coming from the `json!` macro that will cause compiles to fail if the `unused_results` warning is set with [this test case](http://play.rust-lang.org/?gist=baf66a86706282966f5109f537b74041&version=stable&mode=debug&edition=2015). Here's what I get running it with `cargo +nightly rustc -- -Z external-macro-backtrace`:
```
/mnt/c/Users/David/Projects/repro-serde-unused-result master*
❯ cargo +nightly rustc -- -Z external-macro-backtrace
Compiling unicode-xid v0.1.0
Compiling serde v1.0.70
Compiling dtoa v0.4.3
Compiling itoa v0.4.2
Compiling proc-macro2 v0.4.6
Compiling quote v0.6.3
Compiling syn v0.14.4
Compiling serde_derive v1.0.70
Compiling serde_json v1.0.22
Compiling repro-serde-unused-result v0.1.0 (file:///mnt/c/Users/David/Projects/repro-serde-unused-result)
error: unused result=============================================> ] 11/12: repro-serde-unused-result
|
::: <json macros>:1:1
|
1 | ( $ ( $ json : tt ) + ) => { json_internal ! ( $ ( $ json ) + ) } ;
| -------------------------------------------------------------------
| | |
| | in this macro invocation
| in this expansion of `json!`
--> <json_internal macros>:41:61
|
1 | / ( @ array [ $ ( $ elems : expr , ) * ] ) => { vec ! [ $ ( $ elems , ) * ] } ;
2 | | ( @ array [ $ ( $ elems : expr ) , * ] ) => { vec ! [ $ ( $ elems ) , * ] } ;
3 | | ( @ array [ $ ( $ elems : expr , ) * ] null $ ( $ rest : tt ) * ) => {
4 | | json_internal ! (
... |
41 | | $ object . insert ( ( $ ( $ key ) + ) . into ( ) , $ value ) ; } ; (
| | ^^^
... |
105 | | @ object object ( ) ( $ ( $ tt ) + ) ( $ ( $ tt ) + ) ) ; object } ) } ; (
106 | | $ other : expr ) => { $ crate :: to_value ( & $ other ) . unwrap ( ) } ;
| |_________________________________________________________________________- in this expansion of `json_internal!`
|
::: src/main.rs:10:20
|
10 | println!("{}", json!({
| _____________________-
11 | | "architecture": {
12 | | "name": name,
13 | | "ids": ids
14 | | }
15 | | }));
| |_______- in this macro invocation
|
note: lint level defined here
--> src/main.rs:1:9
|
1 | #![deny(unused_results)]
| ^^^^^^^^^^^^^^
error: unused result
|
::: <json macros>:1:1
|
1 | ( $ ( $ json : tt ) + ) => { json_internal ! ( $ ( $ json ) + ) } ;
| -------------------------------------------------------------------
| | |
| | in this macro invocation (#2)
| in this expansion of `json!` (#1)
--> <json_internal macros>:35:61
|
1 | ( @ array [ $ ( $ elems : expr , ) * ] ) => { vec ! [ $ ( $ elems , ) * ] } ;
| _-
| |_|
| ||_|
| |||_|
| ||||
2 | |||| ( @ array [ $ ( $ elems : expr ) , * ] ) => { vec ! [ $ ( $ elems ) , * ] } ;
3 | |||| ( @ array [ $ ( $ elems : expr , ) * ] null $ ( $ rest : tt ) * ) => {
4 | |||| json_internal ! (
... ||||
35 | |||| $ object . insert ( ( $ ( $ key ) + ) . into ( ) , $ value ) ; json_internal
| |||| ^^^
... ||||
65 | |||| @ object $ object [ $ ( $ key ) + ] ( json_internal ! ( { $ ( $ map ) * } ) )
| |||| ------------------------------------- in this macro invocation (#5)
... ||||
93 | / |||| json_internal ! (
94 | | |||| @ object $ object ( $ ( $ key ) * $ tt ) ( $ ( $ rest ) * ) ( $ ( $ rest ) * )
95 | | |||| ) ; } ; ( null ) => { $ crate :: Value :: Null } ; ( true ) => {
| |__||||___- in this macro invocation (#4)
... ||||
104 | |||| let mut object = $ crate :: Map :: new ( ) ; json_internal ! (
| __||||_______________________________________________-
105 | | |||| @ object object ( ) ( $ ( $ tt ) + ) ( $ ( $ tt ) + ) ) ; object } ) } ; (
| |__||||__________________________________________________________- in this macro invocation (#3)
106 | |||| $ other : expr ) => { $ crate :: to_value ( & $ other ) . unwrap ( ) } ;
| |||| -
| ||||_________________________________________________________________________|
| |||__________________________________________________________________________in this expansion of `json_internal!` (#2)
| ||___________________________________________________________________________in this expansion of `json_internal!` (#3)
| |____________________________________________________________________________in this expansion of `json_internal!` (#4)
| in this expansion of `json_internal!` (#5)
|
::: src/main.rs:10:20
|
10 | println!("{}", json!({
| __________________________-
11 | | "architecture": {
12 | | "name": name,
13 | | "ids": ids
14 | | }
15 | | }));
| |____________- in this macro invocation (#1)
error: unused result
|
::: <json macros>:1:1
|
1 | ( $ ( $ json : tt ) + ) => { json_internal ! ( $ ( $ json ) + ) } ;
| -------------------------------------------------------------------
| | |
| | in this macro invocation (#2)
| in this expansion of `json!` (#1)
--> <json_internal macros>:41:61
|
1 | ( @ array [ $ ( $ elems : expr , ) * ] ) => { vec ! [ $ ( $ elems , ) * ] } ;
| _-
| |_|
| ||_|
| |||_|
| ||||
2 | |||| ( @ array [ $ ( $ elems : expr ) , * ] ) => { vec ! [ $ ( $ elems ) , * ] } ;
3 | |||| ( @ array [ $ ( $ elems : expr , ) * ] null $ ( $ rest : tt ) * ) => {
4 | |||| json_internal ! (
... ||||
41 | |||| $ object . insert ( ( $ ( $ key ) + ) . into ( ) , $ value ) ; } ; (
| |||| ^^^
... ||||
65 | |||| @ object $ object [ $ ( $ key ) + ] ( json_internal ! ( { $ ( $ map ) * } ) )
| |||| ------------------------------------- in this macro invocation (#5)
... ||||
93 | / |||| json_internal ! (
94 | | |||| @ object $ object ( $ ( $ key ) * $ tt ) ( $ ( $ rest ) * ) ( $ ( $ rest ) * )
95 | | |||| ) ; } ; ( null ) => { $ crate :: Value :: Null } ; ( true ) => {
| |__||||___- in this macro invocation (#4)
... ||||
104 | |||| let mut object = $ crate :: Map :: new ( ) ; json_internal ! (
| __||||_______________________________________________-
105 | | |||| @ object object ( ) ( $ ( $ tt ) + ) ( $ ( $ tt ) + ) ) ; object } ) } ; (
| |__||||__________________________________________________________- in this macro invocation (#3)
106 | |||| $ other : expr ) => { $ crate :: to_value ( & $ other ) . unwrap ( ) } ;
| |||| -
| ||||_________________________________________________________________________|
| |||__________________________________________________________________________in this expansion of `json_internal!` (#2)
| ||___________________________________________________________________________in this expansion of `json_internal!` (#3)
| |____________________________________________________________________________in this expansion of `json_internal!` (#4)
| in this expansion of `json_internal!` (#5)
|
::: src/main.rs:10:20
|
10 | println!("{}", json!({
| __________________________-
11 | | "architecture": {
12 | | "name": name,
13 | | "ids": ids
14 | | }
15 | | }));
| |____________- in this macro invocation (#1)
error: aborting due to 3 previous errors
error: Could not compile `repro-serde-unused-result`.
To learn more, run the command again with --verbose.
```
|
diff --git a/src/macros.rs b/src/macros.rs
index 29e16b7ab..a3accf75b 100644
--- a/src/macros.rs
+++ b/src/macros.rs
@@ -161,7 +161,7 @@ macro_rules! json_internal {
// Insert the current entry followed by trailing comma.
(@object $object:ident [$($key:tt)+] ($value:expr) , $($rest:tt)*) => {
- $object.insert(($($key)+).into(), $value);
+ let _ = $object.insert(($($key)+).into(), $value);
json_internal!(@object $object () ($($rest)*) ($($rest)*));
};
@@ -172,7 +172,7 @@ macro_rules! json_internal {
// Insert the last entry without trailing comma.
(@object $object:ident [$($key:tt)+] ($value:expr)) => {
- $object.insert(($($key)+).into(), $value);
+ let _ = $object.insert(($($key)+).into(), $value);
};
// Next value is `null`.
|
diff --git a/tests/test.rs b/tests/test.rs
index 4e9c0ccd9..08d038837 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -1847,6 +1847,9 @@ fn test_json_macro() {
(<Result<&str, ()> as Clone>::clone(&Ok("")).unwrap()): "ok",
(<Result<(), &str> as Clone>::clone(&Err("")).unwrap_err()): "err"
});
+
+ #[deny(unused_results)]
+ let _ = json!({ "architecture": [true, null] });
}
#[test]
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
|
1.0
|
serde-rs__json-455
| 455
|
[
"454"
] |
2018-06-24T23:27:48Z
|
7efc0972cd04fc05e028d4d7f5b95359b82d878b
|
Get ExpectedSomeIdent error instead of Eof error if the input ends with a truncated "null"
```rust
extern crate serde_json;
fn main() {
match serde_json::from_str::<serde_json::Value>("nu") {
Ok(_) => unreachable!(),
Err(err) => match err.classify() {
serde_json::error::Category::Eof => println!("OK"),
other => panic!("expected Eof but got {:?} {:?}", other, err),
},
};
}
```
```
thread 'main' panicked at 'expected Eof but got Syntax Error("expected ident", line: 1, column: 2)', src/main.rs:8:22
```
dtolnay said on IRC that this is a bug.
|
diff --git a/src/de.rs b/src/de.rs
index b154cad60..f1c5c3cff 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -308,9 +308,16 @@ impl<'de, R: Read<'de>> Deserializer<R> {
}
fn parse_ident(&mut self, ident: &[u8]) -> Result<()> {
- for c in ident {
- if Some(*c) != try!(self.next_char()) {
- return Err(self.error(ErrorCode::ExpectedSomeIdent));
+ for expected in ident {
+ match try!(self.next_char()) {
+ None => {
+ return Err(self.error(ErrorCode::EofWhileParsingValue));
+ }
+ Some(next) => {
+ if next != *expected {
+ return Err(self.error(ErrorCode::ExpectedSomeIdent));
+ }
+ }
}
}
|
diff --git a/tests/test.rs b/tests/test.rs
index 0b84ce869..811c409af 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -613,6 +613,15 @@ where
let mut de = Deserializer::from_str(&twoline);
IgnoredAny::deserialize(&mut de).unwrap();
assert_eq!(0xDEAD_BEEF, u64::deserialize(&mut de).unwrap());
+
+ // Make sure every prefix is an EOF error, except that a prefix of a
+ // number may be a valid number.
+ if !json_value.is_number() {
+ for (i, _) in s.trim_right().char_indices() {
+ assert!(from_str::<Value>(&s[..i]).unwrap_err().is_eof());
+ assert!(from_str::<IgnoredAny>(&s[..i]).unwrap_err().is_eof());
+ }
+ }
}
}
@@ -671,8 +680,8 @@ where
#[test]
fn test_parse_null() {
test_parse_err::<()>(&[
- ("n", "expected ident at line 1 column 1"),
- ("nul", "expected ident at line 1 column 3"),
+ ("n", "EOF while parsing a value at line 1 column 1"),
+ ("nul", "EOF while parsing a value at line 1 column 3"),
("nulla", "trailing characters at line 1 column 5"),
]);
@@ -682,9 +691,9 @@ fn test_parse_null() {
#[test]
fn test_parse_bool() {
test_parse_err::<bool>(&[
- ("t", "expected ident at line 1 column 1"),
+ ("t", "EOF while parsing a value at line 1 column 1"),
("truz", "expected ident at line 1 column 4"),
- ("f", "expected ident at line 1 column 1"),
+ ("f", "EOF while parsing a value at line 1 column 1"),
("faz", "expected ident at line 1 column 3"),
("truea", "trailing characters at line 1 column 5"),
("falsea", "trailing characters at line 1 column 6"),
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
|
1.0
|
serde-rs__json-449
| 449
|
[
"448"
] |
2018-05-26T22:05:01Z
|
8ffe4d8222d35aae79456ee5eff72db5236fc8df
|
Support i128 and u128
These types gained Serialize and Deserialize impls in [Serde 1.0.60](https://github.com/serde-rs/serde/releases/tag/v1.0.60) but still needs to be implemented in serde_json.
|
diff --git a/Cargo.toml b/Cargo.toml
index 938cf314f..0216476d8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -16,7 +16,7 @@ travis-ci = { repository = "serde-rs/json" }
appveyor = { repository = "serde-rs/json" }
[dependencies]
-serde = "1.0"
+serde = "1.0.60"
linked-hash-map = { version = "0.5", optional = true }
itoa = "0.4"
dtoa = "0.4"
diff --git a/src/de.rs b/src/de.rs
index f39443faf..0e298e797 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -274,6 +274,34 @@ impl<'de, R: Read<'de>> Deserializer<R> {
}
}
+ serde_if_integer128! {
+ fn scan_integer128(&mut self, buf: &mut String) -> Result<()> {
+ match try!(self.next_char_or_null()) {
+ b'0' => {
+ buf.push('0');
+ // There can be only one leading '0'.
+ match try!(self.peek_or_null()) {
+ b'0'...b'9' => {
+ Err(self.peek_error(ErrorCode::InvalidNumber))
+ }
+ _ => Ok(()),
+ }
+ }
+ c @ b'1'...b'9' => {
+ buf.push(c as char);
+ while let c @ b'0'...b'9' = try!(self.peek_or_null()) {
+ self.eat_char();
+ buf.push(c as char);
+ }
+ Ok(())
+ }
+ _ => {
+ Err(self.error(ErrorCode::InvalidNumber))
+ }
+ }
+ }
+ }
+
#[cold]
fn fix_position(&self, err: Error) -> Error {
err.fix_position(move |code| self.error(code))
@@ -1098,6 +1126,70 @@ impl<'de, 'a, R: Read<'de>> de::Deserializer<'de> for &'a mut Deserializer<R> {
deserialize_prim_number!(deserialize_f32);
deserialize_prim_number!(deserialize_f64);
+ serde_if_integer128! {
+ fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value>
+ where
+ V: de::Visitor<'de>,
+ {
+ let mut buf = String::new();
+
+ match try!(self.parse_whitespace()) {
+ Some(b'-') => {
+ self.eat_char();
+ buf.push('-');
+ }
+ Some(_) => {}
+ None => {
+ return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
+ }
+ };
+
+ try!(self.scan_integer128(&mut buf));
+
+ let value = match buf.parse() {
+ Ok(int) => visitor.visit_i128(int),
+ Err(_) => {
+ return Err(self.error(ErrorCode::NumberOutOfRange));
+ }
+ };
+
+ match value {
+ Ok(value) => Ok(value),
+ Err(err) => Err(self.fix_position(err)),
+ }
+ }
+
+ fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value>
+ where
+ V: de::Visitor<'de>,
+ {
+ match try!(self.parse_whitespace()) {
+ Some(b'-') => {
+ return Err(self.peek_error(ErrorCode::NumberOutOfRange));
+ }
+ Some(_) => {}
+ None => {
+ return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
+ }
+ }
+
+ let mut buf = String::new();
+ try!(self.scan_integer128(&mut buf));
+
+ let value = match buf.parse() {
+ Ok(int) => visitor.visit_u128(int),
+ Err(_) => {
+ return Err(self.error(ErrorCode::NumberOutOfRange));
+ }
+ };
+
+ match value {
+ Ok(value) => Ok(value),
+ Err(err) => Err(self.fix_position(err)),
+ }
+ }
+ }
+
fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
@@ -1800,6 +1892,11 @@ where
deserialize_integer_key!(deserialize_u32 => visit_u32);
deserialize_integer_key!(deserialize_u64 => visit_u64);
+ serde_if_integer128! {
+ deserialize_integer_key!(deserialize_i128 => visit_i128);
+ deserialize_integer_key!(deserialize_u128 => visit_u128);
+ }
+
#[inline]
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
where
diff --git a/src/number.rs b/src/number.rs
index 8149ae3a4..949bc5c07 100644
--- a/src/number.rs
+++ b/src/number.rs
@@ -565,6 +565,11 @@ impl<'de> Deserializer<'de> for Number {
deserialize_number!(deserialize_f32 => visit_f32);
deserialize_number!(deserialize_f64 => visit_f64);
+ serde_if_integer128! {
+ deserialize_number!(deserialize_i128 => visit_i128);
+ deserialize_number!(deserialize_u128 => visit_u128);
+ }
+
forward_to_deserialize_any! {
bool char str string bytes byte_buf option unit unit_struct
newtype_struct seq tuple tuple_struct map struct enum identifier
@@ -588,6 +593,11 @@ impl<'de, 'a> Deserializer<'de> for &'a Number {
deserialize_number!(deserialize_f32 => visit_f32);
deserialize_number!(deserialize_f64 => visit_f64);
+ serde_if_integer128! {
+ deserialize_number!(deserialize_i128 => visit_i128);
+ deserialize_number!(deserialize_u128 => visit_u128);
+ }
+
forward_to_deserialize_any! {
bool char str string bytes byte_buf option unit unit_struct
newtype_struct seq tuple tuple_struct map struct enum identifier
@@ -639,9 +649,9 @@ impl<'de> Deserializer<'de> for NumberFieldDeserializer {
}
forward_to_deserialize_any! {
- bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq
- bytes byte_buf map struct option unit newtype_struct
- ignored_any unit_struct tuple_struct tuple enum identifier
+ bool u8 u16 u32 u64 u128 i8 i16 i32 i64 i128 f32 f64 char str string seq
+ bytes byte_buf map struct option unit newtype_struct ignored_any
+ unit_struct tuple_struct tuple enum identifier
}
}
diff --git a/src/ser.rs b/src/ser.rs
index 8ff9eccec..acc0bc006 100644
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -141,6 +141,14 @@ where
Ok(())
}
+ serde_if_integer128! {
+ fn serialize_i128(self, value: i128) -> Result<()> {
+ self.formatter
+ .write_number_str(&mut self.writer, &value.to_string())
+ .map_err(Error::io)
+ }
+ }
+
#[inline]
fn serialize_u8(self, value: u8) -> Result<()> {
try!(
@@ -181,6 +189,14 @@ where
Ok(())
}
+ serde_if_integer128! {
+ fn serialize_u128(self, value: u128) -> Result<()> {
+ self.formatter
+ .write_number_str(&mut self.writer, &value.to_string())
+ .map_err(Error::io)
+ }
+ }
+
#[inline]
fn serialize_f32(self, value: f32) -> Result<()> {
match value.classify() {
@@ -1010,6 +1026,15 @@ where
Ok(())
}
+ serde_if_integer128! {
+ fn serialize_i128(self, value: i128) -> Result<()> {
+ self.ser
+ .formatter
+ .write_number_str(&mut self.ser.writer, &value.to_string())
+ .map_err(Error::io)
+ }
+ }
+
fn serialize_u8(self, value: u8) -> Result<()> {
try!(
self.ser
@@ -1098,6 +1123,15 @@ where
Ok(())
}
+ serde_if_integer128! {
+ fn serialize_u128(self, value: u128) -> Result<()> {
+ self.ser
+ .formatter
+ .write_number_str(&mut self.ser.writer, &value.to_string())
+ .map_err(Error::io)
+ }
+ }
+
fn serialize_f32(self, _value: f32) -> Result<()> {
Err(key_must_be_a_string())
}
@@ -1227,6 +1261,12 @@ impl<'a, W: io::Write, F: Formatter> ser::Serializer for NumberStrEmitter<'a, W,
Err(invalid_number())
}
+ serde_if_integer128! {
+ fn serialize_i128(self, _v: i128) -> Result<Self::Ok> {
+ Err(invalid_number())
+ }
+ }
+
fn serialize_u8(self, _v: u8) -> Result<Self::Ok> {
Err(invalid_number())
}
@@ -1243,6 +1283,12 @@ impl<'a, W: io::Write, F: Formatter> ser::Serializer for NumberStrEmitter<'a, W,
Err(invalid_number())
}
+ serde_if_integer128! {
+ fn serialize_u128(self, _v: u128) -> Result<Self::Ok> {
+ Err(invalid_number())
+ }
+ }
+
fn serialize_f32(self, _v: f32) -> Result<Self::Ok> {
Err(invalid_number())
}
diff --git a/src/value/de.rs b/src/value/de.rs
index d4f9b614a..162e05e74 100644
--- a/src/value/de.rs
+++ b/src/value/de.rs
@@ -316,6 +316,11 @@ impl<'de> serde::Deserializer<'de> for Value {
deserialize_prim_number!(deserialize_f32);
deserialize_prim_number!(deserialize_f64);
+ serde_if_integer128! {
+ deserialize_prim_number!(deserialize_i128);
+ deserialize_prim_number!(deserialize_u128);
+ }
+
#[inline]
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
where
@@ -656,8 +661,8 @@ impl<'de> serde::Deserializer<'de> for SeqDeserializer {
}
forward_to_deserialize_any! {
- bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq tuple
+ bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
+ bytes byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}
@@ -746,8 +751,8 @@ impl<'de> serde::Deserializer<'de> for MapDeserializer {
}
forward_to_deserialize_any! {
- bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq tuple
+ bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
+ bytes byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}
@@ -842,6 +847,11 @@ impl<'de> serde::Deserializer<'de> for &'de Value {
deserialize_value_ref_number!(deserialize_f32);
deserialize_value_ref_number!(deserialize_f64);
+ serde_if_integer128! {
+ deserialize_prim_number!(deserialize_i128);
+ deserialize_prim_number!(deserialize_u128);
+ }
+
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: Visitor<'de>,
@@ -1177,8 +1187,8 @@ impl<'de> serde::Deserializer<'de> for SeqRefDeserializer<'de> {
}
forward_to_deserialize_any! {
- bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq tuple
+ bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
+ bytes byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}
@@ -1267,8 +1277,8 @@ impl<'de> serde::Deserializer<'de> for MapRefDeserializer<'de> {
}
forward_to_deserialize_any! {
- bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq tuple
+ bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
+ bytes byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}
@@ -1311,6 +1321,11 @@ impl<'de> serde::Deserializer<'de> for MapKeyDeserializer<'de> {
deserialize_integer_key!(deserialize_u32 => visit_u32);
deserialize_integer_key!(deserialize_u64 => visit_u64);
+ serde_if_integer128! {
+ deserialize_integer_key!(deserialize_i128 => visit_i128);
+ deserialize_integer_key!(deserialize_u128 => visit_u128);
+ }
+
#[inline]
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
where
|
diff --git a/tests/test.rs b/tests/test.rs
index 61e0d2dc9..a7d21092f 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -1983,3 +1983,40 @@ fn null_invalid_type() {
String::from("invalid type: null, expected a string at line 1 column 4")
);
}
+
+#[test]
+fn test_integer128() {
+ let signed = &[i128::min_value(), -1, 0, 1, i128::max_value()];
+ let unsigned = &[0, 1, u128::max_value()];
+
+ for integer128 in signed {
+ let expected = integer128.to_string();
+ assert_eq!(to_string(integer128).unwrap(), expected);
+ assert_eq!(from_str::<i128>(&expected).unwrap(), *integer128);
+ }
+
+ for integer128 in unsigned {
+ let expected = integer128.to_string();
+ assert_eq!(to_string(integer128).unwrap(), expected);
+ assert_eq!(from_str::<u128>(&expected).unwrap(), *integer128);
+ }
+
+ test_parse_err::<i128>(&[
+ (
+ "-170141183460469231731687303715884105729",
+ "number out of range at line 1 column 40",
+ ),
+ (
+ "170141183460469231731687303715884105728",
+ "number out of range at line 1 column 39",
+ ),
+ ]);
+
+ test_parse_err::<u128>(&[
+ ("-1", "number out of range at line 1 column 1"),
+ (
+ "340282366920938463463374607431768211456",
+ "number out of range at line 1 column 39",
+ ),
+ ]);
+}
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
|
1.0
|
serde-rs__json-356
| 356
|
[
"174"
] |
2017-09-04T19:20:12Z
|
The Pikkr benchmark will be a good way to measure this https://github.com/pikkr/pikkr. They ignore most of the data.
|
b67a9470c59ab8445e145e74a6a5398142e06e21
|
Performance of deserializing IgnoredAny
I haven't benchmarked but there may be an opportunity to optimize IgnoredAny. Currently the codepath for deserialize_ignored_any is the same as for deserializing a serde_json::Value. It jumps back and forth into the IgnoredAny's Visitor and does all of the work that entails, including buffering up long strings, converting floating point values to f64, etc.
Instead we should be able to very quickly scan and do only the most basic syntactic checks, not buffering strings or interpreting numbers.
This could be a good intro task for somebody interested in performance. I can provide mentorship.
|
diff --git a/src/de.rs b/src/de.rs
index 9ec5165f9..fd2a4894d 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -532,6 +532,215 @@ impl<'de, R: Read<'de>> Deserializer<R> {
None => Err(self.peek_error(ErrorCode::EofWhileParsingObject)),
}
}
+
+ fn ignore_value(&mut self) -> Result<()> {
+ let peek = match try!(self.parse_whitespace()) {
+ Some(b) => b,
+ None => {
+ return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
+ }
+ };
+
+ match peek {
+ b'n' => {
+ self.eat_char();
+ self.parse_ident(b"ull")
+ }
+ b't' => {
+ self.eat_char();
+ self.parse_ident(b"rue")
+ }
+ b'f' => {
+ self.eat_char();
+ self.parse_ident(b"alse")
+ }
+ b'-' => {
+ self.eat_char();
+ self.ignore_integer()
+ }
+ b'0'...b'9' => {
+ self.ignore_integer()
+ }
+ b'"' => {
+ self.eat_char();
+ self.read.ignore_str()
+ }
+ b'[' => {
+ self.remaining_depth -= 1;
+ if self.remaining_depth == 0 {
+ return Err(self.peek_error(ErrorCode::RecursionLimitExceeded));
+ }
+
+ self.eat_char();
+ let res = self.ignore_seq();
+ self.remaining_depth += 1;
+ res
+ }
+ b'{' => {
+ self.remaining_depth -= 1;
+ if self.remaining_depth == 0 {
+ return Err(self.peek_error(ErrorCode::RecursionLimitExceeded));
+ }
+
+ self.eat_char();
+ let res = self.ignore_map();
+ self.remaining_depth += 1;
+ res
+ }
+ _ => {
+ Err(self.peek_error(ErrorCode::ExpectedSomeValue))
+ }
+ }
+ }
+
+ fn ignore_integer(&mut self) -> Result<()> {
+ match try!(self.next_char_or_null()) {
+ b'0' => {
+ // There can be only one leading '0'.
+ if let b'0'...b'9' = try!(self.peek_or_null()) {
+ return Err(self.peek_error(ErrorCode::InvalidNumber));
+ }
+ }
+ b'1'...b'9' => {
+ while let b'0'...b'9' = try!(self.peek_or_null()) {
+ self.eat_char();
+ }
+ }
+ _ => {
+ return Err(self.error(ErrorCode::InvalidNumber));
+ }
+ }
+
+ match try!(self.peek_or_null()) {
+ b'.' => self.ignore_decimal(),
+ b'e' | b'E' => self.ignore_exponent(),
+ _ => Ok(()),
+ }
+ }
+
+ fn ignore_decimal(&mut self) -> Result<()> {
+ self.eat_char();
+
+ let mut at_least_one_digit = false;
+ while let b'0'...b'9' = try!(self.peek_or_null()) {
+ self.eat_char();
+ at_least_one_digit = true;
+ }
+
+ if !at_least_one_digit {
+ return Err(self.peek_error(ErrorCode::InvalidNumber));
+ }
+
+ match try!(self.peek_or_null()) {
+ b'e' | b'E' => self.ignore_exponent(),
+ _ => Ok(()),
+ }
+ }
+
+ fn ignore_exponent(&mut self) -> Result<()> {
+ self.eat_char();
+
+ match try!(self.peek_or_null()) {
+ b'+' | b'-' => self.eat_char(),
+ _ => {}
+ }
+
+ // Make sure a digit follows the exponent place.
+ match try!(self.next_char_or_null()) {
+ b'0'...b'9' => {}
+ _ => {
+ return Err(self.error(ErrorCode::InvalidNumber));
+ }
+ }
+
+ while let b'0'...b'9' = try!(self.peek_or_null()) {
+ self.eat_char();
+ }
+
+ Ok(())
+ }
+
+ fn ignore_seq(&mut self) -> Result<()> {
+ let mut first = true;
+
+ loop {
+ match try!(self.parse_whitespace()) {
+ Some(b']') => {
+ self.eat_char();
+ return Ok(());
+ }
+ Some(b',') if !first => {
+ self.eat_char();
+ }
+ Some(_) => {
+ if first {
+ first = false;
+ } else {
+ return Err(self.peek_error(ErrorCode::ExpectedListCommaOrEnd));
+ }
+ }
+ None => {
+ return Err(self.peek_error(ErrorCode::EofWhileParsingList));
+ }
+ }
+
+ try!(self.ignore_value());
+ }
+ }
+
+ fn ignore_map(&mut self) -> Result<()> {
+ let mut first = true;
+
+ loop {
+ let peek = match try!(self.parse_whitespace()) {
+ Some(b'}') => {
+ self.eat_char();
+ return Ok(());
+ }
+ Some(b',') if !first => {
+ self.eat_char();
+ try!(self.parse_whitespace())
+ }
+ Some(b) => {
+ if first {
+ first = false;
+ Some(b)
+ } else {
+ return Err(self.peek_error(ErrorCode::ExpectedObjectCommaOrEnd));
+ }
+ }
+ None => {
+ return Err(self.peek_error(ErrorCode::EofWhileParsingObject));
+ }
+ };
+
+ match peek {
+ Some(b'"') => {
+ self.eat_char();
+ try!(self.read.ignore_str());
+ }
+ Some(_) => {
+ return Err(self.peek_error(ErrorCode::KeyMustBeAString));
+ }
+ None => {
+ return Err(self.peek_error(ErrorCode::EofWhileParsingObject));
+ }
+ }
+
+ match try!(self.parse_whitespace()) {
+ Some(b':') => {
+ self.eat_char();
+ try!(self.ignore_value());
+ }
+ Some(_) => {
+ return Err(self.peek_error(ErrorCode::ExpectedColon));
+ }
+ None => {
+ return Err(self.peek_error(ErrorCode::EofWhileParsingObject));
+ }
+ }
+ }
+ }
}
#[cfg_attr(rustfmt, rustfmt_skip)]
@@ -750,9 +959,17 @@ impl<'de, 'a, R: Read<'de>> de::Deserializer<'de> for &'a mut Deserializer<R> {
self.deserialize_bytes(visitor)
}
+ fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value>
+ where
+ V: de::Visitor<'de>,
+ {
+ try!(self.ignore_value());
+ visitor.visit_unit()
+ }
+
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string unit
- unit_struct seq tuple tuple_struct map struct identifier ignored_any
+ unit_struct seq tuple tuple_struct map struct identifier
}
}
diff --git a/src/read.rs b/src/read.rs
index a3aa6bfab..02db8f7d6 100644
--- a/src/read.rs
+++ b/src/read.rs
@@ -71,6 +71,11 @@ pub trait Read<'de>: private::Sealed {
&'s mut self,
scratch: &'s mut Vec<u8>,
) -> Result<Reference<'de, 's, [u8]>>;
+
+ /// Assumes the previous byte was a quotation mark. Parses a JSON-escaped
+ /// string until the next quotation mark but discards the data.
+ #[doc(hidden)]
+ fn ignore_str(&mut self) -> Result<()>;
}
pub struct Position {
@@ -257,6 +262,26 @@ where
self.parse_str_bytes(scratch, false, |_, bytes| Ok(bytes))
.map(Reference::Copied)
}
+
+ fn ignore_str(&mut self) -> Result<()> {
+ loop {
+ let ch = try!(next_or_eof(self));
+ if !ESCAPE[ch as usize] {
+ continue;
+ }
+ match ch {
+ b'"' => {
+ return Ok(());
+ }
+ b'\\' => {
+ try!(ignore_escape(self));
+ }
+ _ => {
+ return error(self, ErrorCode::InvalidUnicodeCodePoint);
+ }
+ }
+ }
+ }
}
//////////////////////////////////////////////////////////////////////////////
@@ -402,6 +427,30 @@ impl<'a> Read<'a> for SliceRead<'a> {
) -> Result<Reference<'a, 's, [u8]>> {
self.parse_str_bytes(scratch, false, |_, bytes| Ok(bytes))
}
+
+ fn ignore_str(&mut self) -> Result<()> {
+ loop {
+ while self.index < self.slice.len() && !ESCAPE[self.slice[self.index] as usize] {
+ self.index += 1;
+ }
+ if self.index == self.slice.len() {
+ return error(self, ErrorCode::EofWhileParsingString);
+ }
+ match self.slice[self.index] {
+ b'"' => {
+ self.index += 1;
+ return Ok(());
+ }
+ b'\\' => {
+ self.index += 1;
+ try!(ignore_escape(self));
+ }
+ _ => {
+ return error(self, ErrorCode::InvalidUnicodeCodePoint);
+ }
+ }
+ }
+ }
}
//////////////////////////////////////////////////////////////////////////////
@@ -460,6 +509,10 @@ impl<'a> Read<'a> for StrRead<'a> {
) -> Result<Reference<'a, 's, [u8]>> {
self.delegate.parse_str_raw(scratch)
}
+
+ fn ignore_str(&mut self) -> Result<()> {
+ self.delegate.ignore_str()
+ }
}
//////////////////////////////////////////////////////////////////////////////
@@ -492,14 +545,14 @@ static ESCAPE: [bool; 256] = [
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // F
];
-fn next_or_eof<'de, R: Read<'de>>(read: &mut R) -> Result<u8> {
+fn next_or_eof<'de, R: ?Sized + Read<'de>>(read: &mut R) -> Result<u8> {
match try!(read.next().map_err(Error::io)) {
Some(b) => Ok(b),
None => error(read, ErrorCode::EofWhileParsingString),
}
}
-fn error<'de, R: Read<'de>, T>(read: &R, reason: ErrorCode) -> Result<T> {
+fn error<'de, R: ?Sized + Read<'de>, T>(read: &R, reason: ErrorCode) -> Result<T> {
let pos = read.position();
Err(Error::syntax(reason, pos.line, pos.column))
}
@@ -546,7 +599,7 @@ fn parse_escape<'de, R: Read<'de>>(read: &mut R, scratch: &mut Vec<u8>) -> Resul
let n = (((n1 - 0xD800) as u32) << 10 | (n2 - 0xDC00) as u32) + 0x1_0000;
- match char::from_u32(n as u32) {
+ match char::from_u32(n) {
Some(c) => c,
None => {
return error(read, ErrorCode::InvalidUnicodeCodePoint);
@@ -578,7 +631,54 @@ fn parse_escape<'de, R: Read<'de>>(read: &mut R, scratch: &mut Vec<u8>) -> Resul
Ok(())
}
-fn decode_hex_escape<'de, R: Read<'de>>(read: &mut R) -> Result<u16> {
+/// Parses a JSON escape sequence and discards the value. Assumes the previous
+/// byte read was a backslash.
+fn ignore_escape<'de, R: ?Sized + Read<'de>>(read: &mut R) -> Result<()> {
+ let ch = try!(next_or_eof(read));
+
+ match ch {
+ b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't' => {}
+ b'u' => {
+ let n = match try!(decode_hex_escape(read)) {
+ 0xDC00...0xDFFF => {
+ return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape);
+ }
+
+ // Non-BMP characters are encoded as a sequence of
+ // two hex escapes, representing UTF-16 surrogates.
+ n1 @ 0xD800...0xDBFF => {
+ if try!(next_or_eof(read)) != b'\\' {
+ return error(read, ErrorCode::UnexpectedEndOfHexEscape);
+ }
+ if try!(next_or_eof(read)) != b'u' {
+ return error(read, ErrorCode::UnexpectedEndOfHexEscape);
+ }
+
+ let n2 = try!(decode_hex_escape(read));
+
+ if n2 < 0xDC00 || n2 > 0xDFFF {
+ return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape);
+ }
+
+ (((n1 - 0xD800) as u32) << 10 | (n2 - 0xDC00) as u32) + 0x1_0000
+ }
+
+ n => n as u32,
+ };
+
+ if char::from_u32(n).is_none() {
+ return error(read, ErrorCode::InvalidUnicodeCodePoint);
+ }
+ }
+ _ => {
+ return error(read, ErrorCode::InvalidEscape);
+ }
+ }
+
+ Ok(())
+}
+
+fn decode_hex_escape<'de, R: ?Sized + Read<'de>>(read: &mut R) -> Result<u16> {
let mut n = 0;
for _ in 0..4 {
n = match try!(next_or_eof(read)) {
|
diff --git a/tests/test.rs b/tests/test.rs
index 89b1d783e..f8ccd0c5d 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -34,7 +34,7 @@ use std::iter;
use std::marker::PhantomData;
use std::{u8, u16, u32, u64};
-use serde::de::{self, Deserialize};
+use serde::de::{self, Deserialize, IgnoredAny};
use serde::ser::{self, Serialize, Serializer};
use serde_bytes::{ByteBuf, Bytes};
@@ -594,6 +594,12 @@ where
// Make sure we can round trip back to `Value`.
let json_value2: Value = from_value(json_value.clone()).unwrap();
assert_eq!(json_value2, json_value);
+
+ // Make sure we can fully ignore.
+ let twoline = s.to_owned() + "\n3735928559";
+ let mut de = Deserializer::from_str(&twoline);
+ IgnoredAny::deserialize(&mut de).unwrap();
+ assert_eq!(0xDEAD_BEEF, u64::deserialize(&mut de).unwrap());
}
}
@@ -1844,4 +1850,4 @@ fn test_borrow() {
fn null_invalid_type() {
let err = serde_json::from_str::<String>("null").unwrap_err();
assert_eq!(format!("{}", err), String::from("invalid type: null, expected a string at line 1 column 4"));
-}
\ No newline at end of file
+}
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
1.0
|
serde-rs__json-353
| 353
|
[
"352"
] |
2017-09-01T18:40:41Z
|
I agree! Would you be interested in implementing this? The code for parsing a map key will need to recognize when it gets a `}` and treat that as a trailing comma error.
I'll give it a go.
Is there documentation on contributing? It seems like the tests don't compile on rustc stable...
I switched to nightly and the tests compile with warnings about unused extern crate. Only a hand full of tests run and they all fail. What gives?
```
rustc 1.21.0-nightly (7eeac1b81 2017-08-30)
cargo 0.22.0-nightly (3d3f2c05d 2017-08-27)
```
Further study of travis.sh revealed that I was missing a build step
```
(cd "$DIR/tests/deps" && channel build)
```
All tests seem to be passing. On to the real work.
|
764e9607cf5d5a66e6a8447320b9d938d59f3806
|
misleading error message
I was going through the [serde_json :: de :: from_reader](https://docs.serde.rs/serde_json/de/fn.from_reader.html) example and encountered an error at run time "KeyMustBeAString". I went back to my json file and looked. All of the keys were strings... I scratched my head and stared. Then I noticed that I had a trailing comma after the last value.
It seems like adding another error code that has something to do with trailing commas would make the error messages more human friendly.
test.json
```json
{
"fingerprint": "gray",
"location": "1",
}
```
error message:
```rust
ErrorImpl {
code: KeyMustBeAString,
line: 4,
column: 1
}
```
|
diff --git a/src/de.rs b/src/de.rs
index fd2a4894d..0d5225398 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -105,6 +105,7 @@ impl<'de, R: Read<'de>> Deserializer<R> {
/// only has trailing whitespace.
pub fn end(&mut self) -> Result<()> {
match try!(self.parse_whitespace()) {
+ Some(b',') => Err(self.peek_error(ErrorCode::TrailingComma)),
Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)),
None => Ok(()),
}
@@ -517,6 +518,13 @@ impl<'de, R: Read<'de>> Deserializer<R> {
self.eat_char();
Ok(())
}
+ Some(b',') => {
+ self.eat_char();
+ match self.parse_whitespace() {
+ Ok(Some(b']')) => Err(self.peek_error(ErrorCode::TrailingComma)),
+ _ => Err(self.peek_error(ErrorCode::TrailingCharacters)),
+ }
+ }
Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)),
None => Err(self.peek_error(ErrorCode::EofWhileParsingList)),
}
@@ -528,6 +536,7 @@ impl<'de, R: Read<'de>> Deserializer<R> {
self.eat_char();
Ok(())
}
+ Some(b',') => Err(self.peek_error(ErrorCode::TrailingComma)),
Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)),
None => Err(self.peek_error(ErrorCode::EofWhileParsingObject)),
}
@@ -994,16 +1003,18 @@ impl<'de, 'a, R: Read<'de> + 'a> de::SeqAccess<'de> for SeqAccess<'a, R> {
where
T: de::DeserializeSeed<'de>,
{
- match try!(self.de.parse_whitespace()) {
+ let peek = match try!(self.de.parse_whitespace()) {
Some(b']') => {
return Ok(None);
}
Some(b',') if !self.first => {
self.de.eat_char();
+ try!(self.de.parse_whitespace())
}
- Some(_) => {
+ Some(b) => {
if self.first {
self.first = false;
+ Some(b)
} else {
return Err(self.de.peek_error(ErrorCode::ExpectedListCommaOrEnd));
}
@@ -1011,10 +1022,13 @@ impl<'de, 'a, R: Read<'de> + 'a> de::SeqAccess<'de> for SeqAccess<'a, R> {
None => {
return Err(self.de.peek_error(ErrorCode::EofWhileParsingList));
}
- }
+ };
- let value = try!(seed.deserialize(&mut *self.de));
- Ok(Some(value))
+ match peek {
+ Some(b']') => Err(self.de.peek_error(ErrorCode::TrailingComma)),
+ Some(_) => Ok(Some(try!(seed.deserialize(&mut *self.de)))),
+ None => Err(self.de.peek_error(ErrorCode::EofWhileParsingValue)),
+ }
}
}
@@ -1062,6 +1076,7 @@ impl<'de, 'a, R: Read<'de> + 'a> de::MapAccess<'de> for MapAccess<'a, R> {
match peek {
Some(b'"') => seed.deserialize(MapKey { de: &mut *self.de }).map(Some),
+ Some(b'}') => Err(self.de.peek_error(ErrorCode::TrailingComma)),
Some(_) => Err(self.de.peek_error(ErrorCode::KeyMustBeAString)),
None => Err(self.de.peek_error(ErrorCode::EofWhileParsingValue)),
}
diff --git a/src/error.rs b/src/error.rs
index bb82ad69c..90ac64c67 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -75,6 +75,7 @@ impl Error {
ErrorCode::InvalidUnicodeCodePoint |
ErrorCode::KeyMustBeAString |
ErrorCode::LoneLeadingSurrogateInHexEscape |
+ ErrorCode::TrailingComma |
ErrorCode::TrailingCharacters |
ErrorCode::UnexpectedEndOfHexEscape |
ErrorCode::RecursionLimitExceeded => Category::Syntax,
@@ -244,6 +245,9 @@ pub enum ErrorCode {
/// Lone leading surrogate in hex escape.
LoneLeadingSurrogateInHexEscape,
+ /// JSON has a comma after the last value in an array or map.
+ TrailingComma,
+
/// JSON has non-whitespace trailing characters after the value.
TrailingCharacters,
@@ -321,6 +325,7 @@ impl Display for ErrorCode {
ErrorCode::LoneLeadingSurrogateInHexEscape => {
f.write_str("lone leading surrogate in hex escape")
}
+ ErrorCode::TrailingComma => f.write_str("trailing comma"),
ErrorCode::TrailingCharacters => f.write_str("trailing characters"),
ErrorCode::UnexpectedEndOfHexEscape => f.write_str("unexpected end of hex escape"),
ErrorCode::RecursionLimitExceeded => f.write_str("recursion limit exceeded"),
|
diff --git a/tests/test.rs b/tests/test.rs
index f8ccd0c5d..84861b6db 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -894,7 +894,7 @@ fn test_parse_list() {
("[ ", "EOF while parsing a list at line 1 column 2"),
("[1", "EOF while parsing a list at line 1 column 2"),
("[1,", "EOF while parsing a value at line 1 column 3"),
- ("[1,]", "expected value at line 1 column 4"),
+ ("[1,]", "trailing comma at line 1 column 4"),
("[1 2]", "expected `,` or `]` at line 1 column 4"),
("[]a", "trailing characters at line 1 column 3"),
],
@@ -1111,9 +1111,14 @@ fn test_parse_enum_errors() {
"invalid type: map, expected tuple variant Animal::Frog at line 1 column 10"),
("{\"Cat\":[]}", "invalid length 0, expected tuple of 2 elements at line 1 column 9"),
("{\"Cat\":[0]}", "invalid length 1, expected tuple of 2 elements at line 1 column 10"),
- ("{\"Cat\":[0, \"\", 2]}", "trailing characters at line 1 column 14"),
+ ("{\"Cat\":[0, \"\", 2]}", "trailing characters at line 1 column 16"),
("{\"Cat\":{\"age\": 5, \"name\": \"Kate\", \"foo\":\"bar\"}",
"unknown field `foo`, expected `age` or `name` at line 1 column 39"),
+
+ // JSON does not allow trailing commas in data structures
+ ("{\"Cat\":[0, \"Kate\",]}", "trailing comma at line 1 column 19"),
+ ("{\"Cat\":{\"age\": 2, \"name\": \"Kate\",}}",
+ "trailing comma at line 1 column 34"),
],
);
}
|
serde-rs/json
|
cf771a0471dd797b6fead77e767f2f7943740c98
|
0.9
|
serde-rs__json-303
| 303
|
[
"183"
] |
2017-04-12T17:13:41Z
|
a22a06f74faf8bff4e474968d4a6d666125af54b
|
Expose number of bytes processed by StreamDeserializer
Use case from IRC:
> **\<Yorhel>** Hi everyone. Does serde_json support decoding JSON with trailing data?
> **\<Yorhel>** E.g. I'd like to do something in the form of: let (val, data) = serde_json::from_str("{}garbage");
> **\<Yorhel>** With val being the parsed Value and data pointing to the trailing "garbage"
Bincode has a bytes_read() method on their Deserializer that would support this much better than serde_json. You can kind of fake it like this:
```rust
let mut bytes = 0;
let stream = StreamDeserializer::new(s.bytes().map(|b| { bytes += 1; Ok(b) });
/* deserialize a thing */
let garbage = &s[bytes..];
```
But there must be a better way for us to support this.
|
diff --git a/src/de.rs b/src/de.rs
index db61ef8c3..29b68ef64 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -97,8 +97,10 @@ impl<'de, R: Read<'de>> Deserializer<R> {
{
// This cannot be an implementation of std::iter::IntoIterator because
// we need the caller to choose what T is.
+ let offset = self.read.byte_offset();
StreamDeserializer {
de: self,
+ offset: offset,
output: PhantomData,
lifetime: PhantomData,
}
@@ -1013,6 +1015,7 @@ impl<'de, 'a, R: Read<'de> + 'a> de::VariantVisitor<'de> for UnitVariantVisitor<
/// ```
pub struct StreamDeserializer<'de, R, T> {
de: Deserializer<R>,
+ offset: usize,
output: PhantomData<T>,
lifetime: PhantomData<&'de ()>,
}
@@ -1031,12 +1034,49 @@ impl<'de, R, T> StreamDeserializer<'de, R, T>
/// - Deserializer::from_iter(...).into_iter()
/// - Deserializer::from_reader(...).into_iter()
pub fn new(read: R) -> Self {
+ let offset = read.byte_offset();
StreamDeserializer {
de: Deserializer::new(read),
+ offset: offset,
output: PhantomData,
lifetime: PhantomData,
}
}
+
+ /// Returns the number of bytes so far deserialized into a successful `T`.
+ ///
+ /// If a stream deserializer returns an EOF error, new data can be joined to
+ /// `old_data[stream.byte_offset()..]` to try again.
+ ///
+ /// ```rust
+ /// let data = b"[0] [1] [";
+ ///
+ /// let de = serde_json::Deserializer::from_slice(data);
+ /// let mut stream = de.into_iter::<Vec<i32>>();
+ /// assert_eq!(0, stream.byte_offset());
+ ///
+ /// println!("{:?}", stream.next()); // [0]
+ /// assert_eq!(3, stream.byte_offset());
+ ///
+ /// println!("{:?}", stream.next()); // [1]
+ /// assert_eq!(7, stream.byte_offset());
+ ///
+ /// println!("{:?}", stream.next()); // error
+ /// assert_eq!(8, stream.byte_offset());
+ ///
+ /// // If err.is_eof(), can join the remaining data to new data and continue.
+ /// let remaining = &data[stream.byte_offset()..];
+ /// ```
+ ///
+ /// *Note:* In the future this method may be changed to return the number of
+ /// bytes so far deserialized into a successful T *or* syntactically valid
+ /// JSON skipped over due to a type error. See [serde-rs/json#70] for an
+ /// example illustrating this.
+ ///
+ /// [serde-rs/json#70]: https://github.com/serde-rs/json/issues/70
+ pub fn byte_offset(&self) -> usize {
+ self.offset
+ }
}
impl<'de, R, T> Iterator for StreamDeserializer<'de, R, T>
@@ -1050,9 +1090,17 @@ impl<'de, R, T> Iterator for StreamDeserializer<'de, R, T>
// this helps with trailing whitespaces, since whitespaces between
// values are handled for us.
match self.de.parse_whitespace() {
- Ok(None) => None,
+ Ok(None) => {
+ self.offset = self.de.read.byte_offset();
+ None
+ }
Ok(Some(b'{')) | Ok(Some(b'[')) => {
- Some(de::Deserialize::deserialize(&mut self.de))
+ self.offset = self.de.read.byte_offset();
+ let result = de::Deserialize::deserialize(&mut self.de);
+ if result.is_ok() {
+ self.offset = self.de.read.byte_offset();
+ }
+ Some(result)
}
Ok(Some(_)) => {
Some(Err(self.de.peek_error(ErrorCode::ExpectedObjectOrArray)))
diff --git a/src/iter.rs b/src/iter.rs
index fe48fe377..8d4ade83f 100644
--- a/src/iter.rs
+++ b/src/iter.rs
@@ -2,8 +2,21 @@ use std::io;
pub struct LineColIterator<I> {
iter: I,
+
+ /// Index of the current line. Characters in the first line of the input
+ /// (before the first newline character) are in line 1.
line: usize,
+
+ /// Index of the current column. The first character in the input and any
+ /// characters immediately following a newline character are in column 1.
+ /// The column is 0 immediately after a newline character has been read.
col: usize,
+
+ /// Byte offset of the start of the current line. This is the sum of lenghts
+ /// of all previous lines. Keeping track of things this way allows efficient
+ /// computation of the current line, column, and byte offset while only
+ /// updating one of the counters in `next()` in the common case.
+ start_of_line: usize,
}
impl<I> LineColIterator<I>
@@ -14,6 +27,7 @@ impl<I> LineColIterator<I>
iter: iter,
line: 1,
col: 0,
+ start_of_line: 0,
}
}
@@ -24,6 +38,10 @@ impl<I> LineColIterator<I>
pub fn col(&self) -> usize {
self.col
}
+
+ pub fn byte_offset(&self) -> usize {
+ self.start_of_line + self.col
+ }
}
impl<I> Iterator for LineColIterator<I>
@@ -35,6 +53,7 @@ impl<I> Iterator for LineColIterator<I>
match self.iter.next() {
None => None,
Some(Ok(b'\n')) => {
+ self.start_of_line += self.col + 1;
self.line += 1;
self.col = 0;
Some(Ok(b'\n'))
diff --git a/src/read.rs b/src/read.rs
index c3711fec4..2a9cfeffc 100644
--- a/src/read.rs
+++ b/src/read.rs
@@ -40,6 +40,11 @@ pub trait Read<'de>: private::Sealed {
#[doc(hidden)]
fn peek_position(&self) -> Position;
+ /// Offset from the beginning of the input to the next byte that would be
+ /// returned by next() or peek().
+ #[doc(hidden)]
+ fn byte_offset(&self) -> usize;
+
/// Assumes the previous byte was a quotation mark. Parses a JSON-escaped
/// string until the next quotation mark using the given scratch space if
/// necessary. The scratch space is initially empty.
@@ -215,6 +220,13 @@ impl<'de, Iter> Read<'de> for IteratorRead<Iter>
self.position()
}
+ fn byte_offset(&self) -> usize {
+ match self.ch {
+ Some(_) => self.iter.byte_offset() - 1,
+ None => self.iter.byte_offset(),
+ }
+ }
+
fn parse_str<'s>(
&'s mut self,
scratch: &'s mut Vec<u8>
@@ -274,6 +286,11 @@ impl<'de, R> Read<'de> for IoRead<R>
self.delegate.peek_position()
}
+ #[inline]
+ fn byte_offset(&self) -> usize {
+ self.delegate.byte_offset()
+ }
+
#[inline]
fn parse_str<'s>(
&'s mut self,
@@ -419,6 +436,10 @@ impl<'a> Read<'a> for SliceRead<'a> {
self.position_of_index(cmp::min(self.slice.len(), self.index + 1))
}
+ fn byte_offset(&self) -> usize {
+ self.index
+ }
+
fn parse_str<'s>(
&'s mut self,
scratch: &'s mut Vec<u8>
@@ -472,6 +493,10 @@ impl<'a> Read<'a> for StrRead<'a> {
self.delegate.peek_position()
}
+ fn byte_offset(&self) -> usize {
+ self.delegate.byte_offset()
+ }
+
fn parse_str<'s>(
&'s mut self,
scratch: &'s mut Vec<u8>
|
diff --git a/tests/stream.rs b/tests/stream.rs
new file mode 100644
index 000000000..e4f573098
--- /dev/null
+++ b/tests/stream.rs
@@ -0,0 +1,109 @@
+#![cfg(not(feature = "preserve_order"))]
+
+extern crate serde;
+
+#[macro_use]
+extern crate serde_json;
+
+use serde_json::{Deserializer, Value};
+
+macro_rules! test_stream {
+ ($data:expr, $ty:ty, |$stream:ident| $test:block) => {
+ {
+ let de = Deserializer::from_str($data);
+ let mut $stream = de.into_iter::<$ty>();
+ assert_eq!($stream.byte_offset(), 0);
+ $test
+ }
+ {
+ let de = Deserializer::from_slice($data.as_bytes());
+ let mut $stream = de.into_iter::<$ty>();
+ assert_eq!($stream.byte_offset(), 0);
+ $test
+ }
+ {
+ let de = Deserializer::from_iter($data.bytes().map(Ok));
+ let mut $stream = de.into_iter::<$ty>();
+ assert_eq!($stream.byte_offset(), 0);
+ $test
+ }
+ {
+ let mut bytes = $data.as_bytes();
+ let de = Deserializer::from_reader(&mut bytes);
+ let mut $stream = de.into_iter::<$ty>();
+ assert_eq!($stream.byte_offset(), 0);
+ $test
+ }
+ }
+}
+
+#[test]
+fn test_json_stream_newlines() {
+ let data = "{\"x\":39} {\"x\":40}{\"x\":41}\n{\"x\":42}";
+
+ test_stream!(data, Value, |stream| {
+ assert_eq!(stream.next().unwrap().unwrap()["x"], 39);
+ assert_eq!(stream.byte_offset(), 8);
+
+ assert_eq!(stream.next().unwrap().unwrap()["x"], 40);
+ assert_eq!(stream.byte_offset(), 17);
+
+ assert_eq!(stream.next().unwrap().unwrap()["x"], 41);
+ assert_eq!(stream.byte_offset(), 25);
+
+ assert_eq!(stream.next().unwrap().unwrap()["x"], 42);
+ assert_eq!(stream.byte_offset(), 34);
+
+ assert!(stream.next().is_none());
+ assert_eq!(stream.byte_offset(), 34);
+ });
+}
+
+#[test]
+fn test_json_stream_trailing_whitespaces() {
+ let data = "{\"x\":42} \t\n";
+
+ test_stream!(data, Value, |stream| {
+ assert_eq!(stream.next().unwrap().unwrap()["x"], 42);
+ assert_eq!(stream.byte_offset(), 8);
+
+ assert!(stream.next().is_none());
+ assert_eq!(stream.byte_offset(), 11);
+ });
+}
+
+#[test]
+fn test_json_stream_truncated() {
+ let data = "{\"x\":40}\n{\"x\":";
+
+ test_stream!(data, Value, |stream| {
+ assert_eq!(stream.next().unwrap().unwrap()["x"], 40);
+ assert_eq!(stream.byte_offset(), 8);
+
+ assert!(stream.next().unwrap().unwrap_err().is_eof());
+ assert_eq!(stream.byte_offset(), 9);
+ });
+}
+
+#[test]
+fn test_json_stream_empty() {
+ let data = "";
+
+ test_stream!(data, Value, |stream| {
+ assert!(stream.next().is_none());
+ assert_eq!(stream.byte_offset(), 0);
+ });
+}
+
+#[test]
+fn test_json_stream_primitive() {
+ let data = "{} true";
+
+ test_stream!(data, Value, |stream| {
+ assert_eq!(stream.next().unwrap().unwrap(), json!({}));
+ assert_eq!(stream.byte_offset(), 2);
+
+ let second = stream.next().unwrap().unwrap_err();
+ assert_eq!(second.to_string(), "expected `{` or `[` at line 1 column 4");
+ });
+}
diff --git a/tests/test.rs b/tests/test.rs
index 95aa2ddd6..cb831cdd9 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -33,7 +33,6 @@ use serde_bytes::{ByteBuf, Bytes};
use serde_json::{
Deserializer,
- Map,
Value,
from_iter,
from_reader,
@@ -1634,57 +1633,6 @@ fn test_byte_buf_de_multiple() {
assert_eq!(vec![a, b], s);
}
-#[test]
-fn test_json_stream_newlines() {
- let data = "{\"x\":39} {\"x\":40}{\"x\":41}\n{\"x\":42}";
- let mut parsed = Deserializer::from_str(data).into_iter::<Value>();
-
- assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(), 39);
- assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(), 40);
- assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(), 41);
- assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(), 42);
- assert!(parsed.next().is_none());
-}
-
-#[test]
-fn test_json_stream_trailing_whitespaces() {
- let data = "{\"x\":42} \t\n";
- let mut parsed = Deserializer::from_str(data).into_iter::<Value>();
-
- assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(), 42);
- assert!(parsed.next().is_none());
-}
-
-#[test]
-fn test_json_stream_truncated() {
- let data = "{\"x\":40}\n{\"x\":";
- let mut parsed = Deserializer::from_str(data).into_iter::<Value>();
-
- assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(), 40);
- assert!(parsed.next().unwrap().is_err());
- assert!(parsed.next().is_none());
-}
-
-#[test]
-fn test_json_stream_empty() {
- let data = "";
- let mut parsed = Deserializer::from_str(data).into_iter::<Value>();
-
- assert!(parsed.next().is_none());
-}
-
-#[test]
-fn test_json_stream_primitive() {
- let data = "{} true";
- let mut parsed = Deserializer::from_str(data).into_iter::<Value>();
-
- let first = parsed.next().unwrap().unwrap();
- assert_eq!(first, Value::Object(Map::new()));
-
- let second = parsed.next().unwrap().unwrap_err();
- assert_eq!(second.to_string(), "expected `{` or `[` at line 1 column 4");
-}
-
#[test]
fn test_json_pointer() {
// Test case taken from https://tools.ietf.org/html/rfc6901#page-5
|
serde-rs/json
|
a22a06f74faf8bff4e474968d4a6d666125af54b
|
|
null |
serde-rs__json-302
| 302
|
[
"266"
] |
2017-04-12T04:11:39Z
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
Combine serde_json and serde_json_tests into one crate
These have been separated historically because it was not possible for serde_json to have an optional dev-dependency on serde_derive (https://github.com/rust-lang/cargo/issues/1596).
Now that serde_derive is not optional, it would be simpler to structure the repo in the way serde_urlencoded does, for example.
cc @nox
|
diff --git a/Cargo.toml b/Cargo.toml
index ed69eecdc..e7c52d24f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,5 +1,31 @@
-[workspace]
-members = [
- "json",
- "json_tests",
-]
+[package]
+name = "serde_json"
+version = "0.9.10"
+authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
+license = "MIT/Apache-2.0"
+description = "A JSON serialization file format"
+repository = "https://github.com/serde-rs/json"
+documentation = "http://docs.serde.rs/serde_json/"
+keywords = ["json", "serde", "serialization"]
+categories = ["encoding"]
+readme = "../README.md"
+include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
+publish = false # this branch contains breaking changes
+
+[badges]
+travis-ci = { repository = "serde-rs/json" }
+
+[features]
+preserve_order = ["linked-hash-map"]
+
+[dependencies]
+serde = { git = "https://github.com/serde-rs/serde", branch = "1.0" }
+num-traits = "0.1.32"
+linked-hash-map = { version = "0.4.1", optional = true }
+itoa = "0.3"
+dtoa = "0.4"
+
+[dev-dependencies]
+compiletest_rs = "0.2"
+serde_bytes = { git = "https://github.com/serde-rs/bytes", branch = "1.0" }
+serde_derive = { git = "https://github.com/serde-rs/serde", branch = "1.0" }
diff --git a/json/Cargo.toml b/json/Cargo.toml
deleted file mode 100644
index 6c3f8b0e5..000000000
--- a/json/Cargo.toml
+++ /dev/null
@@ -1,30 +0,0 @@
-[package]
-name = "serde_json"
-version = "0.9.10"
-authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
-license = "MIT/Apache-2.0"
-description = "A JSON serialization file format"
-repository = "https://github.com/serde-rs/json"
-documentation = "http://docs.serde.rs/serde_json/"
-keywords = ["json", "serde", "serialization"]
-categories = ["encoding"]
-readme = "../README.md"
-include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
-publish = false # this branch contains breaking changes
-
-[badges]
-travis-ci = { repository = "serde-rs/json" }
-
-[features]
-preserve_order = ["linked-hash-map"]
-
-[dependencies]
-serde = { git = "https://github.com/serde-rs/serde", branch = "1.0" }
-num-traits = "0.1.32"
-linked-hash-map = { version = "0.4.1", optional = true }
-itoa = "0.3"
-dtoa = "0.4"
-
-[dev-dependencies]
-serde_bytes = { git = "https://github.com/serde-rs/bytes", branch = "1.0" }
-serde_derive = { git = "https://github.com/serde-rs/serde", branch = "1.0" }
diff --git a/json/LICENSE-APACHE b/json/LICENSE-APACHE
deleted file mode 120000
index 965b606f3..000000000
--- a/json/LICENSE-APACHE
+++ /dev/null
@@ -1,1 +0,0 @@
-../LICENSE-APACHE
\ No newline at end of file
diff --git a/json/LICENSE-MIT b/json/LICENSE-MIT
deleted file mode 120000
index 76219eb72..000000000
--- a/json/LICENSE-MIT
+++ /dev/null
@@ -1,1 +0,0 @@
-../LICENSE-MIT
\ No newline at end of file
diff --git a/json/README.md b/json/README.md
deleted file mode 120000
index 32d46ee88..000000000
--- a/json/README.md
+++ /dev/null
@@ -1,1 +0,0 @@
-../README.md
\ No newline at end of file
diff --git a/json/src/de.rs b/src/de.rs
similarity index 100%
rename from json/src/de.rs
rename to src/de.rs
diff --git a/json/src/error.rs b/src/error.rs
similarity index 100%
rename from json/src/error.rs
rename to src/error.rs
diff --git a/json/src/iter.rs b/src/iter.rs
similarity index 100%
rename from json/src/iter.rs
rename to src/iter.rs
diff --git a/json/src/lib.rs b/src/lib.rs
similarity index 100%
rename from json/src/lib.rs
rename to src/lib.rs
diff --git a/json/src/macros.rs b/src/macros.rs
similarity index 100%
rename from json/src/macros.rs
rename to src/macros.rs
diff --git a/json/src/map.rs b/src/map.rs
similarity index 100%
rename from json/src/map.rs
rename to src/map.rs
diff --git a/json/src/number.rs b/src/number.rs
similarity index 100%
rename from json/src/number.rs
rename to src/number.rs
diff --git a/json/src/read.rs b/src/read.rs
similarity index 100%
rename from json/src/read.rs
rename to src/read.rs
diff --git a/json/src/ser.rs b/src/ser.rs
similarity index 100%
rename from json/src/ser.rs
rename to src/ser.rs
diff --git a/json/src/value.rs b/src/value.rs
similarity index 100%
rename from json/src/value.rs
rename to src/value.rs
diff --git a/travis.sh b/travis.sh
index 84b56caf3..3acf126ee 100755
--- a/travis.sh
+++ b/travis.sh
@@ -28,25 +28,16 @@ if [ -n "${CLIPPY}" ]; then
exit
fi
- cd "$DIR/json"
- cargo clippy -- -Dclippy
-
- cd "$DIR/json_tests"
cargo clippy -- -Dclippy
else
CHANNEL=nightly
- cd "$DIR/json"
channel clean
channel build
- channel build --features preserve_order
+ (cd "$DIR/tests/deps" && channel build)
channel test
- cd "$DIR/json_tests/deps"
- channel build
- cd "$DIR/json_tests"
- channel test --features unstable-testing
+ channel test --features preserve_order
for CHANNEL in stable 1.12.0 1.13.0 beta; do
- cd "$DIR/json"
channel clean
channel build
channel build --features preserve_order
|
diff --git a/json_tests/Cargo.toml b/json_tests/Cargo.toml
deleted file mode 100644
index e3c2711e5..000000000
--- a/json_tests/Cargo.toml
+++ /dev/null
@@ -1,18 +0,0 @@
-[package]
-name = "serde_json_tests"
-version = "0.0.0"
-authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
-publish = false
-
-[features]
-trace-macros = []
-unstable-testing = ["compiletest_rs"]
-
-[dev-dependencies]
-serde = { git = "https://github.com/serde-rs/serde", branch = "1.0" }
-serde_bytes = { git = "https://github.com/serde-rs/bytes", branch = "1.0" }
-serde_json = { path = "../json" }
-serde_derive = { git = "https://github.com/serde-rs/serde", branch = "1.0" }
-
-[dependencies]
-compiletest_rs = { version = "0.2", optional = true }
diff --git a/json_tests/tests/compiletest.rs b/tests/compiletest.rs
similarity index 78%
rename from json_tests/tests/compiletest.rs
rename to tests/compiletest.rs
index f6585b915..2fa1bb63d 100644
--- a/json_tests/tests/compiletest.rs
+++ b/tests/compiletest.rs
@@ -1,5 +1,3 @@
-#![cfg(feature = "unstable-testing")]
-
extern crate compiletest_rs as compiletest;
use std::env;
@@ -8,7 +6,7 @@ fn run_mode(mode: &'static str) {
let mut config = compiletest::default_config();
config.mode = mode.parse().expect("invalid mode");
- config.target_rustcflags = Some("-L deps/target/debug/deps".to_owned());
+ config.target_rustcflags = Some("-L tests/deps/target/debug/deps".to_owned());
if let Ok(name) = env::var("TESTNAME") {
config.filter = Some(name);
}
diff --git a/json_tests/deps/Cargo.toml b/tests/deps/Cargo.toml
similarity index 80%
rename from json_tests/deps/Cargo.toml
rename to tests/deps/Cargo.toml
index 6bf64b594..5af31f627 100644
--- a/json_tests/deps/Cargo.toml
+++ b/tests/deps/Cargo.toml
@@ -7,4 +7,4 @@ publish = false
[workspace]
[dependencies]
-serde_json = { path = "../../json" }
+serde_json = { path = "../.." }
diff --git a/json_tests/deps/src/lib.rs b/tests/deps/src/lib.rs
similarity index 100%
rename from json_tests/deps/src/lib.rs
rename to tests/deps/src/lib.rs
diff --git a/json_tests/tests/macros.rs b/tests/macros.rs
similarity index 100%
rename from json_tests/tests/macros.rs
rename to tests/macros.rs
diff --git a/json_tests/tests/test.rs b/tests/test.rs
similarity index 100%
rename from json_tests/tests/test.rs
rename to tests/test.rs
diff --git a/json_tests/tests/ui/missing_colon.rs b/tests/ui/missing_colon.rs
similarity index 100%
rename from json_tests/tests/ui/missing_colon.rs
rename to tests/ui/missing_colon.rs
diff --git a/json_tests/tests/ui/missing_colon.stderr b/tests/ui/missing_colon.stderr
similarity index 100%
rename from json_tests/tests/ui/missing_colon.stderr
rename to tests/ui/missing_colon.stderr
diff --git a/json_tests/tests/ui/missing_value.rs b/tests/ui/missing_value.rs
similarity index 100%
rename from json_tests/tests/ui/missing_value.rs
rename to tests/ui/missing_value.rs
diff --git a/json_tests/tests/ui/missing_value.stderr b/tests/ui/missing_value.stderr
similarity index 100%
rename from json_tests/tests/ui/missing_value.stderr
rename to tests/ui/missing_value.stderr
diff --git a/json_tests/tests/ui/not_found.rs b/tests/ui/not_found.rs
similarity index 100%
rename from json_tests/tests/ui/not_found.rs
rename to tests/ui/not_found.rs
diff --git a/json_tests/tests/ui/not_found.stderr b/tests/ui/not_found.stderr
similarity index 100%
rename from json_tests/tests/ui/not_found.stderr
rename to tests/ui/not_found.stderr
diff --git a/json_tests/tests/ui/parse_expr.rs b/tests/ui/parse_expr.rs
similarity index 100%
rename from json_tests/tests/ui/parse_expr.rs
rename to tests/ui/parse_expr.rs
diff --git a/json_tests/tests/ui/parse_expr.stderr b/tests/ui/parse_expr.stderr
similarity index 100%
rename from json_tests/tests/ui/parse_expr.stderr
rename to tests/ui/parse_expr.stderr
diff --git a/json_tests/tests/ui/parse_key.rs b/tests/ui/parse_key.rs
similarity index 100%
rename from json_tests/tests/ui/parse_key.rs
rename to tests/ui/parse_key.rs
diff --git a/json_tests/tests/ui/parse_key.stderr b/tests/ui/parse_key.stderr
similarity index 100%
rename from json_tests/tests/ui/parse_key.stderr
rename to tests/ui/parse_key.stderr
diff --git a/json_tests/tests/ui/unexpected_colon.rs b/tests/ui/unexpected_colon.rs
similarity index 100%
rename from json_tests/tests/ui/unexpected_colon.rs
rename to tests/ui/unexpected_colon.rs
diff --git a/json_tests/tests/ui/unexpected_colon.stderr b/tests/ui/unexpected_colon.stderr
similarity index 100%
rename from json_tests/tests/ui/unexpected_colon.stderr
rename to tests/ui/unexpected_colon.stderr
diff --git a/json_tests/tests/ui/unexpected_comma.rs b/tests/ui/unexpected_comma.rs
similarity index 100%
rename from json_tests/tests/ui/unexpected_comma.rs
rename to tests/ui/unexpected_comma.rs
diff --git a/json_tests/tests/ui/unexpected_comma.stderr b/tests/ui/unexpected_comma.stderr
similarity index 100%
rename from json_tests/tests/ui/unexpected_comma.stderr
rename to tests/ui/unexpected_comma.stderr
diff --git a/json_tests/tests/ui/update-references.sh b/tests/ui/update-references.sh
similarity index 100%
rename from json_tests/tests/ui/update-references.sh
rename to tests/ui/update-references.sh
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
|
null |
serde-rs__json-301
| 301
|
[
"300"
] |
2017-04-11T23:28:29Z
|
565e692cafafbf16a960de43d98f29d438fe461a
|
StreamDeserializer should only accept arrays and objects
```json
// ok
{"a":0}{"a":1}
// not ok
falsetrue
// also not ok
false true
```
Supersedes #56 which intended to support other types as long as they were separated by whitespace. I am open to extending support to types in the future as long as somebody has a compelling concrete use case.
This lets us ignore ambiguities such as https://github.com/serde-rs/json/pull/212#issuecomment-280212280.
|
diff --git a/json/src/de.rs b/json/src/de.rs
index cad22c792..a0efe53ed 100644
--- a/json/src/de.rs
+++ b/json/src/de.rs
@@ -992,13 +992,17 @@ impl<'de, 'a, R: Read<'de> + 'a> de::VariantVisitor<'de> for UnitVariantVisitor<
/// A stream deserializer can be created from any JSON deserializer using the
/// `Deserializer::into_iter` method.
///
+/// The data must consist of JSON arrays and JSON objects optionally separated
+/// by whitespace. A null, boolean, number, or string at the top level are all
+/// errors.
+///
/// ```rust
/// extern crate serde_json;
///
/// use serde_json::{Deserializer, Value};
///
/// fn main() {
-/// let data = "1 2 {\"k\": 3}";
+/// let data = "{\"k\": 3} {} [0, 1, 2]";
///
/// let stream = Deserializer::from_str(data).into_iter::<Value>();
///
@@ -1047,9 +1051,12 @@ impl<'de, R, T> Iterator for StreamDeserializer<'de, R, T>
// values are handled for us.
match self.de.parse_whitespace() {
Ok(None) => None,
- Ok(Some(_)) => {
+ Ok(Some(b'{')) | Ok(Some(b'[')) => {
Some(de::Deserialize::deserialize(&mut self.de))
}
+ Ok(Some(_)) => {
+ Some(Err(self.de.peek_error(ErrorCode::ExpectedObjectOrArray)))
+ }
Err(e) => Some(Err(e)),
}
}
diff --git a/json/src/error.rs b/json/src/error.rs
index 11000321b..00ff9c4c3 100644
--- a/json/src/error.rs
+++ b/json/src/error.rs
@@ -57,6 +57,7 @@ impl Error {
ErrorCode::ExpectedColon |
ErrorCode::ExpectedListCommaOrEnd |
ErrorCode::ExpectedObjectCommaOrEnd |
+ ErrorCode::ExpectedObjectOrArray |
ErrorCode::ExpectedSomeIdent |
ErrorCode::ExpectedSomeValue |
ErrorCode::ExpectedSomeString |
@@ -203,12 +204,15 @@ pub enum ErrorCode {
/// Expected this character to be a `':'`.
ExpectedColon,
- /// Expected this character to be either a `','` or a `]`.
+ /// Expected this character to be either a `','` or a `']'`.
ExpectedListCommaOrEnd,
- /// Expected this character to be either a `','` or a `}`.
+ /// Expected this character to be either a `','` or a `'}'`.
ExpectedObjectCommaOrEnd,
+ /// Expected this character to be either a `'{'` or a `'['`.
+ ExpectedObjectOrArray,
+
/// Expected to parse either a `true`, `false`, or a `null`.
ExpectedSomeIdent,
@@ -294,6 +298,9 @@ impl Display for ErrorCode {
ErrorCode::ExpectedObjectCommaOrEnd => {
f.write_str("expected `,` or `}`")
}
+ ErrorCode::ExpectedObjectOrArray => {
+ f.write_str("expected `{` or `[`")
+ }
ErrorCode::ExpectedSomeIdent => {
f.write_str("expected ident")
}
|
diff --git a/json_tests/tests/test.rs b/json_tests/tests/test.rs
index 93f273d33..4500f9fec 100644
--- a/json_tests/tests/test.rs
+++ b/json_tests/tests/test.rs
@@ -31,6 +31,7 @@ use serde_bytes::{ByteBuf, Bytes};
use serde_json::{
Deserializer,
+ Map,
Value,
from_iter,
from_reader,
@@ -1670,6 +1671,18 @@ fn test_json_stream_empty() {
assert!(parsed.next().is_none());
}
+#[test]
+fn test_json_stream_primitive() {
+ let data = "{} true";
+ let mut parsed = Deserializer::from_str(data).into_iter::<Value>();
+
+ let first = parsed.next().unwrap().unwrap();
+ assert_eq!(first, Value::Object(Map::new()));
+
+ let second = parsed.next().unwrap().unwrap_err();
+ assert_eq!(second.to_string(), "expected `{` or `[` at line 1 column 4");
+}
+
#[test]
fn test_json_pointer() {
// Test case taken from https://tools.ietf.org/html/rfc6901#page-5
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
|
null |
serde-rs__json-295
| 295
|
[
"294"
] |
2017-04-11T18:06:29Z
|
f5094829a885d78d0dd1d3797f9e730df13a7a71
|
Remove ToJson trait
This trait was ripped directly from [`rustc_serialize::json::ToJson`](https://docs.rs/rustc-serialize/0.3.23/rustc_serialize/json/trait.ToJson.html) but the point was lost by providing an impl ToJson for T where T: Serialize. The rustc_serialize trait is infallible and there are impls for standard library types that can be infallibly converted to Json - not for all types that implement Encodable.
I don't think the trait as it currently exists serves a purpose. The fallible use case is covered by serde_json::to_value and the literal use case is covered by the `json!` macro.
I would be open to seeing an infallible ToJson trait explored in its own crate - ideally complete with its own custom derive which is distinct from serde's Serialize.
```rust
#[derive(ToJson)]
struct S {
a: u8,
b: u8,
}
// The generated code:
impl ToJson for S {
fn to_json(&self) -> serde_json::Value {
json!({
"a": ToJson::to_json(&self.a),
"b": ToJson::to_json(&self.b),
})
}
}
```
|
diff --git a/json/src/macros.rs b/json/src/macros.rs
index 4145737de..e4dbb72ba 100644
--- a/json/src/macros.rs
+++ b/json/src/macros.rs
@@ -266,6 +266,6 @@ macro_rules! json_internal {
// Any Serialize type: numbers, strings, struct literals, variables etc.
// Must be below every other rule.
($other:expr) => {
- $crate::value::ToJson::to_json(&$other).unwrap()
+ $crate::to_value(&$other).unwrap()
};
}
diff --git a/json/src/value.rs b/json/src/value.rs
index 91cfc4e2c..1485b9be0 100644
--- a/json/src/value.rs
+++ b/json/src/value.rs
@@ -2251,21 +2251,3 @@ pub fn from_value<T>(value: Value) -> Result<T, Error>
{
de::Deserialize::deserialize(value)
}
-
-/// Representation of any serializable data as a `serde_json::Value`.
-pub trait ToJson {
- /// Represent `self` as a `serde_json::Value`. Note that `Value` is not a
- /// JSON string. If you need a string, use `serde_json::to_string` instead.
- ///
- /// This conversion can fail if `T`'s implementation of `Serialize` decides
- /// to fail, or if `T` contains a map with non-string keys.
- fn to_json(&self) -> Result<Value, Error>;
-}
-
-impl<T: ?Sized> ToJson for T
- where T: ser::Serialize,
-{
- fn to_json(&self) -> Result<Value, Error> {
- to_value(self)
- }
-}
|
diff --git a/json_tests/tests/test.rs b/json_tests/tests/test.rs
index 81c4d6e97..93f273d33 100644
--- a/json_tests/tests/test.rs
+++ b/json_tests/tests/test.rs
@@ -31,7 +31,6 @@ use serde_bytes::{ByteBuf, Bytes};
use serde_json::{
Deserializer,
- Error,
Value,
from_iter,
from_reader,
@@ -44,7 +43,6 @@ use serde_json::{
to_vec,
to_writer,
};
-use serde_json::value::ToJson;
macro_rules! treemap {
() => {
@@ -1849,18 +1847,6 @@ fn test_json_macro() {
});
}
-#[test]
-fn test_json_not_serializable() {
- // Does not implement Serialize
- struct S;
- impl ToJson for S {
- fn to_json(&self) -> Result<Value, Error> {
- Ok(Value::String("S".to_owned()))
- }
- }
- assert_eq!(Value::String("S".to_owned()), json!(S));
-}
-
#[test]
fn issue_220() {
#[derive(Debug, PartialEq, Eq, Deserialize)]
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
|
null |
serde-rs__json-278
| 278
|
[
"245"
] |
2017-03-12T20:40:52Z
|
Let's add:
- is_eof()
- is_syntax()
- is_io()
where I think eof errors are not syntax errors.
Just to clarify, if I have a struct, let's say:
```rust
#[derive(deserialize)]
struct Point {
x: u64,
y: u64,
};
```
And pass this JSON:
```json
{"a": 16}
```
What kind of error is this? It's not exactly syntax error, it just doesn't fit into the form. Maybe having another one for these kinds of errors would be nice?
I'd prefer making IO error associated type, so that if you parse from `&str`, it's statically known that IO error can't occur. Similarly, in case of serialising, no error can happen at all.
> What kind of error is this? It's not exactly syntax error, it just doesn't fit into the form. Maybe having another one for these kinds of errors would be nice?
Let's call this a data error - the syntax was valid but the data was wrong somehow. err.is_data()?
> I'd prefer making IO error associated type, so that if you parse from `&str`, it's statically known that IO error can't occur.
@Kixunil can you explain more about your use case that requires you to differentiate between IO errors and other types of errors? What are you doing that is more than just printing the error as a string, and why is it beneficial to know that IO errors can't occur?
> Let's call this a data error - the syntax was valid but the data was wrong somehow. err.is_data()?
That sounds like a good name to me :-).
@dtolnay I believe that it's more expressive design. The reasons led me to create [`genio`](https://github.com/Kixunil/genio) crate. In case of serde, serialisation is more interesting to me regarding error type.
I wrote `serde_json::to_string(my_obj).unwrap(); // Serialising to string can't fail.` but I have no way to be 100% sure it can't fail. If someone accidentally writes a code in library that would return `Err` my program would panic.
> What are you doing that is more than just printing the error as a string
I'm translating error messages. In case of `io::Error` I check if it's system error for which I have translation function. If it's not, I pass error untranslated. In case of `serde_json::Error` I have to pass all errors untranslated (even those that could be otherwise. Also, `serde_json::Error` doesn't provide any useful information beside error message, so I can't create translation for it. (This is not a blocker, but it'd be nice feature to have and use later.)
P.S.: Would be awesome if `serde_json` supported `genio`.
@Kixunil serde_json::to_string fails in both of these cases. Does that affect your perspective at all?
These are the cases noted in the serde_json::to_string [documentation](https://docs.serde.rs/serde_json/fn.to_string.html).
```rust
extern crate serde;
extern crate serde_json;
use std::collections::BTreeMap as Map;
use serde::{Serialize, Serializer};
struct S(u8);
impl Serialize for S {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
match self.0 {
0 => Err(serde::ser::Error::custom("zero is my least favorite byte")),
_ => serializer.serialize_u8(self.0),
}
}
}
fn main() {
println!("{}", serde_json::to_string(&S(0)).unwrap_err());
let mut map = Map::new();
map.insert(vec!["K"], "V");
println!("{}", serde_json::to_string(&map).unwrap_err());
}
```
Oh, shit, I didn't notice. Is there a way to require `S::Error` to be `void::Void`? Could the "map with non-string keys" be checked statically?
|
b4adb3c4a4eb32645884fd48485eb56e0c650b07
|
Expose whether error is caused by EOF
In streaming use cases you want to treat `{"x": true,` differently from `{]`. One of them you retry later once you have more data, the other is just an error.
cc @vorner
|
diff --git a/json/src/de.rs b/json/src/de.rs
index 864619eba..b93aad75e 100644
--- a/json/src/de.rs
+++ b/json/src/de.rs
@@ -159,7 +159,7 @@ impl<R: Read> Deserializer<R> {
where V: de::Visitor,
{
if try!(self.parse_whitespace()) { // true if eof
- return Err(self.peek_error(ErrorCode::EOFWhileParsingValue));
+ return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
}
let value = match try!(self.peek_or_null()) {
@@ -526,7 +526,7 @@ impl<R: Read> Deserializer<R> {
Ok(())
}
Some(_) => Err(self.peek_error(ErrorCode::ExpectedColon)),
- None => Err(self.peek_error(ErrorCode::EOFWhileParsingObject)),
+ None => Err(self.peek_error(ErrorCode::EofWhileParsingObject)),
}
}
@@ -536,7 +536,7 @@ impl<R: Read> Deserializer<R> {
match try!(self.next_char()) {
Some(b']') => Ok(()),
Some(_) => Err(self.error(ErrorCode::TrailingCharacters)),
- None => Err(self.error(ErrorCode::EOFWhileParsingList)),
+ None => Err(self.error(ErrorCode::EofWhileParsingList)),
}
}
@@ -546,7 +546,7 @@ impl<R: Read> Deserializer<R> {
match try!(self.next_char()) {
Some(b'}') => Ok(()),
Some(_) => Err(self.error(ErrorCode::TrailingCharacters)),
- None => Err(self.error(ErrorCode::EOFWhileParsingObject)),
+ None => Err(self.error(ErrorCode::EofWhileParsingObject)),
}
}
}
@@ -765,7 +765,7 @@ impl<'a, R: Read + 'a> de::SeqVisitor for SeqVisitor<'a, R> {
}
}
None => {
- return Err(self.de.peek_error(ErrorCode::EOFWhileParsingList));
+ return Err(self.de.peek_error(ErrorCode::EofWhileParsingList));
}
}
@@ -814,14 +814,14 @@ impl<'a, R: Read + 'a> de::MapVisitor for MapVisitor<'a, R> {
}
None => {
return Err(self.de
- .peek_error(ErrorCode::EOFWhileParsingObject));
+ .peek_error(ErrorCode::EofWhileParsingObject));
}
}
match try!(self.de.peek()) {
Some(b'"') => Ok(Some(try!(seed.deserialize(&mut *self.de)))),
Some(_) => Err(self.de.peek_error(ErrorCode::KeyMustBeAString)),
- None => Err(self.de.peek_error(ErrorCode::EOFWhileParsingValue)),
+ None => Err(self.de.peek_error(ErrorCode::EofWhileParsingValue)),
}
}
diff --git a/json/src/error.rs b/json/src/error.rs
index 53f5e26f3..1d5ecbfe4 100644
--- a/json/src/error.rs
+++ b/json/src/error.rs
@@ -11,38 +11,149 @@ use serde::ser;
/// This type represents all possible errors that can occur when serializing or
/// deserializing JSON data.
pub struct Error {
+ /// This `Box` allows us to keep the size of `Error` as small as possible. A
+ /// larger `Error` type was substantially slower due to all the functions
+ /// that pass around `Result<T, Error>`.
err: Box<ErrorImpl>,
}
/// Alias for a `Result` with the error type `serde_json::Error`.
pub type Result<T> = result::Result<T, Error>;
-enum ErrorImpl {
- /// The JSON value had some syntatic error.
- Syntax(ErrorCode, usize, usize),
+impl Error {
+ /// One-based line number at which the error was detected.
+ ///
+ /// Characters in the first line of the input (before the first newline
+ /// character) are in line 1.
+ pub fn line(&self) -> usize {
+ self.err.line
+ }
- /// Some IO error occurred when serializing or deserializing a value.
- Io(io::Error),
+ /// One-based column number at which the error was detected.
+ ///
+ /// The first character in the input and any characters immediately
+ /// following a newline character are in column 1.
+ ///
+ /// Note that errors may occur in column 0, for example if a read from an IO
+ /// stream fails immediately following a previously read newline character.
+ pub fn column(&self) -> usize {
+ self.err.column
+ }
+
+ /// Categorizes the cause of this error.
+ ///
+ /// - `Category::Io` - failure to read or write bytes on an IO stream
+ /// - `Category::Syntax` - input that is not syntactically valid JSON
+ /// - `Category::Data` - input data that is semantically incorrect
+ /// - `Category::Eof` - unexpected end of the input data
+ pub fn classify(&self) -> Category {
+ match self.err.code {
+ ErrorCode::Message(_) => Category::Data,
+ ErrorCode::Io(_) => Category::Io,
+ ErrorCode::EofWhileParsingList |
+ ErrorCode::EofWhileParsingObject |
+ ErrorCode::EofWhileParsingString |
+ ErrorCode::EofWhileParsingValue => Category::Eof,
+ ErrorCode::ExpectedColon |
+ ErrorCode::ExpectedListCommaOrEnd |
+ ErrorCode::ExpectedObjectCommaOrEnd |
+ ErrorCode::ExpectedSomeIdent |
+ ErrorCode::ExpectedSomeValue |
+ ErrorCode::ExpectedSomeString |
+ ErrorCode::InvalidEscape |
+ ErrorCode::InvalidNumber |
+ ErrorCode::NumberOutOfRange |
+ ErrorCode::InvalidUnicodeCodePoint |
+ ErrorCode::KeyMustBeAString |
+ ErrorCode::LoneLeadingSurrogateInHexEscape |
+ ErrorCode::TrailingCharacters |
+ ErrorCode::UnexpectedEndOfHexEscape |
+ ErrorCode::RecursionLimitExceeded => Category::Syntax,
+ }
+ }
+
+ /// Returns true if this error was caused by a failure to read or write
+ /// bytes on an IO stream.
+ pub fn is_io(&self) -> bool {
+ self.classify() == Category::Io
+ }
+
+ /// Returns true if this error was caused by input that was not
+ /// syntactically valid JSON.
+ pub fn is_syntax(&self) -> bool {
+ self.classify() == Category::Syntax
+ }
+
+ /// Returns true if this error was caused by input data that was
+ /// semantically incorrect.
+ ///
+ /// For example, JSON containing a number is semantically incorrect when the
+ /// type being deserialized into holds a String.
+ pub fn is_data(&self) -> bool {
+ self.classify() == Category::Data
+ }
+
+ /// Returns true if this error was caused by prematurely reaching the end of
+ /// the input data.
+ ///
+ /// Callers that process streaming input may be interested in retrying the
+ /// deserialization once more data is available.
+ pub fn is_eof(&self) -> bool {
+ self.classify() == Category::Eof
+ }
+}
+
+/// Categorizes the cause of a `serde_json::Error`.
+#[derive(Copy, Clone, PartialEq, Eq, Debug)]
+pub enum Category {
+ /// The error was caused by a failure to read or write bytes on an IO
+ /// stream.
+ Io,
+
+ /// The error was caused by input that was not syntactically valid JSON.
+ Syntax,
+
+ /// The error was caused by input data that was semantically incorrect.
+ ///
+ /// For example, JSON containing a number is semantically incorrect when the
+ /// type being deserialized into holds a String.
+ Data,
+
+ /// The error was caused by prematurely reaching the end of the input data.
+ ///
+ /// Callers that process streaming input may be interested in retrying the
+ /// deserialization once more data is available.
+ Eof,
+}
+
+#[derive(Debug)]
+struct ErrorImpl {
+ code: ErrorCode,
+ line: usize,
+ column: usize,
}
// Not public API. Should be pub(crate).
#[doc(hidden)]
-#[derive(Clone, PartialEq, Debug)]
+#[derive(Debug)]
pub enum ErrorCode {
/// Catchall for syntax error messages
Message(String),
+ /// Some IO error occurred while serializing or deserializing.
+ Io(io::Error),
+
/// EOF while parsing a list.
- EOFWhileParsingList,
+ EofWhileParsingList,
/// EOF while parsing an object.
- EOFWhileParsingObject,
+ EofWhileParsingObject,
/// EOF while parsing a string.
- EOFWhileParsingString,
+ EofWhileParsingString,
/// EOF while parsing a JSON value.
- EOFWhileParsingValue,
+ EofWhileParsingValue,
/// Expected this character to be a `':'`.
ExpectedColon,
@@ -93,9 +204,9 @@ pub enum ErrorCode {
impl Error {
// Not public API. Should be pub(crate).
#[doc(hidden)]
- pub fn syntax(code: ErrorCode, line: usize, col: usize) -> Self {
+ pub fn syntax(code: ErrorCode, line: usize, column: usize) -> Self {
Error {
- err: Box::new(ErrorImpl::Syntax(code, line, col)),
+ err: Box::new(ErrorImpl { code: code, line: line, column: column }),
}
}
@@ -104,8 +215,8 @@ impl Error {
pub fn fix_position<F>(self, f: F) -> Self
where F: FnOnce(ErrorCode) -> Error
{
- if let ErrorImpl::Syntax(code, 0, 0) = *self.err {
- f(code)
+ if self.err.line == 0 {
+ f(self.err.code)
} else {
self
}
@@ -115,17 +226,18 @@ impl Error {
impl Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
- ErrorCode::Message(ref msg) => write!(f, "{}", msg),
- ErrorCode::EOFWhileParsingList => {
+ ErrorCode::Message(ref msg) => f.write_str(msg),
+ ErrorCode::Io(ref err) => Display::fmt(err, f),
+ ErrorCode::EofWhileParsingList => {
f.write_str("EOF while parsing a list")
}
- ErrorCode::EOFWhileParsingObject => {
+ ErrorCode::EofWhileParsingObject => {
f.write_str("EOF while parsing an object")
}
- ErrorCode::EOFWhileParsingString => {
+ ErrorCode::EofWhileParsingString => {
f.write_str("EOF while parsing a string")
}
- ErrorCode::EOFWhileParsingValue => {
+ ErrorCode::EofWhileParsingValue => {
f.write_str("EOF while parsing a value")
}
ErrorCode::ExpectedColon => {
@@ -179,34 +291,35 @@ impl Display for ErrorCode {
impl error::Error for Error {
fn description(&self) -> &str {
- match *self.err {
- ErrorImpl::Syntax(..) => {
+ match self.err.code {
+ ErrorCode::Io(ref err) => error::Error::description(err),
+ _ => {
// If you want a better message, use Display::fmt or to_string().
"JSON error"
}
- ErrorImpl::Io(ref error) => error::Error::description(error),
}
}
fn cause(&self) -> Option<&error::Error> {
- match *self.err {
- ErrorImpl::Io(ref error) => Some(error),
+ match self.err.code {
+ ErrorCode::Io(ref err) => Some(err),
_ => None,
}
}
}
impl Display for Error {
- fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- match *self.err {
- ErrorImpl::Syntax(ref code, line, col) => {
- if line == 0 && col == 0 {
- write!(fmt, "{}", code)
- } else {
- write!(fmt, "{} at line {} column {}", code, line, col)
- }
- }
- ErrorImpl::Io(ref error) => fmt::Display::fmt(error, fmt),
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ Display::fmt(&*self.err, f)
+ }
+}
+
+impl Display for ErrorImpl {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ if self.line == 0 {
+ Display::fmt(&self.code, f)
+ } else {
+ write!(f, "{} at line {} column {}", self.code, self.line, self.column)
}
}
}
@@ -214,21 +327,8 @@ impl Display for Error {
// Remove two layers of verbosity from the debug representation. Humans often
// end up seeing this representation because it is what unwrap() shows.
impl Debug for Error {
- fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
- match *self.err {
- ErrorImpl::Syntax(ref code, ref line, ref col) => {
- formatter.debug_tuple("Syntax")
- .field(code)
- .field(line)
- .field(col)
- .finish()
- }
- ErrorImpl::Io(ref io) => {
- formatter.debug_tuple("Io")
- .field(io)
- .finish()
- }
- }
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ Debug::fmt(&*self.err, f)
}
}
@@ -243,7 +343,7 @@ impl From<ErrorImpl> for Error {
impl From<io::Error> for Error {
fn from(error: io::Error) -> Error {
Error {
- err: Box::new(ErrorImpl::Io(error)),
+ err: Box::new(ErrorImpl { code: ErrorCode::Io(error), line: 0, column: 0 }),
}
}
}
@@ -251,7 +351,7 @@ impl From<io::Error> for Error {
impl From<de::value::Error> for Error {
fn from(error: de::value::Error) -> Error {
Error {
- err: Box::new(ErrorImpl::Syntax(ErrorCode::Message(error.to_string()), 0, 0)),
+ err: Box::new(ErrorImpl { code: ErrorCode::Message(error.to_string()), line: 0, column: 0 }),
}
}
}
@@ -259,7 +359,7 @@ impl From<de::value::Error> for Error {
impl de::Error for Error {
fn custom<T: Display>(msg: T) -> Error {
Error {
- err: Box::new(ErrorImpl::Syntax(ErrorCode::Message(msg.to_string()), 0, 0)),
+ err: Box::new(ErrorImpl { code: ErrorCode::Message(msg.to_string()), line: 0, column: 0 }),
}
}
}
@@ -267,7 +367,7 @@ impl de::Error for Error {
impl ser::Error for Error {
fn custom<T: Display>(msg: T) -> Error {
Error {
- err: Box::new(ErrorImpl::Syntax(ErrorCode::Message(msg.to_string()), 0, 0)),
+ err: Box::new(ErrorImpl { code: ErrorCode::Message(msg.to_string()), line: 0, column: 0 }),
}
}
}
diff --git a/json/src/read.rs b/json/src/read.rs
index b712925c8..a352b203a 100644
--- a/json/src/read.rs
+++ b/json/src/read.rs
@@ -135,12 +135,7 @@ impl<Iter> IteratorRead<Iter>
F: FnOnce(&'s Self, &'s [u8]) -> Result<T>,
{
loop {
- let ch = match try!(self.next()) {
- Some(ch) => ch,
- None => {
- return error(self, ErrorCode::EOFWhileParsingString);
- }
- };
+ let ch = try!(next_or_eof(self));
if !ESCAPE[ch as usize] {
scratch.push(ch);
continue;
@@ -342,7 +337,7 @@ impl<'a> SliceRead<'a> {
self.index += 1;
}
if self.index == self.slice.len() {
- return error(self, ErrorCode::EOFWhileParsingString);
+ return error(self, ErrorCode::EofWhileParsingString);
}
match self.slice[self.index] {
b'"' => {
@@ -519,6 +514,13 @@ static ESCAPE: [bool; 256] = [
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // F
];
+fn next_or_eof<R: Read>(read: &mut R) -> Result<u8> {
+ match try!(read.next()) {
+ Some(b) => Ok(b),
+ None => error(read, ErrorCode::EofWhileParsingString),
+ }
+}
+
fn error<R: Read, T>(read: &R, reason: ErrorCode) -> Result<T> {
let pos = read.position();
Err(Error::syntax(reason, pos.line, pos.column))
@@ -532,12 +534,7 @@ fn as_str<'s, R: Read>(read: &R, slice: &'s [u8]) -> Result<&'s str> {
/// Parses a JSON escape sequence and appends it into the scratch space. Assumes
/// the previous byte read was a backslash.
fn parse_escape<R: Read>(read: &mut R, scratch: &mut Vec<u8>) -> Result<()> {
- let ch = match try!(read.next()) {
- Some(ch) => ch,
- None => {
- return error(read, ErrorCode::EOFWhileParsingString);
- }
- };
+ let ch = try!(next_or_eof(read));
match ch {
b'"' => scratch.push(b'"'),
@@ -558,12 +555,11 @@ fn parse_escape<R: Read>(read: &mut R, scratch: &mut Vec<u8>) -> Result<()> {
// Non-BMP characters are encoded as a sequence of
// two hex escapes, representing UTF-16 surrogates.
n1 @ 0xD800...0xDBFF => {
- match (try!(read.next()),
- try!(read.next())) {
- (Some(b'\\'), Some(b'u')) => (),
- _ => {
- return error(read, ErrorCode::UnexpectedEndOfHexEscape);
- }
+ if try!(next_or_eof(read)) != b'\\' {
+ return error(read, ErrorCode::UnexpectedEndOfHexEscape);
+ }
+ if try!(next_or_eof(read)) != b'u' {
+ return error(read, ErrorCode::UnexpectedEndOfHexEscape);
}
let n2 = try!(decode_hex_escape(read));
@@ -609,10 +605,9 @@ fn parse_escape<R: Read>(read: &mut R, scratch: &mut Vec<u8>) -> Result<()> {
}
fn decode_hex_escape<R: Read>(read: &mut R) -> Result<u16> {
- let mut i = 0;
let mut n = 0;
- while i < 4 && try!(read.peek()).is_some() {
- n = match try!(read.next()).unwrap_or(b'\x00') {
+ for _ in 0..4 {
+ n = match try!(next_or_eof(read)) {
c @ b'0'...b'9' => n * 16_u16 + ((c as u16) - (b'0' as u16)),
b'a' | b'A' => n * 16_u16 + 10_u16,
b'b' | b'B' => n * 16_u16 + 11_u16,
@@ -624,14 +619,6 @@ fn decode_hex_escape<R: Read>(read: &mut R) -> Result<u16> {
return error(read, ErrorCode::InvalidEscape);
}
};
-
- i += 1;
}
-
- // Error out if we didn't parse 4 digits.
- if i != 4 {
- return error(read, ErrorCode::InvalidEscape);
- }
-
Ok(n)
}
|
diff --git a/json_tests/tests/test.rs b/json_tests/tests/test.rs
index 83e09f95e..b90ce6765 100644
--- a/json_tests/tests/test.rs
+++ b/json_tests/tests/test.rs
@@ -1907,3 +1907,28 @@ fn test_partialeq_string() {
assert_eq!(v, String::from("42"));
assert_eq!(String::from("42"), v);
}
+
+#[test]
+fn test_category() {
+ assert!(from_str::<String>("123").unwrap_err().is_data());
+
+ assert!(from_str::<String>("]").unwrap_err().is_syntax());
+
+ assert!(from_str::<String>("").unwrap_err().is_eof());
+ assert!(from_str::<String>("\"").unwrap_err().is_eof());
+ assert!(from_str::<String>("\"\\").unwrap_err().is_eof());
+ assert!(from_str::<String>("\"\\u").unwrap_err().is_eof());
+ assert!(from_str::<String>("\"\\u0").unwrap_err().is_eof());
+ assert!(from_str::<String>("\"\\u00").unwrap_err().is_eof());
+ assert!(from_str::<String>("\"\\u000").unwrap_err().is_eof());
+
+ assert!(from_str::<Vec<usize>>("[").unwrap_err().is_eof());
+ assert!(from_str::<Vec<usize>>("[0").unwrap_err().is_eof());
+ assert!(from_str::<Vec<usize>>("[0,").unwrap_err().is_eof());
+
+ assert!(from_str::<BTreeMap<String, usize>>("{").unwrap_err().is_eof());
+ assert!(from_str::<BTreeMap<String, usize>>("{\"k\"").unwrap_err().is_eof());
+ assert!(from_str::<BTreeMap<String, usize>>("{\"k\":").unwrap_err().is_eof());
+ assert!(from_str::<BTreeMap<String, usize>>("{\"k\":0").unwrap_err().is_eof());
+ assert!(from_str::<BTreeMap<String, usize>>("{\"k\":0,").unwrap_err().is_eof());
+}
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
null |
serde-rs__json-276
| 276
|
[
"275"
] |
2017-03-09T01:18:07Z
|
5256c7ba5fb16d9235dd8d5b01c78e2aea19a404
|
Better errors when json! fails to parse colon or comma
```rust
json!({:true})
```
```
error: expected expression, found `:`
--> src/main.rs:19:5
|
5 | json!({:true})
| ^^^^^^^^^^^^^^
```
```rust
json!({"a",})
```
```
error: expected expression, found `,`
--> src/main.rs:20:5
|
5 | json!({"a",})
| ^^^^^^^^^^^^^
```
I came up with a trick in [`iota`](https://github.com/dtolnay/iota) that would let us emit better errors in these cases. Duplicate the input tokens: `($($tt)*) ($($tt)*)` and then match on the first set and trigger errors on the second set. It looks something like:
```rust
((; $($tt:tt)*) ($semi:tt $($y:tt)*)) => {
__fail_to_match($semi)
}
```
|
diff --git a/json/src/macros.rs b/json/src/macros.rs
index e68df8fcd..4145737de 100644
--- a/json/src/macros.rs
+++ b/json/src/macros.rs
@@ -134,16 +134,19 @@ macro_rules! json_internal {
// TT muncher for parsing the inside of an object {...}. Each entry is
// inserted into the given map variable.
//
- // Must be invoked as: json_internal!(@object $map () $($tt)*)
+ // Must be invoked as: json_internal!(@object $map () ($($tt)*) ($($tt)*))
+ //
+ // We require two copies of the input tokens so that we can match on one
+ // copy and trigger errors on the other copy.
//////////////////////////////////////////////////////////////////////////
// Done.
- (@object $object:ident ()) => {};
+ (@object $object:ident () () ()) => {};
// Insert the current entry followed by trailing comma.
(@object $object:ident [$($key:tt)+] ($value:expr) , $($rest:tt)*) => {
$object.insert(($($key)+).into(), $value);
- json_internal!(@object $object () $($rest)*);
+ json_internal!(@object $object () ($($rest)*) ($($rest)*));
};
// Insert the last entry without trailing comma.
@@ -152,67 +155,74 @@ macro_rules! json_internal {
};
// Next value is `null`.
- (@object $object:ident ($($key:tt)+) : null $($rest:tt)*) => {
+ (@object $object:ident ($($key:tt)+) (: null $($rest:tt)*) $copy:tt) => {
json_internal!(@object $object [$($key)+] (json_internal!(null)) $($rest)*);
};
// Next value is `true`.
- (@object $object:ident ($($key:tt)+) : true $($rest:tt)*) => {
+ (@object $object:ident ($($key:tt)+) (: true $($rest:tt)*) $copy:tt) => {
json_internal!(@object $object [$($key)+] (json_internal!(true)) $($rest)*);
};
// Next value is `false`.
- (@object $object:ident ($($key:tt)+) : false $($rest:tt)*) => {
+ (@object $object:ident ($($key:tt)+) (: false $($rest:tt)*) $copy:tt) => {
json_internal!(@object $object [$($key)+] (json_internal!(false)) $($rest)*);
};
// Next value is an array.
- (@object $object:ident ($($key:tt)+) : [$($array:tt)*] $($rest:tt)*) => {
+ (@object $object:ident ($($key:tt)+) (: [$($array:tt)*] $($rest:tt)*) $copy:tt) => {
json_internal!(@object $object [$($key)+] (json_internal!([$($array)*])) $($rest)*);
};
// Next value is a map.
- (@object $object:ident ($($key:tt)+) : {$($map:tt)*} $($rest:tt)*) => {
+ (@object $object:ident ($($key:tt)+) (: {$($map:tt)*} $($rest:tt)*) $copy:tt) => {
json_internal!(@object $object [$($key)+] (json_internal!({$($map)*})) $($rest)*);
};
// Next value is an expression followed by comma.
- (@object $object:ident ($($key:tt)+) : $value:expr , $($rest:tt)*) => {
+ (@object $object:ident ($($key:tt)+) (: $value:expr , $($rest:tt)*) $copy:tt) => {
json_internal!(@object $object [$($key)+] (json_internal!($value)) , $($rest)*);
};
// Last value is an expression with no trailing comma.
- (@object $object:ident ($($key:tt)+) : $value:expr) => {
+ (@object $object:ident ($($key:tt)+) (: $value:expr) $copy:tt) => {
json_internal!(@object $object [$($key)+] (json_internal!($value)));
};
- // Missing value for last entry. Trigger a reasonable error message
- // referring to the unexpected end of macro invocation.
- (@object $object:ident ($($key:tt)+) :) => {
+ // Missing value for last entry. Trigger a reasonable error message.
+ (@object $object:ident ($($key:tt)+) (:) $copy:tt) => {
+ // "unexpected end of macro invocation"
+ json_internal!();
+ };
+
+ // Missing colon and value for last entry. Trigger a reasonable error
+ // message.
+ (@object $object:ident ($($key:tt)+) () $copy:tt) => {
+ // "unexpected end of macro invocation"
json_internal!();
};
- // Misplaced colon. Trigger a reasonable error message by failing to match
- // the colon in the recursive call.
- (@object $object:ident () : $($rest:tt)*) => {
- json_internal!(:);
+ // Misplaced colon. Trigger a reasonable error message.
+ (@object $object:ident () (: $($rest:tt)*) ($colon:tt $($copy:tt)*)) => {
+ // Takes no arguments so "no rules expected the token `:`".
+ unimplemented!($colon);
};
- // Found a comma inside a key. Trigger a reasonable error message by failing
- // to match the comma in the recursive call.
- (@object $object:ident ($($key:tt)*) , $($rest:tt)*) => {
- json_internal!(,);
+ // Found a comma inside a key. Trigger a reasonable error message.
+ (@object $object:ident ($($key:tt)*) (, $($rest:tt)*) ($comma:tt $($copy:tt)*)) => {
+ // Takes no arguments so "no rules expected the token `,`".
+ unimplemented!($comma);
};
// Key is fully parenthesized. This avoids clippy double_parens false
// positives because the parenthesization may be necessary here.
- (@object $object:ident () ($key:expr) : $($rest:tt)*) => {
- json_internal!(@object $object ($key) : $($rest)*);
+ (@object $object:ident () (($key:expr) : $($rest:tt)*) $copy:tt) => {
+ json_internal!(@object $object ($key) (: $($rest)*) (: $($rest)*));
};
// Munch a token into the current key.
- (@object $object:ident ($($key:tt)*) $tt:tt $($rest:tt)*) => {
- json_internal!(@object $object ($($key)* $tt) $($rest)*);
+ (@object $object:ident ($($key:tt)*) ($tt:tt $($rest:tt)*) $copy:tt) => {
+ json_internal!(@object $object ($($key)* $tt) ($($rest)*) ($($rest)*));
};
//////////////////////////////////////////////////////////////////////////
@@ -248,7 +258,7 @@ macro_rules! json_internal {
({ $($tt:tt)+ }) => {
$crate::Value::Object({
let mut object = $crate::Map::new();
- json_internal!(@object object () $($tt)+);
+ json_internal!(@object object () ($($tt)+) ($($tt)+));
object
})
};
diff --git a/travis.sh b/travis.sh
index b697ffa11..feb0dbbba 100755
--- a/travis.sh
+++ b/travis.sh
@@ -35,8 +35,10 @@ else
channel build
channel build --features preserve_order
channel test
+ cd "$DIR/json_tests/deps"
+ channel build
cd "$DIR/json_tests"
- channel test
+ channel test --features unstable-testing
for CHANNEL in stable 1.12.0 1.13.0 beta; do
cd "$DIR/json"
|
diff --git a/json_tests/Cargo.toml b/json_tests/Cargo.toml
index bdfc2e784..70c6dad04 100644
--- a/json_tests/Cargo.toml
+++ b/json_tests/Cargo.toml
@@ -6,12 +6,12 @@ publish = false
[features]
trace-macros = []
+unstable-testing = ["compiletest_rs"]
-[dependencies]
+[dev-dependencies]
serde = "0.9.11"
serde_json = { path = "../json" }
serde_derive = "0.9"
-[[test]]
-name = "test"
-path = "tests/test.rs"
+[dependencies]
+compiletest_rs = { version = "0.2", optional = true }
diff --git a/json_tests/deps/Cargo.toml b/json_tests/deps/Cargo.toml
new file mode 100644
index 000000000..6bf64b594
--- /dev/null
+++ b/json_tests/deps/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "serde_test_suite_deps"
+version = "0.0.0"
+authors = ["David Tolnay <dtolnay@gmail.com>"]
+publish = false
+
+[workspace]
+
+[dependencies]
+serde_json = { path = "../../json" }
diff --git a/json_tests/deps/src/lib.rs b/json_tests/deps/src/lib.rs
new file mode 100644
index 000000000..e69de29bb
diff --git a/json_tests/tests/compiletest.rs b/json_tests/tests/compiletest.rs
new file mode 100644
index 000000000..f6585b915
--- /dev/null
+++ b/json_tests/tests/compiletest.rs
@@ -0,0 +1,23 @@
+#![cfg(feature = "unstable-testing")]
+
+extern crate compiletest_rs as compiletest;
+
+use std::env;
+
+fn run_mode(mode: &'static str) {
+ let mut config = compiletest::default_config();
+
+ config.mode = mode.parse().expect("invalid mode");
+ config.target_rustcflags = Some("-L deps/target/debug/deps".to_owned());
+ if let Ok(name) = env::var("TESTNAME") {
+ config.filter = Some(name);
+ }
+ config.src_base = format!("tests/{}", mode).into();
+
+ compiletest::run_tests(&config);
+}
+
+#[test]
+fn ui() {
+ run_mode("ui");
+}
diff --git a/json_tests/tests/ui/missing_colon.rs b/json_tests/tests/ui/missing_colon.rs
new file mode 100644
index 000000000..98d4f2ce0
--- /dev/null
+++ b/json_tests/tests/ui/missing_colon.rs
@@ -0,0 +1,6 @@
+#[macro_use]
+extern crate serde_json;
+
+fn main() {
+ json!({ "a" });
+}
diff --git a/json_tests/tests/ui/missing_colon.stderr b/json_tests/tests/ui/missing_colon.stderr
new file mode 100644
index 000000000..ab3426f57
--- /dev/null
+++ b/json_tests/tests/ui/missing_colon.stderr
@@ -0,0 +1,8 @@
+error: unexpected end of macro invocation
+ --> $DIR/missing_colon.rs:5:5
+ |
+5 | json!({ "a" });
+ | ^^^^^^^^^^^^^^^
+ |
+ = note: this error originates in a macro outside of the current crate
+
diff --git a/json_tests/tests/ui/missing_value.rs b/json_tests/tests/ui/missing_value.rs
new file mode 100644
index 000000000..d72a49d93
--- /dev/null
+++ b/json_tests/tests/ui/missing_value.rs
@@ -0,0 +1,6 @@
+#[macro_use]
+extern crate serde_json;
+
+fn main() {
+ json!({ "a" : });
+}
diff --git a/json_tests/tests/ui/missing_value.stderr b/json_tests/tests/ui/missing_value.stderr
new file mode 100644
index 000000000..87de800da
--- /dev/null
+++ b/json_tests/tests/ui/missing_value.stderr
@@ -0,0 +1,8 @@
+error: unexpected end of macro invocation
+ --> $DIR/missing_value.rs:5:5
+ |
+5 | json!({ "a" : });
+ | ^^^^^^^^^^^^^^^^^
+ |
+ = note: this error originates in a macro outside of the current crate
+
diff --git a/json_tests/tests/ui/not_found.rs b/json_tests/tests/ui/not_found.rs
new file mode 100644
index 000000000..08b802fe5
--- /dev/null
+++ b/json_tests/tests/ui/not_found.rs
@@ -0,0 +1,6 @@
+#[macro_use]
+extern crate serde_json;
+
+fn main() {
+ json!({ "a" : x });
+}
diff --git a/json_tests/tests/ui/not_found.stderr b/json_tests/tests/ui/not_found.stderr
new file mode 100644
index 000000000..17811191e
--- /dev/null
+++ b/json_tests/tests/ui/not_found.stderr
@@ -0,0 +1,8 @@
+error[E0425]: cannot find value `x` in this scope
+ --> $DIR/not_found.rs:5:19
+ |
+5 | json!({ "a" : x });
+ | ^ not found in this scope
+
+error: aborting due to previous error
+
diff --git a/json_tests/tests/ui/parse_expr.rs b/json_tests/tests/ui/parse_expr.rs
new file mode 100644
index 000000000..bcc58ae22
--- /dev/null
+++ b/json_tests/tests/ui/parse_expr.rs
@@ -0,0 +1,6 @@
+#[macro_use]
+extern crate serde_json;
+
+fn main() {
+ json!({ "a" : ~ });
+}
diff --git a/json_tests/tests/ui/parse_expr.stderr b/json_tests/tests/ui/parse_expr.stderr
new file mode 100644
index 000000000..9cc92e4f7
--- /dev/null
+++ b/json_tests/tests/ui/parse_expr.stderr
@@ -0,0 +1,6 @@
+error: expected expression, found `~`
+ --> $DIR/parse_expr.rs:5:19
+ |
+5 | json!({ "a" : ~ });
+ | ^
+
diff --git a/json_tests/tests/ui/parse_key.rs b/json_tests/tests/ui/parse_key.rs
new file mode 100644
index 000000000..e7f4e27f6
--- /dev/null
+++ b/json_tests/tests/ui/parse_key.rs
@@ -0,0 +1,6 @@
+#[macro_use]
+extern crate serde_json;
+
+fn main() {
+ json!({ "".s : true });
+}
diff --git a/json_tests/tests/ui/parse_key.stderr b/json_tests/tests/ui/parse_key.stderr
new file mode 100644
index 000000000..403dc0ccb
--- /dev/null
+++ b/json_tests/tests/ui/parse_key.stderr
@@ -0,0 +1,8 @@
+error: no field `s` on type `&'static str`
+ --> $DIR/parse_key.rs:5:16
+ |
+5 | json!({ "".s : true });
+ | ^
+
+error: aborting due to previous error
+
diff --git a/json_tests/tests/ui/unexpected_colon.rs b/json_tests/tests/ui/unexpected_colon.rs
new file mode 100644
index 000000000..e9a307e5d
--- /dev/null
+++ b/json_tests/tests/ui/unexpected_colon.rs
@@ -0,0 +1,6 @@
+#[macro_use]
+extern crate serde_json;
+
+fn main() {
+ json!({ : true });
+}
diff --git a/json_tests/tests/ui/unexpected_colon.stderr b/json_tests/tests/ui/unexpected_colon.stderr
new file mode 100644
index 000000000..1c7318947
--- /dev/null
+++ b/json_tests/tests/ui/unexpected_colon.stderr
@@ -0,0 +1,6 @@
+error: no rules expected the token `:`
+ --> $DIR/unexpected_colon.rs:5:13
+ |
+5 | json!({ : true });
+ | ^
+
diff --git a/json_tests/tests/ui/unexpected_comma.rs b/json_tests/tests/ui/unexpected_comma.rs
new file mode 100644
index 000000000..66d106d93
--- /dev/null
+++ b/json_tests/tests/ui/unexpected_comma.rs
@@ -0,0 +1,6 @@
+#[macro_use]
+extern crate serde_json;
+
+fn main() {
+ json!({ "a" , "b": true });
+}
diff --git a/json_tests/tests/ui/unexpected_comma.stderr b/json_tests/tests/ui/unexpected_comma.stderr
new file mode 100644
index 000000000..6af758d46
--- /dev/null
+++ b/json_tests/tests/ui/unexpected_comma.stderr
@@ -0,0 +1,6 @@
+error: no rules expected the token `,`
+ --> $DIR/unexpected_comma.rs:5:17
+ |
+5 | json!({ "a" , "b": true });
+ | ^
+
diff --git a/json_tests/tests/ui/update-references.sh b/json_tests/tests/ui/update-references.sh
new file mode 100755
index 000000000..aa99d35f7
--- /dev/null
+++ b/json_tests/tests/ui/update-references.sh
@@ -0,0 +1,50 @@
+#!/bin/bash
+#
+# Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+# file at the top-level directory of this distribution and at
+# http://rust-lang.org/COPYRIGHT.
+#
+# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+# option. This file may not be copied, modified, or distributed
+# except according to those terms.
+
+# A script to update the references for particular tests. The idea is
+# that you do a run, which will generate files in the build directory
+# containing the (normalized) actual output of the compiler. This
+# script will then copy that output and replace the "expected output"
+# files. You can then commit the changes.
+#
+# If you find yourself manually editing a foo.stderr file, you're
+# doing it wrong.
+
+if [[ "$1" == "--help" || "$1" == "-h" || "$1" == "" || "$2" == "" ]]; then
+ echo "usage: $0 <build-directory> <relative-path-to-rs-files>"
+ echo ""
+ echo "For example:"
+ echo " $0 ../../../build/x86_64-apple-darwin/test/ui *.rs */*.rs"
+fi
+
+MYDIR=$(dirname $0)
+
+BUILD_DIR="$1"
+shift
+
+while [[ "$1" != "" ]]; do
+ STDERR_NAME="${1/%.rs/.stderr}"
+ STDOUT_NAME="${1/%.rs/.stdout}"
+ shift
+ if [ -f $BUILD_DIR/$STDOUT_NAME ] && \
+ ! (diff $BUILD_DIR/$STDOUT_NAME $MYDIR/$STDOUT_NAME >& /dev/null); then
+ echo updating $MYDIR/$STDOUT_NAME
+ cp $BUILD_DIR/$STDOUT_NAME $MYDIR/$STDOUT_NAME
+ fi
+ if [ -f $BUILD_DIR/$STDERR_NAME ] && \
+ ! (diff $BUILD_DIR/$STDERR_NAME $MYDIR/$STDERR_NAME >& /dev/null); then
+ echo updating $MYDIR/$STDERR_NAME
+ cp $BUILD_DIR/$STDERR_NAME $MYDIR/$STDERR_NAME
+ fi
+done
+
+
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
|
null |
serde-rs__json-261
| 261
|
[
"195"
] |
2017-02-21T06:11:59Z
|
a6effeece20e0fcca57540e295f21ee6294594ea
|
Implement Deserializer for &Value
We have an implementation of Deserializer for Value which consumes the Value - for example Value::String turns into visit_string. It would make sense to also implement Deserializer for &Value, so that for example &Value::String turns into visit_str.
|
diff --git a/json/src/number.rs b/json/src/number.rs
index 97736432e..ff401d97e 100644
--- a/json/src/number.rs
+++ b/json/src/number.rs
@@ -180,6 +180,27 @@ impl Deserializer for Number {
}
}
+impl<'a> Deserializer for &'a Number {
+ type Error = Error;
+
+ #[inline]
+ fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
+ where V: Visitor
+ {
+ match self.n {
+ N::PosInt(i) => visitor.visit_u64(i),
+ N::NegInt(i) => visitor.visit_i64(i),
+ N::Float(f) => visitor.visit_f64(f),
+ }
+ }
+
+ forward_to_deserialize! {
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
+ seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
+ tuple_struct struct struct_field tuple enum ignored_any
+ }
+}
+
macro_rules! from_signed {
($($signed_ty:ident)*) => {
$(
diff --git a/json/src/value.rs b/json/src/value.rs
index e6caec8ea..7b9ccae1c 100644
--- a/json/src/value.rs
+++ b/json/src/value.rs
@@ -85,6 +85,7 @@ use std::fmt;
use std::i64;
use std::io;
use std::ops;
+use std::slice;
use std::str;
use std::vec;
use std::borrow::Cow;
@@ -1829,7 +1830,7 @@ impl de::MapVisitor for MapDeserializer {
match self.iter.next() {
Some((key, value)) => {
self.value = Some(value);
- seed.deserialize(Value::String(key)).map(Some)
+ seed.deserialize(key.into_deserializer()).map(Some)
}
None => Ok(None),
}
@@ -1866,6 +1867,298 @@ impl de::Deserializer for MapDeserializer {
}
}
+impl<'a> de::Deserializer for &'a Value {
+ type Error = Error;
+
+ fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
+ where V: de::Visitor,
+ {
+ match *self {
+ Value::Null => visitor.visit_unit(),
+ Value::Bool(v) => visitor.visit_bool(v),
+ Value::Number(ref n) => n.deserialize(visitor),
+ Value::String(ref v) => visitor.visit_str(v),
+ Value::Array(ref v) => {
+ let len = v.len();
+ let mut deserializer = SeqRefDeserializer::new(v);
+ let seq = try!(visitor.visit_seq(&mut deserializer));
+ let remaining = deserializer.iter.len();
+ if remaining == 0 {
+ Ok(seq)
+ } else {
+ Err(de::Error::invalid_length(len, &"fewer elements in array"))
+ }
+ }
+ Value::Object(ref v) => {
+ let len = v.len();
+ let mut deserializer = MapRefDeserializer::new(v);
+ let map = try!(visitor.visit_map(&mut deserializer));
+ let remaining = deserializer.iter.len();
+ if remaining == 0 {
+ Ok(map)
+ } else {
+ Err(de::Error::invalid_length(len, &"fewer elements in map"))
+ }
+ }
+ }
+ }
+
+ fn deserialize_option<V>(
+ self,
+ visitor: V
+ ) -> Result<V::Value, Error>
+ where V: de::Visitor,
+ {
+ match *self {
+ Value::Null => visitor.visit_none(),
+ _ => visitor.visit_some(self),
+ }
+ }
+
+ fn deserialize_enum<V>(
+ self,
+ _name: &str,
+ _variants: &'static [&'static str],
+ visitor: V
+ ) -> Result<V::Value, Error>
+ where V: de::Visitor,
+ {
+ let (variant, value) = match *self {
+ Value::Object(ref value) => {
+ let mut iter = value.into_iter();
+ let (variant, value) = match iter.next() {
+ Some(v) => v,
+ None => {
+ return Err(de::Error::invalid_value(Unexpected::Map, &"map with a single key"));
+ }
+ };
+ // enums are encoded in json as maps with a single key:value pair
+ if iter.next().is_some() {
+ return Err(de::Error::invalid_value(Unexpected::Map, &"map with a single key"));
+ }
+ (variant, Some(value))
+ }
+ Value::String(ref variant) => (variant, None),
+ ref other => {
+ return Err(de::Error::invalid_type(other.unexpected(), &"string or map"));
+ }
+ };
+
+ visitor.visit_enum(EnumRefDeserializer {
+ variant: variant,
+ value: value,
+ })
+ }
+
+ #[inline]
+ fn deserialize_newtype_struct<V>(
+ self,
+ _name: &'static str,
+ visitor: V
+ ) -> Result<V::Value, Self::Error>
+ where V: de::Visitor,
+ {
+ visitor.visit_newtype_struct(self)
+ }
+
+ forward_to_deserialize! {
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
+ seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct
+ struct_field tuple ignored_any
+ }
+}
+
+struct EnumRefDeserializer<'a> {
+ variant: &'a str,
+ value: Option<&'a Value>,
+}
+
+impl<'a> de::EnumVisitor for EnumRefDeserializer<'a> {
+ type Error = Error;
+ type Variant = VariantRefDeserializer<'a>;
+
+ fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Error>
+ where V: de::DeserializeSeed,
+ {
+ let variant = self.variant.into_deserializer();
+ let visitor = VariantRefDeserializer { value: self.value };
+ seed.deserialize(variant).map(|v| (v, visitor))
+ }
+}
+
+struct VariantRefDeserializer<'a> {
+ value: Option<&'a Value>,
+}
+
+impl<'a> de::VariantVisitor for VariantRefDeserializer<'a> {
+ type Error = Error;
+
+ fn visit_unit(self) -> Result<(), Error> {
+ match self.value {
+ Some(value) => de::Deserialize::deserialize(value),
+ None => Ok(()),
+ }
+ }
+
+ fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, Error>
+ where T: de::DeserializeSeed,
+ {
+ match self.value {
+ Some(value) => seed.deserialize(value),
+ None => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant")),
+ }
+ }
+
+ fn visit_tuple<V>(
+ self,
+ _len: usize,
+ visitor: V
+ ) -> Result<V::Value, Error>
+ where V: de::Visitor,
+ {
+ match self.value {
+ Some(&Value::Array(ref v)) => {
+ de::Deserializer::deserialize(SeqRefDeserializer::new(v), visitor)
+ }
+ Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"tuple variant")),
+ None => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant"))
+ }
+ }
+
+ fn visit_struct<V>(
+ self,
+ _fields: &'static [&'static str],
+ visitor: V
+ ) -> Result<V::Value, Error>
+ where V: de::Visitor,
+ {
+ match self.value {
+ Some(&Value::Object(ref v)) => {
+ de::Deserializer::deserialize(MapRefDeserializer::new(v), visitor)
+ }
+ Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"struct variant")),
+ _ => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant"))
+ }
+ }
+}
+
+struct SeqRefDeserializer<'a> {
+ iter: slice::Iter<'a, Value>,
+}
+
+impl<'a> SeqRefDeserializer<'a> {
+ fn new(slice: &'a [Value]) -> Self {
+ SeqRefDeserializer {
+ iter: slice.iter(),
+ }
+ }
+}
+
+impl<'a> de::Deserializer for SeqRefDeserializer<'a> {
+ type Error = Error;
+
+ #[inline]
+ fn deserialize<V>(mut self, visitor: V) -> Result<V::Value, Error>
+ where V: de::Visitor,
+ {
+ let len = self.iter.len();
+ if len == 0 {
+ visitor.visit_unit()
+ } else {
+ let ret = try!(visitor.visit_seq(&mut self));
+ let remaining = self.iter.len();
+ if remaining == 0 {
+ Ok(ret)
+ } else {
+ Err(de::Error::invalid_length(len, &"fewer elements in array"))
+ }
+ }
+ }
+
+ forward_to_deserialize! {
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
+ seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
+ tuple_struct struct struct_field tuple enum ignored_any
+ }
+}
+
+impl<'a> de::SeqVisitor for SeqRefDeserializer<'a> {
+ type Error = Error;
+
+ fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
+ where T: de::DeserializeSeed,
+ {
+ match self.iter.next() {
+ Some(value) => seed.deserialize(value).map(Some),
+ None => Ok(None),
+ }
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+}
+
+struct MapRefDeserializer<'a> {
+ iter: <&'a Map<String, Value> as IntoIterator>::IntoIter,
+ value: Option<&'a Value>,
+}
+
+impl<'a> MapRefDeserializer<'a> {
+ fn new(map: &'a Map<String, Value>) -> Self {
+ MapRefDeserializer {
+ iter: map.into_iter(),
+ value: None,
+ }
+ }
+}
+
+impl<'a> de::MapVisitor for MapRefDeserializer<'a> {
+ type Error = Error;
+
+ fn visit_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
+ where T: de::DeserializeSeed,
+ {
+ match self.iter.next() {
+ Some((key, value)) => {
+ self.value = Some(value);
+ seed.deserialize((&**key).into_deserializer()).map(Some)
+ }
+ None => Ok(None),
+ }
+ }
+
+ fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Error>
+ where T: de::DeserializeSeed,
+ {
+ match self.value.take() {
+ Some(value) => seed.deserialize(value),
+ None => Err(de::Error::custom("value is missing")),
+ }
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+}
+
+impl<'a> de::Deserializer for MapRefDeserializer<'a> {
+ type Error = Error;
+
+ #[inline]
+ fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
+ where V: de::Visitor,
+ {
+ visitor.visit_map(self)
+ }
+
+ forward_to_deserialize! {
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
+ seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
+ tuple_struct struct struct_field tuple enum ignored_any
+ }
+}
+
impl Value {
fn unexpected(&self) -> Unexpected {
match *self {
|
diff --git a/json_tests/tests/test.rs b/json_tests/tests/test.rs
index 90f07d1c3..cea94c693 100644
--- a/json_tests/tests/test.rs
+++ b/json_tests/tests/test.rs
@@ -711,6 +711,10 @@ fn test_parse_ok<T>(tests: Vec<(&str, T)>)
let json_value: Value = from_str(s).unwrap();
assert_eq!(json_value, to_value(&value).unwrap());
+ // Make sure we can deserialize from a `&Value`.
+ let v = T::deserialize(&json_value).unwrap();
+ assert_eq!(v, value);
+
// Make sure we can deserialize from a `Value`.
let v: T = from_value(json_value.clone()).unwrap();
assert_eq!(v, value);
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
|
null |
serde-rs__json-243
| 243
|
[
"242"
] |
2017-02-04T00:40:16Z
|
Or `json!` should use ToJson instead of to_value. Would that work for your use case?
I think there is value in consistency across various Serde crates and part of that is `to_*` functions that take Serialize as input.
I think that sounds reasonable. For my specific use case, having `json!` use `ToJson` instead of `to_value()` would certainly work.
|
15827b445232d24f636d67c3178e2871aadaf5e5
|
to_value should be bound on ToJson, not Serialize
All types that implement `Serialize` implement `ToJson`, but not all types that implement `ToJson` necessarily implement `Serialize`. So `to_value()` should be bound on `ToJson`, not `Serialize`, since that's all it really needs. That way I can implement `ToJson` on my custom types and then use them with the `json!()` macro.
For reference, I'm implementing `ToJson` on my type and not `Serialize` because my type can actually be serialized to both JSON and XML, but the serializations have very different representations, and I don't want to confuse anyone.
|
diff --git a/json/src/macros.rs b/json/src/macros.rs
index 8d5446b2f..71410dba0 100644
--- a/json/src/macros.rs
+++ b/json/src/macros.rs
@@ -254,6 +254,6 @@ macro_rules! json_internal {
// Any Serialize type: numbers, strings, struct literals, variables etc.
// Must be below every other rule.
($other:expr) => {
- $crate::to_value(&$other).unwrap()
+ $crate::value::ToJson::to_json(&$other).unwrap()
};
}
|
diff --git a/json_tests/tests/test.rs b/json_tests/tests/test.rs
index 5d7befcb3..90f07d1c3 100644
--- a/json_tests/tests/test.rs
+++ b/json_tests/tests/test.rs
@@ -28,6 +28,7 @@ use serde::bytes::{ByteBuf, Bytes};
use serde_json::{
Deserializer,
+ Error,
Value,
from_iter,
from_slice,
@@ -39,6 +40,7 @@ use serde_json::{
to_vec,
to_writer,
};
+use serde_json::value::ToJson;
macro_rules! treemap {
() => {
@@ -1795,6 +1797,18 @@ fn test_json_macro() {
});
}
+#[test]
+fn test_json_not_serializable() {
+ // Does not implement Serialize
+ struct S;
+ impl ToJson for S {
+ fn to_json(&self) -> Result<Value, Error> {
+ Ok(Value::String("S".to_owned()))
+ }
+ }
+ assert_eq!(Value::String("S".to_owned()), json!(S));
+}
+
#[test]
fn issue_220() {
#[derive(Debug, PartialEq, Eq, Deserialize)]
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
null |
serde-rs__json-231
| 231
|
[
"221"
] |
2017-01-29T16:05:17Z
|
We need to add a case for `Value::Number` inside `serde_json::value::SerializeMap::serialize_key`.
@killercup this is another quick one.
```rust
let mut map = BTreeMap::new();
map.insert(0, "x"); // integer key
serde_json::to_string(&map) // okay since https://github.com/serde-rs/json/pull/177
serde_json::to_value(&map) // fail
```
|
a9b695d36f85883b089f0f74c148e07c888f25d3
|
Integer keys in to_value
The `to_string` function supports integer map keys but `to_value` does not.
|
diff --git a/json/src/value.rs b/json/src/value.rs
index 074fb21be..aa420fdd0 100644
--- a/json/src/value.rs
+++ b/json/src/value.rs
@@ -1053,6 +1053,7 @@ impl ser::SerializeMap for SerializeMap {
{
match try!(to_value(&key)) {
Value::String(s) => self.next_key = Some(s),
+ Value::Number(s) => self.next_key = Some(s.to_string()),
_ => return Err(Error::syntax(ErrorCode::KeyMustBeAString, 0, 0)),
};
Ok(())
|
diff --git a/json_tests/tests/test.rs b/json_tests/tests/test.rs
index f06cfe86e..21bc91e02 100644
--- a/json_tests/tests/test.rs
+++ b/json_tests/tests/test.rs
@@ -665,6 +665,21 @@ fn test_write_newtype_struct() {
]);
}
+#[test]
+fn test_write_map_with_integer_keys_issue_221() {
+ let mut map = BTreeMap::new();
+ map.insert(0, "x"); // map with integer key
+
+ assert_eq!(
+ serde_json::to_value(&map).unwrap(),
+ json!({"0": "x"})
+ );
+
+ test_encode_ok(&[
+ (&map, r#"{"0":"x"}"#),
+ ]);
+}
+
fn test_parse_ok<T>(tests: Vec<(&str, T)>)
where T: Clone + Debug + PartialEq + ser::Serialize + de::Deserialize,
{
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
null |
serde-rs__json-230
| 230
|
[
"220",
"220"
] |
2017-01-29T15:42:55Z
|
The bug is that KeyOnlyVariantVisitor is parsing the string `"V"` inside visit_variant_seed and then parsing the number `0` inside visit_newtype_seed. The point of KeyOnlyVariantVisitor is that it is supposed to handle unit variants only so it should unconditionally return an error in all the VariantVisitor methods except visit_unit. Let's also rename KeyOnlyVariantVisitor to UnitVariantVisitor to clarify this.
@killercup would you be interested in tackling this?
Sure, let me have a look.
The bug is that KeyOnlyVariantVisitor is parsing the string `"V"` inside visit_variant_seed and then parsing the number `0` inside visit_newtype_seed. The point of KeyOnlyVariantVisitor is that it is supposed to handle unit variants only so it should unconditionally return an error in all the VariantVisitor methods except visit_unit. Let's also rename KeyOnlyVariantVisitor to UnitVariantVisitor to clarify this.
@killercup would you be interested in tackling this?
Sure, let me have a look.
|
a9b695d36f85883b089f0f74c148e07c888f25d3
|
Enums can parse invalid JSON
```rust
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
#[derive(Debug, Deserialize)]
enum E {
V(u8),
}
fn main() {
println!("{:?}", serde_json::from_str::<E>(r#" "V"0 "#));
}
```
```
Ok(V(0))
```
Enums can parse invalid JSON
```rust
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
#[derive(Debug, Deserialize)]
enum E {
V(u8),
}
fn main() {
println!("{:?}", serde_json::from_str::<E>(r#" "V"0 "#));
}
```
```
Ok(V(0))
```
|
diff --git a/json/src/de.rs b/json/src/de.rs
index 58a671987..ca66bcfd8 100644
--- a/json/src/de.rs
+++ b/json/src/de.rs
@@ -642,7 +642,7 @@ impl<'a, R: Read> de::Deserializer for &'a mut Deserializer<R> {
_ => Err(self.error(ErrorCode::ExpectedSomeValue)),
}
}
- b'"' => visitor.visit_enum(KeyOnlyVariantVisitor::new(self)),
+ b'"' => visitor.visit_enum(UnitVariantVisitor::new(self)),
_ => Err(self.peek_error(ErrorCode::ExpectedSomeValue)),
}
}
@@ -816,19 +816,19 @@ impl<'a, R: Read + 'a> de::VariantVisitor for VariantVisitor<'a, R> {
}
}
-struct KeyOnlyVariantVisitor<'a, R: Read + 'a> {
+struct UnitVariantVisitor<'a, R: Read + 'a> {
de: &'a mut Deserializer<R>,
}
-impl<'a, R: Read + 'a> KeyOnlyVariantVisitor<'a, R> {
+impl<'a, R: Read + 'a> UnitVariantVisitor<'a, R> {
fn new(de: &'a mut Deserializer<R>) -> Self {
- KeyOnlyVariantVisitor {
+ UnitVariantVisitor {
de: de,
}
}
}
-impl<'a, R: Read + 'a> de::EnumVisitor for KeyOnlyVariantVisitor<'a, R> {
+impl<'a, R: Read + 'a> de::EnumVisitor for UnitVariantVisitor<'a, R> {
type Error = Error;
type Variant = Self;
@@ -840,33 +840,33 @@ impl<'a, R: Read + 'a> de::EnumVisitor for KeyOnlyVariantVisitor<'a, R> {
}
}
-impl<'a, R: Read + 'a> de::VariantVisitor for KeyOnlyVariantVisitor<'a, R> {
+impl<'a, R: Read + 'a> de::VariantVisitor for UnitVariantVisitor<'a, R> {
type Error = Error;
fn visit_unit(self) -> Result<()> {
Ok(())
}
- fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value>
+ fn visit_newtype_seed<T>(self, _seed: T) -> Result<T::Value>
where T: de::DeserializeSeed,
{
- seed.deserialize(self.de)
+ Err(self.de.error(ErrorCode::EOFWhileParsingValue))
}
- fn visit_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value>
+ fn visit_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value>
where V: de::Visitor,
{
- de::Deserializer::deserialize(self.de, visitor)
+ Err(self.de.error(ErrorCode::EOFWhileParsingValue))
}
fn visit_struct<V>(
self,
_fields: &'static [&'static str],
- visitor: V
+ _visitor: V
) -> Result<V::Value>
where V: de::Visitor,
{
- de::Deserializer::deserialize(self.de, visitor)
+ Err(self.de.error(ErrorCode::EOFWhileParsingValue))
}
}
|
diff --git a/json_tests/tests/test.rs b/json_tests/tests/test.rs
index f06cfe86e..3c5e43eba 100644
--- a/json_tests/tests/test.rs
+++ b/json_tests/tests/test.rs
@@ -1133,6 +1133,8 @@ fn test_parse_enum_errors() {
"trailing characters at line 1 column 9"),
("\"Frog\"",
"EOF while parsing a value at line 1 column 6"),
+ ("\"Frog\" 0 ",
+ "EOF while parsing a value at line 1 column 6"),
("{\"Frog\":{}}",
"invalid type: map, expected tuple variant Animal::Frog at line 1 column 10"),
("{\"Cat\":[]}",
@@ -1772,3 +1774,15 @@ fn test_json_macro() {
(<Result<(), &str> as Clone>::clone(&Err("")).unwrap_err()): "err"
});
}
+
+#[test]
+fn issue_220() {
+ #[derive(Debug, PartialEq, Eq, Deserialize)]
+ enum E {
+ V(u8),
+ }
+
+ assert!(from_str::<E>(r#" "V"0 "#).is_err());
+
+ assert_eq!(from_str::<E>(r#"{"V": 0}"#).unwrap(), E::V(0));
+}
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
null |
serde-rs__json-210
| 210
|
[
"151"
] |
2017-01-24T01:40:10Z
|
These need to be fixed:
- `serde_json::ser::Formatter`
- `serde_json::ser::escape_str`
- `serde_json::ser::to_string`
- `serde_json::ser::to_string_pretty`
- `serde_json::ser::to_vec`
- `serde_json::ser::to_vec_pretty`
- `serde_json::ser::to_writer`
- `serde_json::ser::to_writer_pretty`
|
b60dc2c7b766b07d8e1a82efdf6a728e1e9613d3
|
Audit public API for missing ?Sized bounds
@withoutboats noticed that [`to_writer`](https://docs.serde.rs/serde_json/ser/fn.to_writer.html) could allow `T: ?Sized`, allowing something like `to_writer(w, "str")`.
|
diff --git a/json/Cargo.toml b/json/Cargo.toml
index 20c21adaa..1cf45631c 100644
--- a/json/Cargo.toml
+++ b/json/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_json"
-version = "0.9.0-rc1"
+version = "0.9.0-rc2"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "A JSON serialization file format"
@@ -9,16 +9,14 @@ documentation = "http://docs.serde.rs/serde_json/"
readme = "../README.md"
keywords = ["json", "serde", "serialization"]
-publish = false # this branch contains breaking changes for 0.9
-
[features]
unstable-testing = ["clippy"]
preserve_order = ["linked-hash-map"]
[dependencies]
-serde = "=0.9.0-rc2"
+serde = "=0.9.0-rc3"
num-traits = "~0.1.32"
clippy = { version = "^0.*", optional = true }
linked-hash-map = { version = "0.3", optional = true }
-itoa = "0.1"
-dtoa = "0.2"
+itoa = "0.2"
+dtoa = "0.3"
diff --git a/json/src/ser.rs b/json/src/ser.rs
index 1e93e947c..cac945b80 100644
--- a/json/src/ser.rs
+++ b/json/src/ser.rs
@@ -194,10 +194,10 @@ impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F>
/// Serialize newtypes without an object wrapper.
#[inline]
- fn serialize_newtype_struct<T>(
+ fn serialize_newtype_struct<T: ?Sized>(
self,
_name: &'static str,
- value: T
+ value: &T
) -> Result<()>
where T: ser::Serialize,
{
@@ -205,12 +205,12 @@ impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F>
}
#[inline]
- fn serialize_newtype_variant<T>(
+ fn serialize_newtype_variant<T: ?Sized>(
self,
_name: &'static str,
_variant_index: usize,
variant: &'static str,
- value: T
+ value: &T
) -> Result<()>
where T: ser::Serialize,
{
@@ -230,7 +230,7 @@ impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F>
}
#[inline]
- fn serialize_some<T>(self, value: T) -> Result<()>
+ fn serialize_some<T: ?Sized>(self, value: &T) -> Result<()>
where T: ser::Serialize,
{
value.serialize(self)
@@ -343,9 +343,9 @@ impl<'a, W, F> ser::SerializeSeq for Compound<'a, W, F>
type Error = Error;
#[inline]
- fn serialize_element<T: ser::Serialize>(
+ fn serialize_element<T: ?Sized>(
&mut self,
- value: T
+ value: &T
) -> Result<()>
where T: ser::Serialize,
{
@@ -372,10 +372,12 @@ impl<'a, W, F> ser::SerializeTuple for Compound<'a, W, F>
type Error = Error;
#[inline]
- fn serialize_element<T: ser::Serialize>(
+ fn serialize_element<T: ?Sized>(
&mut self,
- value: T
- ) -> Result<()> {
+ value: &T,
+ ) -> Result<()>
+ where T: ser::Serialize,
+ {
ser::SerializeSeq::serialize_element(self, value)
}
@@ -393,10 +395,12 @@ impl<'a, W, F> ser::SerializeTupleStruct for Compound<'a, W, F>
type Error = Error;
#[inline]
- fn serialize_field<T: ser::Serialize>(
+ fn serialize_field<T: ?Sized>(
&mut self,
- value: T
- ) -> Result<()> {
+ value: &T
+ ) -> Result<()>
+ where T: ser::Serialize,
+ {
ser::SerializeSeq::serialize_element(self, value)
}
@@ -414,10 +418,12 @@ impl<'a, W, F> ser::SerializeTupleVariant for Compound<'a, W, F>
type Error = Error;
#[inline]
- fn serialize_field<T: ser::Serialize>(
+ fn serialize_field<T: ?Sized>(
&mut self,
- value: T
- ) -> Result<()> {
+ value: &T
+ ) -> Result<()>
+ where T: ser::Serialize,
+ {
ser::SerializeSeq::serialize_element(self, value)
}
@@ -440,10 +446,12 @@ impl<'a, W, F> ser::SerializeMap for Compound<'a, W, F>
type Error = Error;
#[inline]
- fn serialize_key<T: ser::Serialize>(
+ fn serialize_key<T: ?Sized>(
&mut self,
- key: T,
- ) -> Result<()> {
+ key: &T,
+ ) -> Result<()>
+ where T: ser::Serialize,
+ {
try!(self.ser.formatter.begin_object_key(&mut self.ser.writer, self.state == State::First));
self.state = State::Rest;
@@ -455,10 +463,12 @@ impl<'a, W, F> ser::SerializeMap for Compound<'a, W, F>
}
#[inline]
- fn serialize_value<T: ser::Serialize>(
+ fn serialize_value<T: ?Sized>(
&mut self,
- value: T,
- ) -> Result<()> {
+ value: &T,
+ ) -> Result<()>
+ where T: ser::Serialize,
+ {
try!(self.ser.formatter.begin_object_value(&mut self.ser.writer));
try!(value.serialize(&mut *self.ser));
self.ser.formatter.end_object_value(&mut self.ser.writer)
@@ -481,11 +491,13 @@ impl<'a, W, F> ser::SerializeStruct for Compound<'a, W, F>
type Error = Error;
#[inline]
- fn serialize_field<V: ser::Serialize>(
+ fn serialize_field<T: ?Sized>(
&mut self,
key: &'static str,
- value: V
- ) -> Result<()> {
+ value: &T
+ ) -> Result<()>
+ where T: ser::Serialize,
+ {
try!(ser::SerializeMap::serialize_key(self, key));
ser::SerializeMap::serialize_value(self, value)
}
@@ -504,11 +516,13 @@ impl<'a, W, F> ser::SerializeStructVariant for Compound<'a, W, F>
type Error = Error;
#[inline]
- fn serialize_field<V: ser::Serialize>(
+ fn serialize_field<T: ?Sized>(
&mut self,
key: &'static str,
- value: V
- ) -> Result<()> {
+ value: &T
+ ) -> Result<()>
+ where T: ser::Serialize,
+ {
ser::SerializeStruct::serialize_field(self, key, value)
}
@@ -557,10 +571,10 @@ impl<'a, W, F> ser::Serializer for MapKeySerializer<'a, W, F>
}
#[inline]
- fn serialize_newtype_struct<T>(
+ fn serialize_newtype_struct<T: ?Sized>(
self,
_name: &'static str,
- value: T
+ value: &T
) -> Result<()>
where T: ser::Serialize,
{
@@ -663,12 +677,12 @@ impl<'a, W, F> ser::Serializer for MapKeySerializer<'a, W, F>
Err(key_must_be_a_string())
}
- fn serialize_newtype_variant<T>(
+ fn serialize_newtype_variant<T: ?Sized>(
self,
_name: &'static str,
_variant_index: usize,
_variant: &'static str,
- _value: T
+ _value: &T
) -> Result<()>
where T: ser::Serialize,
{
@@ -679,7 +693,7 @@ impl<'a, W, F> ser::Serializer for MapKeySerializer<'a, W, F>
Err(key_must_be_a_string())
}
- fn serialize_some<T>(self, _value: T) -> Result<()>
+ fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<()>
where T: ser::Serialize,
{
Err(key_must_be_a_string())
@@ -742,7 +756,7 @@ impl ser::SerializeSeq for Impossible {
type Ok = ();
type Error = Error;
- fn serialize_element<T>(&mut self, _: T) -> Result<()>
+ fn serialize_element<T: ?Sized>(&mut self, _: &T) -> Result<()>
where T: ser::Serialize
{
Err(key_must_be_a_string())
@@ -757,7 +771,7 @@ impl ser::SerializeTuple for Impossible {
type Ok = ();
type Error = Error;
- fn serialize_element<T>(&mut self, _: T) -> Result<()>
+ fn serialize_element<T: ?Sized>(&mut self, _: &T) -> Result<()>
where T: ser::Serialize
{
Err(key_must_be_a_string())
@@ -772,7 +786,7 @@ impl ser::SerializeTupleStruct for Impossible {
type Ok = ();
type Error = Error;
- fn serialize_field<T>(&mut self, _: T) -> Result<()>
+ fn serialize_field<T: ?Sized>(&mut self, _: &T) -> Result<()>
where T: ser::Serialize
{
Err(key_must_be_a_string())
@@ -787,7 +801,7 @@ impl ser::SerializeTupleVariant for Impossible {
type Ok = ();
type Error = Error;
- fn serialize_field<T>(&mut self, _: T) -> Result<()>
+ fn serialize_field<T: ?Sized>(&mut self, _: &T) -> Result<()>
where T: ser::Serialize
{
Err(key_must_be_a_string())
@@ -802,13 +816,13 @@ impl ser::SerializeMap for Impossible {
type Ok = ();
type Error = Error;
- fn serialize_key<T>(&mut self, _: T) -> Result<()>
+ fn serialize_key<T: ?Sized>(&mut self, _: &T) -> Result<()>
where T: ser::Serialize
{
Err(key_must_be_a_string())
}
- fn serialize_value<T>(&mut self, _: T) -> Result<()>
+ fn serialize_value<T: ?Sized>(&mut self, _: &T) -> Result<()>
where T: ser::Serialize
{
Err(key_must_be_a_string())
@@ -823,8 +837,8 @@ impl ser::SerializeStruct for Impossible {
type Ok = ();
type Error = Error;
- fn serialize_field<V>(&mut self, _: &'static str, _: V) -> Result<()>
- where V: ser::Serialize
+ fn serialize_field<T: ?Sized>(&mut self, _: &'static str, _: &T) -> Result<()>
+ where T: ser::Serialize
{
Err(key_must_be_a_string())
}
@@ -838,8 +852,8 @@ impl ser::SerializeStructVariant for Impossible {
type Ok = ();
type Error = Error;
- fn serialize_field<V>(&mut self, _: &'static str, _: V) -> Result<()>
- where V: ser::Serialize
+ fn serialize_field<T: ?Sized>(&mut self, _: &'static str, _: &T) -> Result<()>
+ where T: ser::Serialize
{
Err(key_must_be_a_string())
}
@@ -894,7 +908,7 @@ impl CharEscape {
pub trait Formatter {
/// Writes a `null` value to the specified writer.
#[inline]
- fn write_null<W>(&mut self, writer: &mut W) -> Result<()>
+ fn write_null<W: ?Sized>(&mut self, writer: &mut W) -> Result<()>
where W: io::Write
{
writer.write_all(b"null").map_err(From::from)
@@ -902,7 +916,7 @@ pub trait Formatter {
/// Writes a `true` or `false` value to the specified writer.
#[inline]
- fn write_bool<W>(&mut self, writer: &mut W, value: bool) -> Result<()>
+ fn write_bool<W: ?Sized>(&mut self, writer: &mut W, value: bool) -> Result<()>
where W: io::Write
{
let s = if value {
@@ -915,7 +929,7 @@ pub trait Formatter {
/// Writes an integer value like `-123` to the specified writer.
#[inline]
- fn write_isize<W>(&mut self, writer: &mut W, value: isize) -> Result<()>
+ fn write_isize<W: ?Sized>(&mut self, writer: &mut W, value: isize) -> Result<()>
where W: io::Write
{
itoa::write(writer, value).map_err(From::from)
@@ -923,7 +937,7 @@ pub trait Formatter {
/// Writes an integer value like `-123` to the specified writer.
#[inline]
- fn write_i8<W>(&mut self, writer: &mut W, value: i8) -> Result<()>
+ fn write_i8<W: ?Sized>(&mut self, writer: &mut W, value: i8) -> Result<()>
where W: io::Write
{
itoa::write(writer, value).map_err(From::from)
@@ -931,7 +945,7 @@ pub trait Formatter {
/// Writes an integer value like `-123` to the specified writer.
#[inline]
- fn write_i16<W>(&mut self, writer: &mut W, value: i16) -> Result<()>
+ fn write_i16<W: ?Sized>(&mut self, writer: &mut W, value: i16) -> Result<()>
where W: io::Write
{
itoa::write(writer, value).map_err(From::from)
@@ -939,7 +953,7 @@ pub trait Formatter {
/// Writes an integer value like `-123` to the specified writer.
#[inline]
- fn write_i32<W>(&mut self, writer: &mut W, value: i32) -> Result<()>
+ fn write_i32<W: ?Sized>(&mut self, writer: &mut W, value: i32) -> Result<()>
where W: io::Write
{
itoa::write(writer, value).map_err(From::from)
@@ -947,7 +961,7 @@ pub trait Formatter {
/// Writes an integer value like `-123` to the specified writer.
#[inline]
- fn write_i64<W>(&mut self, writer: &mut W, value: i64) -> Result<()>
+ fn write_i64<W: ?Sized>(&mut self, writer: &mut W, value: i64) -> Result<()>
where W: io::Write
{
itoa::write(writer, value).map_err(From::from)
@@ -955,7 +969,7 @@ pub trait Formatter {
/// Writes an integer value like `123` to the specified writer.
#[inline]
- fn write_usize<W>(&mut self, writer: &mut W, value: usize) -> Result<()>
+ fn write_usize<W: ?Sized>(&mut self, writer: &mut W, value: usize) -> Result<()>
where W: io::Write
{
itoa::write(writer, value).map_err(From::from)
@@ -963,7 +977,7 @@ pub trait Formatter {
/// Writes an integer value like `123` to the specified writer.
#[inline]
- fn write_u8<W>(&mut self, writer: &mut W, value: u8) -> Result<()>
+ fn write_u8<W: ?Sized>(&mut self, writer: &mut W, value: u8) -> Result<()>
where W: io::Write
{
itoa::write(writer, value).map_err(From::from)
@@ -971,7 +985,7 @@ pub trait Formatter {
/// Writes an integer value like `123` to the specified writer.
#[inline]
- fn write_u16<W>(&mut self, writer: &mut W, value: u16) -> Result<()>
+ fn write_u16<W: ?Sized>(&mut self, writer: &mut W, value: u16) -> Result<()>
where W: io::Write
{
itoa::write(writer, value).map_err(From::from)
@@ -979,7 +993,7 @@ pub trait Formatter {
/// Writes an integer value like `123` to the specified writer.
#[inline]
- fn write_u32<W>(&mut self, writer: &mut W, value: u32) -> Result<()>
+ fn write_u32<W: ?Sized>(&mut self, writer: &mut W, value: u32) -> Result<()>
where W: io::Write
{
itoa::write(writer, value).map_err(From::from)
@@ -987,7 +1001,7 @@ pub trait Formatter {
/// Writes an integer value like `123` to the specified writer.
#[inline]
- fn write_u64<W>(&mut self, writer: &mut W, value: u64) -> Result<()>
+ fn write_u64<W: ?Sized>(&mut self, writer: &mut W, value: u64) -> Result<()>
where W: io::Write
{
itoa::write(writer, value).map_err(From::from)
@@ -995,7 +1009,7 @@ pub trait Formatter {
/// Writes a floating point value like `-31.26e+12` to the specified writer.
#[inline]
- fn write_f32<W>(&mut self, writer: &mut W, value: f32) -> Result<()>
+ fn write_f32<W: ?Sized>(&mut self, writer: &mut W, value: f32) -> Result<()>
where W: io::Write
{
dtoa::write(writer, value).map_err(From::from)
@@ -1003,7 +1017,7 @@ pub trait Formatter {
/// Writes a floating point value like `-31.26e+12` to the specified writer.
#[inline]
- fn write_f64<W>(&mut self, writer: &mut W, value: f64) -> Result<()>
+ fn write_f64<W: ?Sized>(&mut self, writer: &mut W, value: f64) -> Result<()>
where W: io::Write
{
dtoa::write(writer, value).map_err(From::from)
@@ -1012,7 +1026,7 @@ pub trait Formatter {
/// Called before each series of `write_string_fragment` and
/// `write_char_escape`. Writes a `"` to the specified writer.
#[inline]
- fn begin_string<W>(&mut self, writer: &mut W) -> Result<()>
+ fn begin_string<W: ?Sized>(&mut self, writer: &mut W) -> Result<()>
where W: io::Write
{
writer.write_all(b"\"").map_err(From::from)
@@ -1021,7 +1035,7 @@ pub trait Formatter {
/// Called after each series of `write_string_fragment` and
/// `write_char_escape`. Writes a `"` to the specified writer.
#[inline]
- fn end_string<W>(&mut self, writer: &mut W) -> Result<()>
+ fn end_string<W: ?Sized>(&mut self, writer: &mut W) -> Result<()>
where W: io::Write
{
writer.write_all(b"\"").map_err(From::from)
@@ -1030,7 +1044,7 @@ pub trait Formatter {
/// Writes a string fragment that doesn't need any escaping to the
/// specified writer.
#[inline]
- fn write_string_fragment<W>(&mut self, writer: &mut W, fragment: &[u8]) -> Result<()>
+ fn write_string_fragment<W: ?Sized>(&mut self, writer: &mut W, fragment: &[u8]) -> Result<()>
where W: io::Write
{
writer.write_all(fragment).map_err(From::from)
@@ -1038,7 +1052,7 @@ pub trait Formatter {
/// Writes a character escape code to the specified writer.
#[inline]
- fn write_char_escape<W>(&mut self, writer: &mut W, char_escape: CharEscape) -> Result<()>
+ fn write_char_escape<W: ?Sized>(&mut self, writer: &mut W, char_escape: CharEscape) -> Result<()>
where W: io::Write
{
use self::CharEscape::*;
@@ -1067,7 +1081,7 @@ pub trait Formatter {
/// Called before every array. Writes a `[` to the specified
/// writer.
#[inline]
- fn begin_array<W>(&mut self, writer: &mut W) -> Result<()>
+ fn begin_array<W: ?Sized>(&mut self, writer: &mut W) -> Result<()>
where W: io::Write
{
writer.write_all(b"[").map_err(From::from)
@@ -1076,7 +1090,7 @@ pub trait Formatter {
/// Called after every array. Writes a `]` to the specified
/// writer.
#[inline]
- fn end_array<W>(&mut self, writer: &mut W) -> Result<()>
+ fn end_array<W: ?Sized>(&mut self, writer: &mut W) -> Result<()>
where W: io::Write
{
writer.write_all(b"]").map_err(From::from)
@@ -1085,7 +1099,7 @@ pub trait Formatter {
/// Called before every array value. Writes a `,` if needed to
/// the specified writer.
#[inline]
- fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
+ fn begin_array_value<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> Result<()>
where W: io::Write
{
if first {
@@ -1097,7 +1111,7 @@ pub trait Formatter {
/// Called after every array value.
#[inline]
- fn end_array_value<W>(&mut self, _writer: &mut W) -> Result<()>
+ fn end_array_value<W: ?Sized>(&mut self, _writer: &mut W) -> Result<()>
where W: io::Write
{
Ok(())
@@ -1106,7 +1120,7 @@ pub trait Formatter {
/// Called before every object. Writes a `{` to the specified
/// writer.
#[inline]
- fn begin_object<W>(&mut self, writer: &mut W) -> Result<()>
+ fn begin_object<W: ?Sized>(&mut self, writer: &mut W) -> Result<()>
where W: io::Write
{
writer.write_all(b"{").map_err(From::from)
@@ -1115,7 +1129,7 @@ pub trait Formatter {
/// Called after every object. Writes a `}` to the specified
/// writer.
#[inline]
- fn end_object<W>(&mut self, writer: &mut W) -> Result<()>
+ fn end_object<W: ?Sized>(&mut self, writer: &mut W) -> Result<()>
where W: io::Write
{
writer.write_all(b"}").map_err(From::from)
@@ -1123,7 +1137,7 @@ pub trait Formatter {
/// Called before every object key.
#[inline]
- fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
+ fn begin_object_key<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> Result<()>
where W: io::Write
{
if first {
@@ -1137,7 +1151,7 @@ pub trait Formatter {
/// specified writer by either this method or
/// `begin_object_value`.
#[inline]
- fn end_object_key<W>(&mut self, _writer: &mut W) -> Result<()>
+ fn end_object_key<W: ?Sized>(&mut self, _writer: &mut W) -> Result<()>
where W: io::Write
{
Ok(())
@@ -1147,7 +1161,7 @@ pub trait Formatter {
/// the specified writer by either this method or
/// `end_object_key`.
#[inline]
- fn begin_object_value<W>(&mut self, writer: &mut W) -> Result<()>
+ fn begin_object_value<W: ?Sized>(&mut self, writer: &mut W) -> Result<()>
where W: io::Write
{
writer.write_all(b":").map_err(From::from)
@@ -1155,7 +1169,7 @@ pub trait Formatter {
/// Called after every object value.
#[inline]
- fn end_object_value<W>(&mut self, _writer: &mut W) -> Result<()>
+ fn end_object_value<W: ?Sized>(&mut self, _writer: &mut W) -> Result<()>
where W: io::Write
{
Ok(())
@@ -1200,7 +1214,7 @@ impl<'a> Default for PrettyFormatter<'a> {
impl<'a> Formatter for PrettyFormatter<'a> {
#[inline]
- fn begin_array<W>(&mut self, writer: &mut W) -> Result<()>
+ fn begin_array<W: ?Sized>(&mut self, writer: &mut W) -> Result<()>
where W: io::Write
{
self.current_indent += 1;
@@ -1209,7 +1223,7 @@ impl<'a> Formatter for PrettyFormatter<'a> {
}
#[inline]
- fn end_array<W>(&mut self, writer: &mut W) -> Result<()>
+ fn end_array<W: ?Sized>(&mut self, writer: &mut W) -> Result<()>
where W: io::Write
{
self.current_indent -= 1;
@@ -1223,7 +1237,7 @@ impl<'a> Formatter for PrettyFormatter<'a> {
}
#[inline]
- fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
+ fn begin_array_value<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> Result<()>
where W: io::Write
{
if first {
@@ -1236,7 +1250,7 @@ impl<'a> Formatter for PrettyFormatter<'a> {
}
#[inline]
- fn end_array_value<W>(&mut self, _writer: &mut W) -> Result<()>
+ fn end_array_value<W: ?Sized>(&mut self, _writer: &mut W) -> Result<()>
where W: io::Write
{
self.has_value = true;
@@ -1244,7 +1258,7 @@ impl<'a> Formatter for PrettyFormatter<'a> {
}
#[inline]
- fn begin_object<W>(&mut self, writer: &mut W) -> Result<()>
+ fn begin_object<W: ?Sized>(&mut self, writer: &mut W) -> Result<()>
where W: io::Write
{
self.current_indent += 1;
@@ -1253,7 +1267,7 @@ impl<'a> Formatter for PrettyFormatter<'a> {
}
#[inline]
- fn end_object<W>(&mut self, writer: &mut W) -> Result<()>
+ fn end_object<W: ?Sized>(&mut self, writer: &mut W) -> Result<()>
where W: io::Write
{
self.current_indent -= 1;
@@ -1267,7 +1281,7 @@ impl<'a> Formatter for PrettyFormatter<'a> {
}
#[inline]
- fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
+ fn begin_object_key<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> Result<()>
where W: io::Write
{
if first {
@@ -1279,14 +1293,14 @@ impl<'a> Formatter for PrettyFormatter<'a> {
}
#[inline]
- fn begin_object_value<W>(&mut self, writer: &mut W) -> Result<()>
+ fn begin_object_value<W: ?Sized>(&mut self, writer: &mut W) -> Result<()>
where W: io::Write
{
writer.write_all(b": ").map_err(From::from)
}
#[inline]
- fn end_object_value<W>(&mut self, _writer: &mut W) -> Result<()>
+ fn end_object_value<W: ?Sized>(&mut self, _writer: &mut W) -> Result<()>
where W: io::Write
{
self.has_value = true;
@@ -1295,13 +1309,13 @@ impl<'a> Formatter for PrettyFormatter<'a> {
}
/// Serializes and escapes a `&str` into a JSON string.
-pub fn escape_str<W>(wr: &mut W, value: &str) -> Result<()>
+pub fn escape_str<W: ?Sized>(wr: &mut W, value: &str) -> Result<()>
where W: io::Write
{
format_escaped_str(wr, &mut CompactFormatter, value)
}
-fn format_escaped_str<W, F>(writer: &mut W, formatter: &mut F, value: &str) -> Result<()>
+fn format_escaped_str<W: ?Sized, F: ?Sized>(writer: &mut W, formatter: &mut F, value: &str) -> Result<()>
where W: io::Write,
F: Formatter
{
@@ -1368,7 +1382,7 @@ static ESCAPE: [u8; 256] = [
];
#[inline]
-fn format_escaped_char<W, F>(wr: &mut W, formatter: &mut F, value: char) -> Result<()>
+fn format_escaped_char<W: ?Sized, F: ?Sized>(wr: &mut W, formatter: &mut F, value: char) -> Result<()>
where W: io::Write,
F: Formatter,
{
@@ -1381,7 +1395,7 @@ fn format_escaped_char<W, F>(wr: &mut W, formatter: &mut F, value: char) -> Resu
/// Encode the specified struct into a json `[u8]` writer.
#[inline]
-pub fn to_writer<W: ?Sized, T>(writer: &mut W, value: &T) -> Result<()>
+pub fn to_writer<W: ?Sized, T: ?Sized>(writer: &mut W, value: &T) -> Result<()>
where W: io::Write,
T: ser::Serialize,
{
@@ -1392,7 +1406,7 @@ pub fn to_writer<W: ?Sized, T>(writer: &mut W, value: &T) -> Result<()>
/// Encode the specified struct into a json `[u8]` writer.
#[inline]
-pub fn to_writer_pretty<W: ?Sized, T>(writer: &mut W, value: &T) -> Result<()>
+pub fn to_writer_pretty<W: ?Sized, T: ?Sized>(writer: &mut W, value: &T) -> Result<()>
where W: io::Write,
T: ser::Serialize,
{
@@ -1403,7 +1417,7 @@ pub fn to_writer_pretty<W: ?Sized, T>(writer: &mut W, value: &T) -> Result<()>
/// Encode the specified struct into a json `[u8]` buffer.
#[inline]
-pub fn to_vec<T>(value: &T) -> Result<Vec<u8>>
+pub fn to_vec<T: ?Sized>(value: &T) -> Result<Vec<u8>>
where T: ser::Serialize,
{
// We are writing to a Vec, which doesn't fail. So we can ignore
@@ -1415,7 +1429,7 @@ pub fn to_vec<T>(value: &T) -> Result<Vec<u8>>
/// Encode the specified struct into a json `[u8]` buffer.
#[inline]
-pub fn to_vec_pretty<T>(value: &T) -> Result<Vec<u8>>
+pub fn to_vec_pretty<T: ?Sized>(value: &T) -> Result<Vec<u8>>
where T: ser::Serialize,
{
// We are writing to a Vec, which doesn't fail. So we can ignore
@@ -1427,7 +1441,7 @@ pub fn to_vec_pretty<T>(value: &T) -> Result<Vec<u8>>
/// Encode the specified struct into a json `String` buffer.
#[inline]
-pub fn to_string<T>(value: &T) -> Result<String>
+pub fn to_string<T: ?Sized>(value: &T) -> Result<String>
where T: ser::Serialize,
{
let vec = try!(to_vec(value));
@@ -1440,7 +1454,7 @@ pub fn to_string<T>(value: &T) -> Result<String>
/// Encode the specified struct into a json `String` buffer.
#[inline]
-pub fn to_string_pretty<T>(value: &T) -> Result<String>
+pub fn to_string_pretty<T: ?Sized>(value: &T) -> Result<String>
where T: ser::Serialize,
{
let vec = try!(to_vec_pretty(value));
@@ -1451,7 +1465,7 @@ pub fn to_string_pretty<T>(value: &T) -> Result<String>
Ok(string)
}
-fn indent<W>(wr: &mut W, n: usize, s: &[u8]) -> Result<()>
+fn indent<W: ?Sized>(wr: &mut W, n: usize, s: &[u8]) -> Result<()>
where W: io::Write,
{
for _ in 0..n {
diff --git a/json/src/value.rs b/json/src/value.rs
index c284dd621..6b4cdbdbb 100644
--- a/json/src/value.rs
+++ b/json/src/value.rs
@@ -677,22 +677,22 @@ impl ser::Serializer for Serializer {
}
#[inline]
- fn serialize_newtype_struct<T>(
+ fn serialize_newtype_struct<T: ?Sized>(
self,
_name: &'static str,
- value: T
+ value: &T
) -> Result<Value, Error>
where T: ser::Serialize,
{
value.serialize(self)
}
- fn serialize_newtype_variant<T>(
+ fn serialize_newtype_variant<T: ?Sized>(
self,
_name: &'static str,
_variant_index: usize,
variant: &'static str,
- value: T
+ value: &T
) -> Result<Value, Error>
where T: ser::Serialize,
{
@@ -707,8 +707,8 @@ impl ser::Serializer for Serializer {
}
#[inline]
- fn serialize_some<V>(self, value: V) -> Result<Value, Error>
- where V: ser::Serialize,
+ fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Value, Error>
+ where T: ser::Serialize,
{
value.serialize(self)
}
@@ -813,7 +813,7 @@ impl ser::SerializeSeq for SerializeVec {
type Ok = Value;
type Error = Error;
- fn serialize_element<T>(&mut self, value: T) -> Result<(), Error>
+ fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
where T: ser::Serialize
{
self.vec.push(try!(to_value(&value)));
@@ -829,7 +829,7 @@ impl ser::SerializeTuple for SerializeVec {
type Ok = Value;
type Error = Error;
- fn serialize_element<T>(&mut self, value: T) -> Result<(), Error>
+ fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
where T: ser::Serialize
{
ser::SerializeSeq::serialize_element(self, value)
@@ -844,7 +844,7 @@ impl ser::SerializeTupleStruct for SerializeVec {
type Ok = Value;
type Error = Error;
- fn serialize_field<T>(&mut self, value: T) -> Result<(), Error>
+ fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
where T: ser::Serialize
{
ser::SerializeSeq::serialize_element(self, value)
@@ -859,7 +859,7 @@ impl ser::SerializeTupleVariant for SerializeTupleVariant {
type Ok = Value;
type Error = Error;
- fn serialize_field<T>(&mut self, value: T) -> Result<(), Error>
+ fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
where T: ser::Serialize
{
self.vec.push(try!(to_value(&value)));
@@ -879,7 +879,7 @@ impl ser::SerializeMap for SerializeMap {
type Ok = Value;
type Error = Error;
- fn serialize_key<T>(&mut self, key: T) -> Result<(), Error>
+ fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Error>
where T: ser::Serialize
{
match try!(to_value(&key)) {
@@ -889,7 +889,7 @@ impl ser::SerializeMap for SerializeMap {
Ok(())
}
- fn serialize_value<T>(&mut self, value: T) -> Result<(), Error>
+ fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
where T: ser::Serialize
{
let key = self.next_key.take();
@@ -909,8 +909,8 @@ impl ser::SerializeStruct for SerializeMap {
type Ok = Value;
type Error = Error;
- fn serialize_field<V>(&mut self, key: &'static str, value: V) -> Result<(), Error>
- where V: ser::Serialize
+ fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
+ where T: ser::Serialize
{
try!(ser::SerializeMap::serialize_key(self, key));
ser::SerializeMap::serialize_value(self, value)
@@ -925,8 +925,8 @@ impl ser::SerializeStructVariant for SerializeStructVariant {
type Ok = Value;
type Error = Error;
- fn serialize_field<V>(&mut self, key: &'static str, value: V) -> Result<(), Error>
- where V: ser::Serialize
+ fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
+ where T: ser::Serialize
{
self.map.insert(String::from(key), try!(to_value(&value)));
Ok(())
|
diff --git a/json_tests/Cargo.toml b/json_tests/Cargo.toml
index f246e74cf..6d9544ffe 100644
--- a/json_tests/Cargo.toml
+++ b/json_tests/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_json_tests"
-version = "0.9.0-rc1"
+version = "0.9.0-rc2"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
build = "build.rs"
publish = false
@@ -13,7 +13,7 @@ trace-macros = []
[build-dependencies]
indoc = "*"
-serde_codegen = { version = "=0.9.0-rc2", optional = true }
+serde_codegen = { version = "=0.9.0-rc3", optional = true }
skeptic = "0.6"
syntex = { version = "*", optional = true }
@@ -22,9 +22,9 @@ clippy = { version = "^0.*", optional = true }
indoc = "*"
num-traits = "*"
rustc-serialize = "*"
-serde = "=0.9.0-rc2"
+serde = "=0.9.0-rc3"
serde_json = { path = "../json" }
-serde_derive = { version = "=0.9.0-rc2", optional = true }
+serde_derive = { version = "=0.9.0-rc3", optional = true }
skeptic = "0.6"
[[test]]
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
null |
serde-rs__json-205
| 205
|
[
"193"
] |
2017-01-21T19:23:13Z
|
You're right, this is not possible with the current serde_json API. We did some contortions when we introduced the DeserializeImpl-related optimizations (the separate specializations for &str vs &[u8] vs io::Read) to avoid breaking backward compatibility. I will try to rework some of this for 0.9.0 to make specialization possible.
Hmm. Would it be possible to make `DeserializerImpl` public for the time being so there's at least some way to specialise on it, even it's to be scrapped later on?
@dtolnay Ok, scratch the previous comment, I've found a pretty hilarious way of specialising which actually works (at least it looks like it does)... on the error type 😃
As you said, would be sure nice to be able to do it without such hacks.
```rust
impl serde::Deserialize for Foo {
fn deserialize<D>(de: &mut D) -> ::std::result::Result<Foo, D::Error>
where D: serde::Deserializer
{
type Result<E> = ::std::result::Result<Foo, E>;
trait Deserialize<E> {
fn deserialize<D: serde::Deserializer>(de: &mut D) -> Result<D::Error>;
}
impl<E> Deserialize<E> for Foo {
default fn deserialize<D: serde::Deserializer>(de: &mut D) -> Result<D::Error> {
/* Default impl */
}
}
impl Deserialize<json::Error> for Foo {
fn deserialize<D: serde::Deserializer>(de: &mut D) -> Result<D::Error> {
/* JSON specialization */
}
}
<Foo as Deserialize<D::Error>>::deserialize(de)
}
}
```
|
7a040fccab33df2a5a894dc378a77a18b9fdd317
|
How to specialise on JSON deserialiser
Now that there's a non-public `DeserializerImpl` which is the one that's actually being used in `from_trait()`, it seems to have become impossible to use specialisation on JSON decoders when using the top-level `from_*()` methods.
E.g., I naively assumed something like this would work:
```rust
#![feature(specialization)]
struct Foo;
impl serde::Deserialize for Foo {
fn deserialize<D>(de: &mut D) -> Result<Foo, D::Error>
where D: serde::Deserializer
{
type Result<E> = Result<Foo, E>;
trait Deserialize<D: serde::Deserializer> {
fn deserialize(de: &mut D) -> Result<D::Error>;
}
impl<D: serde::Deserializer> Deserialize<D> for Foo {
default fn deserialize(de: &mut D) -> Result<D::Error> {
/* Default impl */
}
}
impl<Iter> Deserialize<json::Deserializer<Iter>> for Foo
where Iter: Iterator<Item=::std::io::Result<u8>>
{
fn deserialize(de: &mut json::Deserializer<Iter>) -> Result<json::Error> {
/* JSON specialization */
}
}
<Foo as Deserialize<D>>::deserialize(de)
}
}
```
... and it kind of does, but the default impl is triggered when you use functions like `from_str()`, because `serde_json` doesn't use `serde_json::Deserializer` but instead a custom hidden deserialiser.
Would it make sense for `from_trait()` to somehow use `serde_json::Deserializer` instead? (apologies if I'm missing something obvious; maybe this problem is currently unavoidable)
|
diff --git a/json/Cargo.toml b/json/Cargo.toml
index 28c62ba14..d9b1745f8 100644
--- a/json/Cargo.toml
+++ b/json/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_json"
-version = "0.8.6"
+version = "0.9.0-rc1"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "A JSON serialization file format"
diff --git a/json/src/de.rs b/json/src/de.rs
index c535290c4..0adfe4144 100644
--- a/json/src/de.rs
+++ b/json/src/de.rs
@@ -15,86 +15,52 @@ use read::{self, Read};
//////////////////////////////////////////////////////////////////////////////
/// A structure that deserializes JSON into Rust values.
-pub struct Deserializer<Iter>(DeserializerImpl<read::IteratorRead<Iter>>)
- where Iter: Iterator<Item = io::Result<u8>>;
-
-impl<Iter> Deserializer<Iter>
- where Iter: Iterator<Item = io::Result<u8>>,
-{
- /// Creates the JSON parser from an `std::iter::Iterator`.
- #[inline]
- pub fn new(rdr: Iter) -> Self {
- Deserializer(DeserializerImpl::new(read::IteratorRead::new(rdr)))
- }
+pub struct Deserializer<R> {
+ read: R,
+ str_buf: Vec<u8>,
+ remaining_depth: u8,
+}
- /// The `Deserializer::end` method should be called after a value has been fully deserialized.
- /// This allows the `Deserializer` to validate that the input stream is at the end or that it
- /// only has trailing whitespace.
- #[inline]
- pub fn end(&mut self) -> Result<()> {
- self.0.end()
+impl<R> Deserializer<R> {
+ fn new(read: R) -> Self {
+ Deserializer {
+ read: read,
+ str_buf: Vec::with_capacity(128),
+ remaining_depth: 128,
+ }
}
}
-impl<'a, Iter> de::Deserializer for &'a mut Deserializer<Iter>
- where Iter: Iterator<Item = io::Result<u8>>,
+impl<I> Deserializer<read::IteratorRead<I>>
+ where I: Iterator<Item = io::Result<u8>>
{
- type Error = Error;
-
- #[inline]
- fn deserialize<V>(self, visitor: V) -> Result<V::Value>
- where V: de::Visitor,
- {
- self.0.deserialize(visitor)
- }
-
- /// Parses a `null` as a None, and any other values as a `Some(...)`.
- #[inline]
- fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
- where V: de::Visitor,
- {
- self.0.deserialize_option(visitor)
- }
-
- /// Parses a newtype struct as the underlying value.
- #[inline]
- fn deserialize_newtype_struct<V>(
- self,
- name: &'static str,
- visitor: V
- ) -> Result<V::Value>
- where V: de::Visitor,
- {
- self.0.deserialize_newtype_struct(name, visitor)
+ /// Creates a JSON parser from a `std::iter::Iterator`.
+ pub fn from_iter(iter: I) -> Self {
+ Deserializer::new(read::IteratorRead::new(iter))
}
+}
- /// Parses an enum as an object like `{"$KEY":$VALUE}`, where $VALUE is either a straight
- /// value, a `[..]`, or a `{..}`.
- #[inline]
- fn deserialize_enum<V>(
- self,
- name: &'static str,
- variants: &'static [&'static str],
- visitor: V
- ) -> Result<V::Value>
- where V: de::Visitor,
- {
- self.0.deserialize_enum(name, variants, visitor)
+impl<R> Deserializer<read::IteratorRead<io::Bytes<R>>>
+ where R: io::Read
+{
+ /// Creates a JSON parser from an `io::Read`.
+ pub fn from_reader(reader: R) -> Self {
+ Deserializer::new(read::IteratorRead::new(reader.bytes()))
}
+}
- forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit seq seq_fixed_size bytes byte_buf map unit_struct tuple_struct
- struct struct_field tuple ignored_any
+impl<'a> Deserializer<read::SliceRead<'a>> {
+ /// Creates a JSON parser from a `&[u8]`.
+ pub fn from_slice(bytes: &'a [u8]) -> Self {
+ Deserializer::new(read::SliceRead::new(bytes))
}
}
-//////////////////////////////////////////////////////////////////////////////
-
-struct DeserializerImpl<R: Read> {
- read: R,
- str_buf: Vec<u8>,
- remaining_depth: u8,
+impl<'a> Deserializer<read::StrRead<'a>> {
+ /// Creates a JSON parser from a `&str`.
+ pub fn from_str(s: &'a str) -> Self {
+ Deserializer::new(read::StrRead::new(s))
+ }
}
macro_rules! overflow {
@@ -103,16 +69,11 @@ macro_rules! overflow {
}
}
-impl<R: Read> DeserializerImpl<R> {
- fn new(read: R) -> Self {
- DeserializerImpl {
- read: read,
- str_buf: Vec::with_capacity(128),
- remaining_depth: 128,
- }
- }
-
- fn end(&mut self) -> Result<()> {
+impl<R: Read> Deserializer<R> {
+ /// The `Deserializer::end` method should be called after a value has been fully deserialized.
+ /// This allows the `Deserializer` to validate that the input stream is at the end or that it
+ /// only has trailing whitespace.
+ pub fn end(&mut self) -> Result<()> {
if try!(self.parse_whitespace()) { // true if eof
Ok(())
} else {
@@ -120,6 +81,18 @@ impl<R: Read> DeserializerImpl<R> {
}
}
+ /// Turn a JSON deserializer into an iterator over values of type T.
+ pub fn into_iter<T>(self) -> StreamDeserializer<R, T>
+ where T: de::Deserialize
+ {
+ // This cannot be an implementation of std::iter::IntoIterator because
+ // we need the caller to choose what T is.
+ StreamDeserializer {
+ de: self,
+ _marker: PhantomData,
+ }
+ }
+
fn peek(&mut self) -> Result<Option<u8>> {
self.read.peek().map_err(Error::Io)
}
@@ -601,7 +574,7 @@ static POW10: [f64; 309] =
1e290, 1e291, 1e292, 1e293, 1e294, 1e295, 1e296, 1e297, 1e298, 1e299,
1e300, 1e301, 1e302, 1e303, 1e304, 1e305, 1e306, 1e307, 1e308];
-impl<'a, R: Read> de::Deserializer for &'a mut DeserializerImpl<R> {
+impl<'a, R: Read> de::Deserializer for &'a mut Deserializer<R> {
type Error = Error;
#[inline]
@@ -685,12 +658,12 @@ impl<'a, R: Read> de::Deserializer for &'a mut DeserializerImpl<R> {
}
struct SeqVisitor<'a, R: Read + 'a> {
- de: &'a mut DeserializerImpl<R>,
+ de: &'a mut Deserializer<R>,
first: bool,
}
impl<'a, R: Read + 'a> SeqVisitor<'a, R> {
- fn new(de: &'a mut DeserializerImpl<R>) -> Self {
+ fn new(de: &'a mut Deserializer<R>) -> Self {
SeqVisitor {
de: de,
first: true,
@@ -732,12 +705,12 @@ impl<'a, R: Read + 'a> de::SeqVisitor for SeqVisitor<'a, R> {
}
struct MapVisitor<'a, R: Read + 'a> {
- de: &'a mut DeserializerImpl<R>,
+ de: &'a mut Deserializer<R>,
first: bool,
}
impl<'a, R: Read + 'a> MapVisitor<'a, R> {
- fn new(de: &'a mut DeserializerImpl<R>) -> Self {
+ fn new(de: &'a mut Deserializer<R>) -> Self {
MapVisitor {
de: de,
first: true,
@@ -792,11 +765,11 @@ impl<'a, R: Read + 'a> de::MapVisitor for MapVisitor<'a, R> {
}
struct VariantVisitor<'a, R: Read + 'a> {
- de: &'a mut DeserializerImpl<R>,
+ de: &'a mut Deserializer<R>,
}
impl<'a, R: Read + 'a> VariantVisitor<'a, R> {
- fn new(de: &'a mut DeserializerImpl<R>) -> Self {
+ fn new(de: &'a mut Deserializer<R>) -> Self {
VariantVisitor {
de: de,
}
@@ -847,11 +820,11 @@ impl<'a, R: Read + 'a> de::VariantVisitor for VariantVisitor<'a, R> {
}
struct KeyOnlyVariantVisitor<'a, R: Read + 'a> {
- de: &'a mut DeserializerImpl<R>,
+ de: &'a mut Deserializer<R>,
}
impl<'a, R: Read + 'a> KeyOnlyVariantVisitor<'a, R> {
- fn new(de: &'a mut DeserializerImpl<R>) -> Self {
+ fn new(de: &'a mut Deserializer<R>) -> Self {
KeyOnlyVariantVisitor {
de: de,
}
@@ -903,30 +876,16 @@ impl<'a, R: Read + 'a> de::VariantVisitor for KeyOnlyVariantVisitor<'a, R> {
//////////////////////////////////////////////////////////////////////////////
/// Iterator that deserializes a stream into multiple JSON values.
-pub struct StreamDeserializer<T, Iter>
- where Iter: Iterator<Item = io::Result<u8>>,
+pub struct StreamDeserializer<R, T>
+ where R: Read,
T: de::Deserialize,
{
- deser: DeserializerImpl<read::IteratorRead<Iter>>,
+ de: Deserializer<R>,
_marker: PhantomData<T>,
}
-impl<T, Iter> StreamDeserializer<T, Iter>
- where Iter: Iterator<Item = io::Result<u8>>,
- T: de::Deserialize,
-{
- /// Returns an `Iterator` of decoded JSON values from an iterator over
- /// `Iterator<Item=io::Result<u8>>`.
- pub fn new(iter: Iter) -> StreamDeserializer<T, Iter> {
- StreamDeserializer {
- deser: DeserializerImpl::new(read::IteratorRead::new(iter)),
- _marker: PhantomData,
- }
- }
-}
-
-impl<T, Iter> Iterator for StreamDeserializer<T, Iter>
- where Iter: Iterator<Item = io::Result<u8>>,
+impl<R, T> Iterator for StreamDeserializer<R, T>
+ where R: Read,
T: de::Deserialize,
{
type Item = Result<T>;
@@ -935,10 +894,10 @@ impl<T, Iter> Iterator for StreamDeserializer<T, Iter>
// skip whitespaces, if any
// this helps with trailing whitespaces, since whitespaces between
// values are handled for us.
- match self.deser.parse_whitespace() {
+ match self.de.parse_whitespace() {
Ok(true) => None, // eof
Ok(false) => {
- match de::Deserialize::deserialize(&mut self.deser) {
+ match de::Deserialize::deserialize(&mut self.de) {
Ok(v) => Some(Ok(v)),
Err(e) => Some(Err(e)),
}
@@ -954,7 +913,7 @@ fn from_trait<R, T>(read: R) -> Result<T>
where R: Read,
T: de::Deserialize,
{
- let mut de = DeserializerImpl::new(read);
+ let mut de = Deserializer::new(read);
let value = try!(de::Deserialize::deserialize(&mut de));
// Make sure the whole stream has been consumed.
diff --git a/json/src/lib.rs b/json/src/lib.rs
index 5ee49ac08..041026e12 100644
--- a/json/src/lib.rs
+++ b/json/src/lib.rs
@@ -119,6 +119,8 @@
#![cfg_attr(feature = "clippy", allow(doc_markdown))]
// Whitelisted clippy_pedantic lints
#![cfg_attr(feature = "clippy", allow(
+// Deserializer::from_str, from_iter, into_iter
+ should_implement_trait,
// integer and float ser/de requires these sorts of casts
cast_possible_truncation,
cast_possible_wrap,
|
diff --git a/json_tests/Cargo.toml b/json_tests/Cargo.toml
index f3f6b45dc..e3b268954 100644
--- a/json_tests/Cargo.toml
+++ b/json_tests/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_json_tests"
-version = "0.8.6"
+version = "0.9.0-rc1"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
build = "build.rs"
publish = false
diff --git a/json_tests/tests/test.rs.in b/json_tests/tests/test.rs.in
index 0a7dc5436..9f74ba242 100644
--- a/json_tests/tests/test.rs.in
+++ b/json_tests/tests/test.rs.in
@@ -11,7 +11,7 @@ use serde::ser;
use serde::bytes::{ByteBuf, Bytes};
use serde_json::{
- StreamDeserializer,
+ Deserializer,
Value,
Map,
from_iter,
@@ -1476,7 +1476,6 @@ fn test_serialize_map_with_no_len() {
#[test]
fn test_deserialize_from_stream() {
use std::net;
- use std::io::Read;
use std::thread;
use serde::Deserialize;
@@ -1493,7 +1492,7 @@ fn test_deserialize_from_stream() {
let mut stream = stream.unwrap();
let read_stream = stream.try_clone().unwrap();
- let mut de = serde_json::Deserializer::new(read_stream.bytes());
+ let mut de = Deserializer::from_reader(read_stream);
let request = Message::deserialize(&mut de).unwrap();
let response = Message { message: request.message };
serde_json::to_writer(&mut stream, &response).unwrap();
@@ -1504,7 +1503,7 @@ fn test_deserialize_from_stream() {
let request = Message { message: "hi there".to_string() };
serde_json::to_writer(&mut stream, &request).unwrap();
- let mut de = serde_json::Deserializer::new(stream.bytes());
+ let mut de = Deserializer::from_reader(stream);
let response = Message::deserialize(&mut de).unwrap();
assert_eq!(request, response);
@@ -1593,10 +1592,8 @@ fn test_byte_buf_de() {
#[test]
fn test_json_stream_newlines() {
- let stream = "{\"x\":39} {\"x\":40}{\"x\":41}\n{\"x\":42}".to_string();
- let mut parsed: StreamDeserializer<Value, _> = StreamDeserializer::new(
- stream.as_bytes().iter().map(|byte| Ok(*byte))
- );
+ let data = "{\"x\":39} {\"x\":40}{\"x\":41}\n{\"x\":42}";
+ let mut parsed = Deserializer::from_str(data).into_iter::<Value>();
assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(),
&39.into());
@@ -1611,10 +1608,8 @@ fn test_json_stream_newlines() {
#[test]
fn test_json_stream_trailing_whitespaces() {
- let stream = "{\"x\":42} \t\n".to_string();
- let mut parsed: StreamDeserializer<Value, _> = StreamDeserializer::new(
- stream.as_bytes().iter().map(|byte| Ok(*byte))
- );
+ let data = "{\"x\":42} \t\n";
+ let mut parsed = Deserializer::from_str(data).into_iter::<Value>();
assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(),
&42.into());
@@ -1623,10 +1618,8 @@ fn test_json_stream_trailing_whitespaces() {
#[test]
fn test_json_stream_truncated() {
- let stream = "{\"x\":40}\n{\"x\":".to_string();
- let mut parsed: StreamDeserializer<Value, _> = StreamDeserializer::new(
- stream.as_bytes().iter().map(|byte| Ok(*byte))
- );
+ let data = "{\"x\":40}\n{\"x\":";
+ let mut parsed = Deserializer::from_str(data).into_iter::<Value>();
assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(),
&40.into());
@@ -1636,10 +1629,8 @@ fn test_json_stream_truncated() {
#[test]
fn test_json_stream_empty() {
- let stream = "".to_string();
- let mut parsed: StreamDeserializer<Value, _> = StreamDeserializer::new(
- stream.as_bytes().iter().map(|byte| Ok(*byte))
- );
+ let data = "";
+ let mut parsed = Deserializer::from_str(data).into_iter::<Value>();
assert!(parsed.next().is_none());
}
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
null |
serde-rs__json-197
| 197
|
[
"196"
] |
2017-01-18T06:27:27Z
|
c7101a1d41f6f08a829fed10d649c2937292172d
|
Merge the old v0.9.0 branch into master
There is a branch from https://github.com/serde-rs/json/pull/143 that has unfortunately gotten pretty stale. We can merge it in now but it will take some work.
|
diff --git a/json/src/ser.rs b/json/src/ser.rs
index 67d8df0bb..efc50baf5 100644
--- a/json/src/ser.rs
+++ b/json/src/ser.rs
@@ -75,81 +75,91 @@ impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F>
#[inline]
fn serialize_bool(self, value: bool) -> Result<()> {
- if value {
- self.writer.write_all(b"true").map_err(From::from)
- } else {
- self.writer.write_all(b"false").map_err(From::from)
- }
+ self.formatter.write_bool(&mut self.writer, value)
}
#[inline]
fn serialize_isize(self, value: isize) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.formatter.write_isize(&mut self.writer, value)
}
#[inline]
fn serialize_i8(self, value: i8) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.formatter.write_i8(&mut self.writer, value)
}
#[inline]
fn serialize_i16(self, value: i16) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.formatter.write_i16(&mut self.writer, value)
}
#[inline]
fn serialize_i32(self, value: i32) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.formatter.write_i32(&mut self.writer, value)
}
#[inline]
fn serialize_i64(self, value: i64) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.formatter.write_i64(&mut self.writer, value)
}
#[inline]
fn serialize_usize(self, value: usize) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.formatter.write_usize(&mut self.writer, value)
}
#[inline]
fn serialize_u8(self, value: u8) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.formatter.write_u8(&mut self.writer, value)
}
#[inline]
fn serialize_u16(self, value: u16) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.formatter.write_u16(&mut self.writer, value)
}
#[inline]
fn serialize_u32(self, value: u32) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.formatter.write_u32(&mut self.writer, value)
}
#[inline]
fn serialize_u64(self, value: u64) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.formatter.write_u64(&mut self.writer, value)
}
#[inline]
fn serialize_f32(self, value: f32) -> Result<()> {
- fmt_f32_or_null(&mut self.writer, value).map_err(From::from)
+ match value.classify() {
+ FpCategory::Nan | FpCategory::Infinite => {
+ self.formatter.write_null(&mut self.writer)
+ }
+ _ => {
+ self.formatter.write_f32(&mut self.writer, value)
+ }
+ }
}
#[inline]
fn serialize_f64(self, value: f64) -> Result<()> {
- fmt_f64_or_null(&mut self.writer, value).map_err(From::from)
+ match value.classify() {
+ FpCategory::Nan | FpCategory::Infinite => {
+ self.formatter.write_null(&mut self.writer)
+ }
+ _ => {
+ self.formatter.write_f64(&mut self.writer, value)
+ }
+ }
}
#[inline]
fn serialize_char(self, value: char) -> Result<()> {
- escape_char(&mut self.writer, value).map_err(From::from)
+ format_escaped_char(&mut self.writer, &mut self.formatter, value).map_err(From::from)
}
#[inline]
fn serialize_str(self, value: &str) -> Result<()> {
- escape_str(&mut self.writer, value).map_err(From::from)
+ format_escaped_str(&mut self.writer, &mut self.formatter, value).map_err(From::from)
}
#[inline]
@@ -164,7 +174,7 @@ impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F>
#[inline]
fn serialize_unit(self) -> Result<()> {
- self.writer.write_all(b"null").map_err(From::from)
+ self.formatter.write_null(&mut self.writer)
}
#[inline]
@@ -204,12 +214,14 @@ impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F>
) -> Result<()>
where T: ser::Serialize,
{
- try!(self.formatter.open(&mut self.writer, b'{'));
- try!(self.formatter.comma(&mut self.writer, true));
+ try!(self.formatter.begin_object(&mut self.writer));
+ try!(self.formatter.begin_object_key(&mut self.writer, true));
try!(self.serialize_str(variant));
- try!(self.formatter.colon(&mut self.writer));
+ try!(self.formatter.end_object_key(&mut self.writer));
+ try!(self.formatter.begin_object_value(&mut self.writer));
try!(value.serialize(&mut *self));
- self.formatter.close(&mut self.writer, b'}')
+ try!(self.formatter.end_object_value(&mut self.writer));
+ self.formatter.end_object(&mut self.writer)
}
#[inline]
@@ -227,10 +239,11 @@ impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F>
#[inline]
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
if len == Some(0) {
- try!(self.writer.write_all(b"[]"));
+ try!(self.formatter.begin_array(&mut self.writer));
+ try!(self.formatter.end_array(&mut self.writer));
Ok(Compound { ser: self, state: State::Empty })
} else {
- try!(self.formatter.open(&mut self.writer, b'['));
+ try!(self.formatter.begin_array(&mut self.writer));
Ok(Compound { ser: self, state: State::First })
}
}
@@ -262,20 +275,22 @@ impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F>
variant: &'static str,
len: usize
) -> Result<Self::SerializeTupleVariant> {
- try!(self.formatter.open(&mut self.writer, b'{'));
- try!(self.formatter.comma(&mut self.writer, true));
+ try!(self.formatter.begin_object(&mut self.writer));
+ try!(self.formatter.begin_object_key(&mut self.writer, true));
try!(self.serialize_str(variant));
- try!(self.formatter.colon(&mut self.writer));
+ try!(self.formatter.end_object_key(&mut self.writer));
+ try!(self.formatter.begin_object_value(&mut self.writer));
self.serialize_seq(Some(len))
}
#[inline]
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
if len == Some(0) {
- try!(self.writer.write_all(b"{}"));
+ try!(self.formatter.begin_object(&mut self.writer));
+ try!(self.formatter.end_object(&mut self.writer));
Ok(Compound { ser: self, state: State::Empty })
} else {
- try!(self.formatter.open(&mut self.writer, b'{'));
+ try!(self.formatter.begin_object(&mut self.writer));
Ok(Compound { ser: self, state: State::First })
}
}
@@ -297,10 +312,11 @@ impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F>
variant: &'static str,
len: usize
) -> Result<Self::SerializeStructVariant> {
- try!(self.formatter.open(&mut self.writer, b'{'));
- try!(self.formatter.comma(&mut self.writer, true));
+ try!(self.formatter.begin_object(&mut self.writer));
+ try!(self.formatter.begin_object_key(&mut self.writer, true));
try!(self.serialize_str(variant));
- try!(self.formatter.colon(&mut self.writer));
+ try!(self.formatter.end_object_key(&mut self.writer));
+ try!(self.formatter.begin_object_value(&mut self.writer));
self.serialize_map(Some(len))
}
}
@@ -333,17 +349,17 @@ impl<'a, W, F> ser::SerializeSeq for Compound<'a, W, F>
) -> Result<()>
where T: ser::Serialize,
{
- try!(self.ser.formatter.comma(&mut self.ser.writer, self.state == State::First));
+ try!(self.ser.formatter.begin_array_value(&mut self.ser.writer, self.state == State::First));
self.state = State::Rest;
-
- value.serialize(&mut *self.ser)
+ try!(value.serialize(&mut *self.ser));
+ self.ser.formatter.end_array_value(&mut self.ser.writer)
}
#[inline]
fn end(self) -> Result<()> {
match self.state {
State::Empty => Ok(()),
- _ => self.ser.formatter.close(&mut self.ser.writer, b']'),
+ _ => self.ser.formatter.end_array(&mut self.ser.writer),
}
}
}
@@ -409,9 +425,10 @@ impl<'a, W, F> ser::SerializeTupleVariant for Compound<'a, W, F>
fn end(self) -> Result<()> {
match self.state {
State::Empty => {}
- _ => try!(self.ser.formatter.close(&mut self.ser.writer, b']')),
+ _ => try!(self.ser.formatter.end_array(&mut self.ser.writer)),
}
- self.ser.formatter.close(&mut self.ser.writer, b'}')
+ try!(self.ser.formatter.end_object_value(&mut self.ser.writer));
+ self.ser.formatter.end_object(&mut self.ser.writer)
}
}
@@ -427,14 +444,14 @@ impl<'a, W, F> ser::SerializeMap for Compound<'a, W, F>
&mut self,
key: T,
) -> Result<()> {
- try!(self.ser.formatter.comma(&mut self.ser.writer, self.state == State::First));
+ try!(self.ser.formatter.begin_object_key(&mut self.ser.writer, self.state == State::First));
self.state = State::Rest;
try!(key.serialize(MapKeySerializer {
ser: self.ser,
}));
- self.ser.formatter.colon(&mut self.ser.writer)
+ self.ser.formatter.end_object_key(&mut self.ser.writer)
}
#[inline]
@@ -442,14 +459,16 @@ impl<'a, W, F> ser::SerializeMap for Compound<'a, W, F>
&mut self,
value: T,
) -> Result<()> {
- value.serialize(&mut *self.ser)
+ try!(self.ser.formatter.begin_object_value(&mut self.ser.writer));
+ try!(value.serialize(&mut *self.ser));
+ self.ser.formatter.end_object_value(&mut self.ser.writer)
}
#[inline]
fn end(self) -> Result<()> {
match self.state {
State::Empty => Ok(()),
- _ => self.ser.formatter.close(&mut self.ser.writer, b'}'),
+ _ => self.ser.formatter.end_object(&mut self.ser.writer),
}
}
}
@@ -497,9 +516,10 @@ impl<'a, W, F> ser::SerializeStructVariant for Compound<'a, W, F>
fn end(self) -> Result<()> {
match self.state {
State::Empty => {}
- _ => try!(self.ser.formatter.close(&mut self.ser.writer, b'}')),
+ _ => try!(self.ser.formatter.end_object(&mut self.ser.writer)),
}
- self.ser.formatter.close(&mut self.ser.writer, b'}')
+ try!(self.ser.formatter.end_object_value(&mut self.ser.writer));
+ self.ser.formatter.end_object(&mut self.ser.writer)
}
}
@@ -556,49 +576,63 @@ impl<'a, W, F> ser::Serializer for MapKeySerializer<'a, W, F>
}
fn serialize_isize(self, value: isize) -> Result<()> {
- self.serialize_i64(value as i64)
+ try!(self.ser.formatter.begin_string(&mut self.ser.writer));
+ try!(self.ser.formatter.write_isize(&mut self.ser.writer, value));
+ self.ser.formatter.end_string(&mut self.ser.writer)
}
fn serialize_i8(self, value: i8) -> Result<()> {
- self.serialize_i64(value as i64)
+ try!(self.ser.formatter.begin_string(&mut self.ser.writer));
+ try!(self.ser.formatter.write_i8(&mut self.ser.writer, value));
+ self.ser.formatter.end_string(&mut self.ser.writer)
}
fn serialize_i16(self, value: i16) -> Result<()> {
- self.serialize_i64(value as i64)
+ try!(self.ser.formatter.begin_string(&mut self.ser.writer));
+ try!(self.ser.formatter.write_i16(&mut self.ser.writer, value));
+ self.ser.formatter.end_string(&mut self.ser.writer)
}
fn serialize_i32(self, value: i32) -> Result<()> {
- self.serialize_i64(value as i64)
+ try!(self.ser.formatter.begin_string(&mut self.ser.writer));
+ try!(self.ser.formatter.write_i32(&mut self.ser.writer, value));
+ self.ser.formatter.end_string(&mut self.ser.writer)
}
fn serialize_i64(self, value: i64) -> Result<()> {
- try!(self.ser.writer.write_all(b"\""));
- try!(self.ser.serialize_i64(value));
- try!(self.ser.writer.write_all(b"\""));
- Ok(())
+ try!(self.ser.formatter.begin_string(&mut self.ser.writer));
+ try!(self.ser.formatter.write_i64(&mut self.ser.writer, value));
+ self.ser.formatter.end_string(&mut self.ser.writer)
}
fn serialize_usize(self, value: usize) -> Result<()> {
- self.serialize_u64(value as u64)
+ try!(self.ser.formatter.begin_string(&mut self.ser.writer));
+ try!(self.ser.formatter.write_usize(&mut self.ser.writer, value));
+ self.ser.formatter.end_string(&mut self.ser.writer)
}
fn serialize_u8(self, value: u8) -> Result<()> {
- self.serialize_u64(value as u64)
+ try!(self.ser.formatter.begin_string(&mut self.ser.writer));
+ try!(self.ser.formatter.write_u8(&mut self.ser.writer, value));
+ self.ser.formatter.end_string(&mut self.ser.writer)
}
fn serialize_u16(self, value: u16) -> Result<()> {
- self.serialize_u64(value as u64)
+ try!(self.ser.formatter.begin_string(&mut self.ser.writer));
+ try!(self.ser.formatter.write_u16(&mut self.ser.writer, value));
+ self.ser.formatter.end_string(&mut self.ser.writer)
}
fn serialize_u32(self, value: u32) -> Result<()> {
- self.serialize_u64(value as u64)
+ try!(self.ser.formatter.begin_string(&mut self.ser.writer));
+ try!(self.ser.formatter.write_u32(&mut self.ser.writer, value));
+ self.ser.formatter.end_string(&mut self.ser.writer)
}
fn serialize_u64(self, value: u64) -> Result<()> {
- try!(self.ser.writer.write_all(b"\""));
- try!(self.ser.serialize_u64(value));
- try!(self.ser.writer.write_all(b"\""));
- Ok(())
+ try!(self.ser.formatter.begin_string(&mut self.ser.writer));
+ try!(self.ser.formatter.write_u64(&mut self.ser.writer, value));
+ self.ser.formatter.end_string(&mut self.ser.writer)
}
fn serialize_f32(self, _value: f32) -> Result<()> {
@@ -811,38 +845,282 @@ impl ser::SerializeStructVariant for Impossible {
}
}
+/// Represents a character escape code in a type-safe manner.
+pub enum CharEscape {
+ /// An escaped quote `"`
+ Quote,
+ /// An escaped reverse solidus `\`
+ ReverseSolidus,
+ /// An escaped solidus `/`
+ Solidus,
+ /// An escaped backspace character (usually escaped as `\b`)
+ Backspace,
+ /// An escaped form feed character (usually escaped as `\f`)
+ FormFeed,
+ /// An escaped line feed character (usually escaped as `\n`)
+ LineFeed,
+ /// An escaped carriage return character (usually escaped as `\r`)
+ CarriageReturn,
+ /// An escaped tab character (usually escaped as `\t`)
+ Tab,
+ /// An escaped ASCII plane control character (usually escaped as
+ /// `\u00XX` where `XX` are two hex characters)
+ AsciiControl(u8),
+}
+
+impl CharEscape {
+ #[inline]
+ fn from_escape_table(escape: u8, byte: u8) -> CharEscape {
+ match escape {
+ self::BB => CharEscape::Backspace,
+ self::TT => CharEscape::Tab,
+ self::NN => CharEscape::LineFeed,
+ self::FF => CharEscape::FormFeed,
+ self::RR => CharEscape::CarriageReturn,
+ self::QU => CharEscape::Quote,
+ self::BS => CharEscape::ReverseSolidus,
+ self::U => CharEscape::AsciiControl(byte),
+ _ => unreachable!(),
+ }
+ }
+}
+
/// This trait abstracts away serializing the JSON control characters, which allows the user to
/// optionally pretty print the JSON output.
pub trait Formatter {
- /// Called when serializing a '{' or '['.
- fn open<W>(&mut self, writer: &mut W, ch: u8) -> Result<()>
- where W: io::Write;
+ /// Writes a `null` value to the specified writer.
+ #[inline]
+ fn write_null<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ writer.write_all(b"null").map_err(From::from)
+ }
+
+ /// Writes a `true` or `false` value to the specified writer.
+ #[inline]
+ fn write_bool<W>(&mut self, writer: &mut W, value: bool) -> Result<()>
+ where W: io::Write
+ {
+ let s = if value {
+ b"true" as &[u8]
+ } else {
+ b"false" as &[u8]
+ };
+ writer.write_all(s).map_err(From::from)
+ }
+
+ /// Writes an integer value like `-123` to the specified writer.
+ #[inline]
+ fn write_isize<W>(&mut self, writer: &mut W, value: isize) -> Result<()>
+ where W: io::Write
+ {
+ itoa::write(writer, value).map_err(From::from)
+ }
- /// Called when serializing a ','.
- fn comma<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
- where W: io::Write;
+ /// Writes an integer value like `-123` to the specified writer.
+ #[inline]
+ fn write_i8<W>(&mut self, writer: &mut W, value: i8) -> Result<()>
+ where W: io::Write
+ {
+ itoa::write(writer, value).map_err(From::from)
+ }
- /// Called when serializing a ':'.
- fn colon<W>(&mut self, writer: &mut W) -> Result<()> where W: io::Write;
+ /// Writes an integer value like `-123` to the specified writer.
+ #[inline]
+ fn write_i16<W>(&mut self, writer: &mut W, value: i16) -> Result<()>
+ where W: io::Write
+ {
+ itoa::write(writer, value).map_err(From::from)
+ }
- /// Called when serializing a '}' or ']'.
- fn close<W>(&mut self, writer: &mut W, ch: u8) -> Result<()>
- where W: io::Write;
-}
+ /// Writes an integer value like `-123` to the specified writer.
+ #[inline]
+ fn write_i32<W>(&mut self, writer: &mut W, value: i32) -> Result<()>
+ where W: io::Write
+ {
+ itoa::write(writer, value).map_err(From::from)
+ }
-/// This structure compacts a JSON value with no extra whitespace.
-#[derive(Clone, Debug)]
-pub struct CompactFormatter;
+ /// Writes an integer value like `-123` to the specified writer.
+ #[inline]
+ fn write_i64<W>(&mut self, writer: &mut W, value: i64) -> Result<()>
+ where W: io::Write
+ {
+ itoa::write(writer, value).map_err(From::from)
+ }
+
+ /// Writes an integer value like `123` to the specified writer.
+ #[inline]
+ fn write_usize<W>(&mut self, writer: &mut W, value: usize) -> Result<()>
+ where W: io::Write
+ {
+ itoa::write(writer, value).map_err(From::from)
+ }
+
+ /// Writes an integer value like `123` to the specified writer.
+ #[inline]
+ fn write_u8<W>(&mut self, writer: &mut W, value: u8) -> Result<()>
+ where W: io::Write
+ {
+ itoa::write(writer, value).map_err(From::from)
+ }
+
+ /// Writes an integer value like `123` to the specified writer.
+ #[inline]
+ fn write_u16<W>(&mut self, writer: &mut W, value: u16) -> Result<()>
+ where W: io::Write
+ {
+ itoa::write(writer, value).map_err(From::from)
+ }
+
+ /// Writes an integer value like `123` to the specified writer.
+ #[inline]
+ fn write_u32<W>(&mut self, writer: &mut W, value: u32) -> Result<()>
+ where W: io::Write
+ {
+ itoa::write(writer, value).map_err(From::from)
+ }
+
+ /// Writes an integer value like `123` to the specified writer.
+ #[inline]
+ fn write_u64<W>(&mut self, writer: &mut W, value: u64) -> Result<()>
+ where W: io::Write
+ {
+ itoa::write(writer, value).map_err(From::from)
+ }
+
+ /// Writes a floating point value like `-31.26e+12` to the specified writer.
+ #[inline]
+ fn write_f32<W>(&mut self, writer: &mut W, value: f32) -> Result<()>
+ where W: io::Write
+ {
+ dtoa::write(writer, value).map_err(From::from)
+ }
+
+ /// Writes a floating point value like `-31.26e+12` to the specified writer.
+ #[inline]
+ fn write_f64<W>(&mut self, writer: &mut W, value: f64) -> Result<()>
+ where W: io::Write
+ {
+ dtoa::write(writer, value).map_err(From::from)
+ }
+
+ /// Called before each series of `write_string_fragment` and
+ /// `write_char_escape`. Writes a `"` to the specified writer.
+ #[inline]
+ fn begin_string<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ writer.write_all(b"\"").map_err(From::from)
+ }
+
+ /// Called after each series of `write_string_fragment` and
+ /// `write_char_escape`. Writes a `"` to the specified writer.
+ #[inline]
+ fn end_string<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ writer.write_all(b"\"").map_err(From::from)
+ }
+
+ /// Writes a string fragment that doesn't need any escaping to the
+ /// specified writer.
+ #[inline]
+ fn write_string_fragment<W>(&mut self, writer: &mut W, fragment: &[u8]) -> Result<()>
+ where W: io::Write
+ {
+ writer.write_all(fragment).map_err(From::from)
+ }
+
+ /// Writes a character escape code to the specified writer.
+ #[inline]
+ fn write_char_escape<W>(&mut self, writer: &mut W, char_escape: CharEscape) -> Result<()>
+ where W: io::Write
+ {
+ use self::CharEscape::*;
+
+ let s = match char_escape {
+ Quote => b"\\\"",
+ ReverseSolidus => b"\\\\",
+ Solidus => b"\\/",
+ Backspace => b"\\b",
+ FormFeed => b"\\f",
+ LineFeed => b"\\n",
+ CarriageReturn => b"\\r",
+ Tab => b"\\t",
+ AsciiControl(byte) => {
+ static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";
+ let bytes = &[b'\\', b'u', b'0', b'0',
+ HEX_DIGITS[(byte >> 4) as usize],
+ HEX_DIGITS[(byte & 0xF) as usize]];
+ return writer.write_all(bytes).map_err(From::from);
+ }
+ };
+
+ writer.write_all(s).map_err(From::from)
+ }
+
+ /// Called before every array. Writes a `[` to the specified
+ /// writer.
+ #[inline]
+ fn begin_array<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ writer.write_all(b"[").map_err(From::from)
+ }
+
+ /// Called after every array. Writes a `]` to the specified
+ /// writer.
+ #[inline]
+ fn end_array<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ writer.write_all(b"]").map_err(From::from)
+ }
+
+ /// Called before every array value. Writes a `,` if needed to
+ /// the specified writer.
+ #[inline]
+ fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
+ where W: io::Write
+ {
+ if first {
+ Ok(())
+ } else {
+ writer.write_all(b",").map_err(From::from)
+ }
+ }
+
+ /// Called after every array value.
+ #[inline]
+ fn end_array_value<W>(&mut self, _writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ Ok(())
+ }
+
+ /// Called before every object. Writes a `{` to the specified
+ /// writer.
+ #[inline]
+ fn begin_object<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ writer.write_all(b"{").map_err(From::from)
+ }
-impl Formatter for CompactFormatter {
- fn open<W>(&mut self, writer: &mut W, ch: u8) -> Result<()>
- where W: io::Write,
+ /// Called after every object. Writes a `}` to the specified
+ /// writer.
+ #[inline]
+ fn end_object<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
{
- writer.write_all(&[ch]).map_err(From::from)
+ writer.write_all(b"}").map_err(From::from)
}
- fn comma<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
- where W: io::Write,
+ /// Called before every object key.
+ #[inline]
+ fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
+ where W: io::Write
{
if first {
Ok(())
@@ -851,23 +1129,46 @@ impl Formatter for CompactFormatter {
}
}
- fn colon<W>(&mut self, writer: &mut W) -> Result<()>
- where W: io::Write,
+ /// Called after every object key. A `:` should be written to the
+ /// specified writer by either this method or
+ /// `begin_object_value`.
+ #[inline]
+ fn end_object_key<W>(&mut self, _writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ Ok(())
+ }
+
+ /// Called before every object value. A `:` should be written to
+ /// the specified writer by either this method or
+ /// `end_object_key`.
+ #[inline]
+ fn begin_object_value<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
{
writer.write_all(b":").map_err(From::from)
}
- fn close<W>(&mut self, writer: &mut W, ch: u8) -> Result<()>
- where W: io::Write,
+ /// Called after every object value.
+ #[inline]
+ fn end_object_value<W>(&mut self, _writer: &mut W) -> Result<()>
+ where W: io::Write
{
- writer.write_all(&[ch]).map_err(From::from)
+ Ok(())
}
}
+/// This structure compacts a JSON value with no extra whitespace.
+#[derive(Clone, Debug)]
+pub struct CompactFormatter;
+
+impl Formatter for CompactFormatter {}
+
/// This structure pretty prints a JSON value to make it human readable.
#[derive(Clone, Debug)]
pub struct PrettyFormatter<'a> {
current_indent: usize,
+ has_value: bool,
indent: &'a [u8],
}
@@ -881,6 +1182,7 @@ impl<'a> PrettyFormatter<'a> {
pub fn with_indent(indent: &'a [u8]) -> Self {
PrettyFormatter {
current_indent: 0,
+ has_value: false,
indent: indent,
}
}
@@ -893,49 +1195,115 @@ impl<'a> Default for PrettyFormatter<'a> {
}
impl<'a> Formatter for PrettyFormatter<'a> {
- fn open<W>(&mut self, writer: &mut W, ch: u8) -> Result<()>
- where W: io::Write,
+ #[inline]
+ fn begin_array<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
{
self.current_indent += 1;
- writer.write_all(&[ch]).map_err(From::from)
+ self.has_value = false;
+ writer.write_all(b"[").map_err(From::from)
+ }
+
+ #[inline]
+ fn end_array<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ self.current_indent -= 1;
+
+ if self.has_value {
+ try!(writer.write_all(b"\n"));
+ try!(indent(writer, self.current_indent, self.indent));
+ }
+
+ writer.write_all(b"]").map_err(From::from)
}
- fn comma<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
- where W: io::Write,
+ #[inline]
+ fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
+ where W: io::Write
{
if first {
try!(writer.write_all(b"\n"));
} else {
try!(writer.write_all(b",\n"));
}
+ try!(indent(writer, self.current_indent, self.indent));
+ Ok(())
+ }
- indent(writer, self.current_indent, self.indent)
+ #[inline]
+ fn end_array_value<W>(&mut self, _writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ self.has_value = true;
+ Ok(())
}
- fn colon<W>(&mut self, writer: &mut W) -> Result<()>
- where W: io::Write,
+ #[inline]
+ fn begin_object<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
{
- writer.write_all(b": ").map_err(From::from)
+ self.current_indent += 1;
+ self.has_value = false;
+ writer.write_all(b"{").map_err(From::from)
}
- fn close<W>(&mut self, writer: &mut W, ch: u8) -> Result<()>
- where W: io::Write,
+ #[inline]
+ fn end_object<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
{
self.current_indent -= 1;
- try!(writer.write_all(b"\n"));
- try!(indent(writer, self.current_indent, self.indent));
- writer.write_all(&[ch]).map_err(From::from)
+ if self.has_value {
+ try!(writer.write_all(b"\n"));
+ try!(indent(writer, self.current_indent, self.indent));
+ }
+
+ writer.write_all(b"}").map_err(From::from)
+ }
+
+ #[inline]
+ fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
+ where W: io::Write
+ {
+ if first {
+ try!(writer.write_all(b"\n"));
+ } else {
+ try!(writer.write_all(b",\n"));
+ }
+ indent(writer, self.current_indent, self.indent)
+ }
+
+ #[inline]
+ fn begin_object_value<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ writer.write_all(b": ").map_err(From::from)
+ }
+
+ #[inline]
+ fn end_object_value<W>(&mut self, _writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ self.has_value = true;
+ Ok(())
}
}
/// Serializes and escapes a `&str` into a JSON string.
pub fn escape_str<W>(wr: &mut W, value: &str) -> Result<()>
+ where W: io::Write
+{
+ format_escaped_str(wr, &mut CompactFormatter, value)
+}
+
+fn format_escaped_str<W, F>(writer: &mut W, formatter: &mut F, value: &str) -> Result<()>
where W: io::Write,
+ F: Formatter
{
let bytes = value.as_bytes();
- try!(wr.write_all(b"\""));
+ try!(formatter.begin_string(writer));
let mut start = 0;
@@ -946,29 +1314,20 @@ pub fn escape_str<W>(wr: &mut W, value: &str) -> Result<()>
}
if start < i {
- try!(wr.write_all(&bytes[start..i]));
+ try!(formatter.write_string_fragment(writer, &bytes[start..i]));
}
- if escape == b'u' {
- static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";
- try!(wr.write_all(&[b'\\',
- b'u',
- b'0',
- b'0',
- HEX_DIGITS[(byte >> 4) as usize],
- HEX_DIGITS[(byte & 0xF) as usize]]));
- } else {
- try!(wr.write_all(&[b'\\', escape]));
- }
+ let char_escape = CharEscape::from_escape_table(escape, byte);
+ try!(formatter.write_char_escape(writer, char_escape));
start = i + 1;
}
if start != bytes.len() {
- try!(wr.write_all(&bytes[start..]));
+ try!(formatter.write_string_fragment(writer, &bytes[start..]));
}
- try!(wr.write_all(b"\""));
+ try!(formatter.end_string(writer));
Ok(())
}
@@ -1005,36 +1364,15 @@ static ESCAPE: [u8; 256] = [
];
#[inline]
-fn escape_char<W>(wr: &mut W, value: char) -> Result<()>
+fn format_escaped_char<W, F>(wr: &mut W, formatter: &mut F, value: char) -> Result<()>
where W: io::Write,
+ F: Formatter,
{
// FIXME: this allocation is required in order to be compatible with stable
// rust, which doesn't support encoding a `char` into a stack buffer.
let mut s = String::new();
s.push(value);
- escape_str(wr, &s)
-}
-
-fn fmt_f32_or_null<W>(wr: &mut W, value: f32) -> Result<()>
- where W: io::Write,
-{
- match value.classify() {
- FpCategory::Nan | FpCategory::Infinite => try!(wr.write_all(b"null")),
- _ => try!(dtoa::write(wr, value)),
- }
-
- Ok(())
-}
-
-fn fmt_f64_or_null<W>(wr: &mut W, value: f64) -> Result<()>
- where W: io::Write,
-{
- match value.classify() {
- FpCategory::Nan | FpCategory::Infinite => try!(wr.write_all(b"null")),
- _ => try!(dtoa::write(wr, value)),
- }
-
- Ok(())
+ format_escaped_str(wr, formatter, &s)
}
/// Encode the specified struct into a json `[u8]` writer.
|
diff --git a/json_tests/tests/test_json.rs b/json_tests/tests/test_json.rs
index 0d4f6ac8c..982fcea07 100644
--- a/json_tests/tests/test_json.rs
+++ b/json_tests/tests/test_json.rs
@@ -1374,10 +1374,8 @@ fn test_serialize_seq_with_no_len() {
let s = serde_json::to_string_pretty(&vec).unwrap();
let expected = indoc!("
[
- [
- ],
- [
- ]
+ [],
+ []
]");
assert_eq!(s, expected);
}
@@ -1462,10 +1460,8 @@ fn test_serialize_map_with_no_len() {
let s = serde_json::to_string_pretty(&map).unwrap();
let expected = indoc!(r#"
{
- "a": {
- },
- "b": {
- }
+ "a": {},
+ "b": {}
}"#);
assert_eq!(s, expected);
}
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
|
null |
serde-rs__json-192
| 192
|
[
"189"
] |
2017-01-16T03:16:27Z
|
7550d401830b99791da4a2db36c7b1eec6cf5859
|
Remove Value::lookup
This method is deprecated in favor of Value::pointer and pointer syntax.
|
diff --git a/json/src/value.rs b/json/src/value.rs
index 3f28019e0..1400b9c1d 100644
--- a/json/src/value.rs
+++ b/json/src/value.rs
@@ -126,32 +126,6 @@ impl Value {
Some(target)
}
- /// **Deprecated**: Use `Value.pointer()` and pointer syntax instead.
- ///
- /// Looks up a value by path.
- ///
- /// This is a convenience method that splits the path by `'.'`
- /// and then feeds the sequence of keys into the `find_path`
- /// method.
- ///
- /// ``` ignore
- /// let obj: Value = json::from_str(r#"{"x": {"a": 1}}"#).unwrap();
- ///
- /// assert!(obj.lookup("x.a").unwrap() == &Value::U64(1));
- /// ```
- pub fn lookup<'a>(&'a self, path: &str) -> Option<&'a Value> {
- let mut target = self;
- for key in path.split('.') {
- match target.find(key) {
- Some(t) => {
- target = t;
- }
- None => return None,
- }
- }
- Some(target)
- }
-
/// Looks up a value by a JSON Pointer.
///
/// JSON Pointer defines a string syntax for identifying a specific value
|
diff --git a/json_tests/tests/test_json.rs b/json_tests/tests/test_json.rs
index f95755074..d0c0b2a85 100644
--- a/json_tests/tests/test_json.rs
+++ b/json_tests/tests/test_json.rs
@@ -1280,15 +1280,6 @@ fn test_find_path() {
assert!(obj.find_path(&["z"]).is_none());
}
-#[test]
-fn test_lookup() {
- let obj: Value = serde_json::from_str(r#"{"x": {"a": 1}, "y": 2}"#).unwrap();
-
- assert!(obj.lookup("x.a").unwrap() == &Value::U64(1));
- assert!(obj.lookup("y").unwrap() == &Value::U64(2));
- assert!(obj.lookup("z").is_none());
-}
-
#[test]
fn test_serialize_seq_with_no_len() {
#[derive(Clone, Debug, PartialEq)]
@@ -1586,13 +1577,13 @@ fn test_json_stream_newlines() {
stream.as_bytes().iter().map(|byte| Ok(*byte))
);
- assert_eq!(parsed.next().unwrap().ok().unwrap().lookup("x").unwrap(),
+ assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(),
&Value::U64(39));
- assert_eq!(parsed.next().unwrap().ok().unwrap().lookup("x").unwrap(),
+ assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(),
&Value::U64(40));
- assert_eq!(parsed.next().unwrap().ok().unwrap().lookup("x").unwrap(),
+ assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(),
&Value::U64(41));
- assert_eq!(parsed.next().unwrap().ok().unwrap().lookup("x").unwrap(),
+ assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(),
&Value::U64(42));
assert!(parsed.next().is_none());
}
@@ -1604,7 +1595,7 @@ fn test_json_stream_trailing_whitespaces() {
stream.as_bytes().iter().map(|byte| Ok(*byte))
);
- assert_eq!(parsed.next().unwrap().ok().unwrap().lookup("x").unwrap(),
+ assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(),
&Value::U64(42));
assert!(parsed.next().is_none());
}
@@ -1616,7 +1607,7 @@ fn test_json_stream_truncated() {
stream.as_bytes().iter().map(|byte| Ok(*byte))
);
- assert_eq!(parsed.next().unwrap().ok().unwrap().lookup("x").unwrap(),
+ assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(),
&Value::U64(40));
assert!(parsed.next().unwrap().is_err());
assert!(parsed.next().is_none());
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
|
null |
serde-rs__json-188
| 188
|
[
"152",
"57"
] |
2017-01-15T22:29:30Z
|
We can avoid affecting types in the public API by replacing `serde_json::value::Map` (which is currently either `BTreeMap` or `LinkedHashMap`) with an opaque newtype wrapper around `BTreeMap` or `LinkedHashMap`. @oli-obk do you see a better approach?
|
016cfdbb86fc70e268db3b3c4cf707c6c44cb626
|
Feature `preserve_order` is not additive
Cargo unions all features that all rdeps in a project of a crate want, and compiles the crate with that. This requires features to be additive. Since this feature changes the types used in the public API of the crate, it is not.
Unify the number variants in Value
I am not convinced by the justification in https://github.com/serde-rs/json/issues/48#issuecomment-191194370. Instead of three `I64`, `U64`, `F64` variants I would much rather use one `Number` variant backed by an arbitrary-precision number. We can keep `as_i64`, `as_u64`, `as_f64` for convenience.
|
diff --git a/json/src/lib.rs b/json/src/lib.rs
index 83a3644f2..1e6e540f3 100644
--- a/json/src/lib.rs
+++ b/json/src/lib.rs
@@ -102,7 +102,7 @@
//!
//! for (key, value) in obj.iter() {
//! println!("{}: {}", key, match *value {
-//! Value::U64(v) => format!("{} (u64)", v),
+//! Value::Number(ref v) => format!("{} (number)", v),
//! Value::String(ref v) => format!("{} (string)", v),
//! _ => format!("other")
//! });
@@ -151,7 +151,7 @@ pub use self::de::{Deserializer, StreamDeserializer, from_iter, from_reader,
pub use self::error::{Error, ErrorCode, Result};
pub use self::ser::{Serializer, escape_str, to_string, to_string_pretty,
to_vec, to_vec_pretty, to_writer, to_writer_pretty};
-pub use self::value::{Map, Value, from_value, to_value};
+pub use self::value::{Map, Number, Value, from_value, to_value};
pub mod builder;
pub mod de;
@@ -159,4 +159,6 @@ pub mod error;
pub mod ser;
pub mod value;
+mod map;
+mod number;
mod read;
diff --git a/json/src/map.rs b/json/src/map.rs
new file mode 100644
index 000000000..e234fab2a
--- /dev/null
+++ b/json/src/map.rs
@@ -0,0 +1,335 @@
+use serde::{ser, de};
+use std::fmt::{self, Debug};
+use value::Value;
+use std::hash::Hash;
+use std::borrow::Borrow;
+
+#[cfg(not(feature = "preserve_order"))]
+use std::collections::{BTreeMap, btree_map};
+
+#[cfg(feature = "preserve_order")]
+use linked_hash_map::{self, LinkedHashMap};
+
+/// Represents a key/value type.
+pub struct Map<K, V>(MapImpl<K, V>);
+
+#[cfg(not(feature = "preserve_order"))]
+type MapImpl<K, V> = BTreeMap<K, V>;
+#[cfg(feature = "preserve_order")]
+type MapImpl<K, V> = LinkedHashMap<K, V>;
+
+impl Map<String, Value> {
+ /// Makes a new empty Map.
+ #[inline]
+ pub fn new() -> Self {
+ Map(MapImpl::new())
+ }
+
+ #[cfg(not(feature = "preserve_order"))]
+ /// Makes a new empty Map with the given initial capacity.
+ #[inline]
+ pub fn with_capacity(capacity: usize) -> Self {
+ let _ = capacity;
+ Map(BTreeMap::new()) // does not support with_capacity
+ }
+
+ #[cfg(feature = "preserve_order")]
+ /// Makes a new empty Map with the given initial capacity.
+ #[inline]
+ pub fn with_capacity(capacity: usize) -> Self {
+ Map(LinkedHashMap::with_capacity(capacity))
+ }
+
+ /// Clears the map, removing all values.
+ #[inline]
+ pub fn clear(&mut self) {
+ self.0.clear()
+ }
+
+ /// Returns a reference to the value corresponding to the key.
+ ///
+ /// The key may be any borrowed form of the map's key type, but the ordering
+ /// on the borrowed form *must* match the ordering on the key type.
+ #[inline]
+ pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&Value>
+ where String: Borrow<Q>,
+ Q: Ord + Eq + Hash
+ {
+ self.0.get(key)
+ }
+
+ /// Returns true if the map contains a value for the specified key.
+ ///
+ /// The key may be any borrowed form of the map's key type, but the ordering
+ /// on the borrowed form *must* match the ordering on the key type.
+ #[inline]
+ pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
+ where String: Borrow<Q>,
+ Q: Ord + Eq + Hash
+ {
+ self.0.contains_key(key)
+ }
+
+ /// Returns a mutable reference to the value corresponding to the key.
+ ///
+ /// The key may be any borrowed form of the map's key type, but the ordering
+ /// on the borrowed form *must* match the ordering on the key type.
+ #[inline]
+ pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut Value>
+ where String: Borrow<Q>,
+ Q: Ord + Eq + Hash
+ {
+ self.0.get_mut(key)
+ }
+
+ /// Inserts a key-value pair into the map.
+ ///
+ /// If the map did not have this key present, `None` is returned.
+ ///
+ /// If the map did have this key present, the value is updated, and the old
+ /// value is returned. The key is not updated, though; this matters for
+ /// types that can be `==` without being identical.
+ #[inline]
+ pub fn insert(&mut self, k: String, v: Value) -> Option<Value> {
+ self.0.insert(k, v)
+ }
+
+ /// Removes a key from the map, returning the value at the key if the key
+ /// was previously in the map.
+ ///
+ /// The key may be any borrowed form of the map's key type, but the ordering
+ /// on the borrowed form *must* match the ordering on the key type.
+ #[inline]
+ pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<Value>
+ where String: Borrow<Q>,
+ Q: Ord + Eq + Hash
+ {
+ self.0.remove(key)
+ }
+
+ /// Returns the number of elements in the map.
+ #[inline]
+ pub fn len(&self) -> usize {
+ self.0.len()
+ }
+
+ /// Returns true if the map contains no elements.
+ #[inline]
+ pub fn is_empty(&self) -> bool {
+ self.0.is_empty()
+ }
+
+ /// Gets an iterator over the entries of the map.
+ #[inline]
+ pub fn iter(&self) -> MapIter {
+ MapIter(self.0.iter())
+ }
+
+ /// Gets a mutable iterator over the entries of the map.
+ #[inline]
+ pub fn iter_mut(&mut self) -> MapIterMut {
+ MapIterMut(self.0.iter_mut())
+ }
+
+ /// Gets an iterator over the keys of the map.
+ #[inline]
+ pub fn keys(&self) -> MapKeys {
+ MapKeys(self.0.keys())
+ }
+
+ /// Gets an iterator over the values of the map.
+ #[inline]
+ pub fn values(&self) -> MapValues {
+ MapValues(self.0.values())
+ }
+}
+
+impl Default for Map<String, Value> {
+ #[inline]
+ fn default() -> Self {
+ Map(MapImpl::new())
+ }
+}
+
+impl Clone for Map<String, Value> {
+ #[inline]
+ fn clone(&self) -> Self {
+ Map(self.0.clone())
+ }
+}
+
+impl PartialEq for Map<String, Value> {
+ #[inline]
+ fn eq(&self, other: &Self) -> bool {
+ self.0.eq(&other.0)
+ }
+}
+
+impl Debug for Map<String, Value> {
+ #[inline]
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+ self.0.fmt(formatter)
+ }
+}
+
+impl ser::Serialize for Map<String, Value> {
+ #[inline]
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where S: ser::Serializer
+ {
+ use serde::ser::SerializeMap;
+ let mut map = try!(serializer.serialize_map(Some(self.len())));
+ for (k, v) in self {
+ try!(map.serialize_key(k));
+ try!(map.serialize_value(v));
+ }
+ map.end()
+ }
+}
+
+impl de::Deserialize for Map<String, Value> {
+ #[inline]
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where D: de::Deserializer
+ {
+ struct Visitor;
+
+ impl de::Visitor for Visitor {
+ type Value = Map<String, Value>;
+
+ #[inline]
+ fn visit_unit<E>(self) -> Result<Self::Value, E>
+ where E: de::Error
+ {
+ Ok(Map::new())
+ }
+
+ #[inline]
+ fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
+ where V: de::MapVisitor
+ {
+ let mut values = Map::with_capacity(visitor.size_hint().0);
+
+ while let Some((key, value)) = try!(visitor.visit()) {
+ values.insert(key, value);
+ }
+
+ Ok(values)
+ }
+ }
+
+ deserializer.deserialize_map(Visitor)
+ }
+}
+
+macro_rules! delegate_iterator {
+ (($name:ident $($generics:tt)*) => $item:ty) => {
+ impl $($generics)* Iterator for $name $($generics)* {
+ type Item = $item;
+ #[inline]
+ fn next(&mut self) -> Option<Self::Item> {
+ self.0.next()
+ }
+ #[inline]
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.0.size_hint()
+ }
+ }
+
+ impl $($generics)* DoubleEndedIterator for $name $($generics)* {
+ #[inline]
+ fn next_back(&mut self) -> Option<Self::Item> {
+ self.0.next_back()
+ }
+ }
+
+ impl $($generics)* ExactSizeIterator for $name $($generics)* {
+ #[inline]
+ fn len(&self) -> usize {
+ self.0.len()
+ }
+ }
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+impl<'a> IntoIterator for &'a Map<String, Value> {
+ type Item = (&'a String, &'a Value);
+ type IntoIter = MapIter<'a>;
+ #[inline]
+ fn into_iter(self) -> Self::IntoIter {
+ MapIter(self.0.iter())
+ }
+}
+
+pub struct MapIter<'a>(MapIterImpl<'a>);
+
+#[cfg(not(feature = "preserve_order"))]
+type MapIterImpl<'a> = btree_map::Iter<'a, String, Value>;
+#[cfg(feature = "preserve_order")]
+type MapIterImpl<'a> = linked_hash_map::Iter<'a, String, Value>;
+
+delegate_iterator!((MapIter<'a>) => (&'a String, &'a Value));
+
+//////////////////////////////////////////////////////////////////////////////
+
+impl<'a> IntoIterator for &'a mut Map<String, Value> {
+ type Item = (&'a String, &'a mut Value);
+ type IntoIter = MapIterMut<'a>;
+ #[inline]
+ fn into_iter(self) -> Self::IntoIter {
+ MapIterMut(self.0.iter_mut())
+ }
+}
+
+pub struct MapIterMut<'a>(MapIterMutImpl<'a>);
+
+#[cfg(not(feature = "preserve_order"))]
+type MapIterMutImpl<'a> = btree_map::IterMut<'a, String, Value>;
+#[cfg(feature = "preserve_order")]
+type MapIterMutImpl<'a> = linked_hash_map::IterMut<'a, String, Value>;
+
+delegate_iterator!((MapIterMut<'a>) => (&'a String, &'a mut Value));
+
+//////////////////////////////////////////////////////////////////////////////
+
+impl IntoIterator for Map<String, Value> {
+ type Item = (String, Value);
+ type IntoIter = MapIntoIter;
+ #[inline]
+ fn into_iter(self) -> Self::IntoIter {
+ MapIntoIter(self.0.into_iter())
+ }
+}
+
+pub struct MapIntoIter(MapIntoIterImpl);
+
+#[cfg(not(feature = "preserve_order"))]
+type MapIntoIterImpl = btree_map::IntoIter<String, Value>;
+#[cfg(feature = "preserve_order")]
+type MapIntoIterImpl = linked_hash_map::IntoIter<String, Value>;
+
+delegate_iterator!((MapIntoIter) => (String, Value));
+
+//////////////////////////////////////////////////////////////////////////////
+
+pub struct MapKeys<'a>(MapKeysImpl<'a>);
+
+#[cfg(not(feature = "preserve_order"))]
+type MapKeysImpl<'a> = btree_map::Keys<'a, String, Value>;
+#[cfg(feature = "preserve_order")]
+type MapKeysImpl<'a> = linked_hash_map::Keys<'a, String, Value>;
+
+delegate_iterator!((MapKeys<'a>) => &'a String);
+
+//////////////////////////////////////////////////////////////////////////////
+
+pub struct MapValues<'a>(MapValuesImpl<'a>);
+
+#[cfg(not(feature = "preserve_order"))]
+type MapValuesImpl<'a> = btree_map::Values<'a, String, Value>;
+#[cfg(feature = "preserve_order")]
+type MapValuesImpl<'a> = linked_hash_map::Values<'a, String, Value>;
+
+delegate_iterator!((MapValues<'a>) => &'a Value);
diff --git a/json/src/number.rs b/json/src/number.rs
new file mode 100644
index 000000000..9ee1728d0
--- /dev/null
+++ b/json/src/number.rs
@@ -0,0 +1,201 @@
+use error::Error;
+use num_traits::NumCast;
+use serde::de::{self, Visitor};
+use serde::{Serialize, Serializer, Deserialize, Deserializer};
+use std::{fmt, i64};
+
+/// Represents a JSON number, whether integer or floating point.
+#[derive(Clone, PartialEq)]
+pub struct Number(N);
+
+// "N" is a prefix of "NegInt"... this is a false positive.
+// https://github.com/Manishearth/rust-clippy/issues/1241
+#[cfg_attr(feature = "clippy", allow(enum_variant_names))]
+#[derive(Copy, Clone, Debug, PartialEq)]
+enum N {
+ PosInt(u64),
+ /// Always less than zero.
+ NegInt(i64),
+ /// Always finite.
+ Float(f64),
+}
+
+impl Number {
+ /// Returns true if the number can be represented by i64.
+ #[inline]
+ pub fn is_i64(&self) -> bool {
+ match self.0 {
+ N::PosInt(v) => v <= i64::MAX as u64,
+ N::NegInt(_) => true,
+ N::Float(_) => false,
+ }
+ }
+
+ /// Returns true if the number can be represented as u64.
+ #[inline]
+ pub fn is_u64(&self) -> bool {
+ match self.0 {
+ N::PosInt(_) => true,
+ N::NegInt(_) | N::Float(_) => false,
+ }
+ }
+
+ /// Returns true if the number can be represented as f64.
+ #[inline]
+ pub fn is_f64(&self) -> bool {
+ match self.0 {
+ N::Float(_) => true,
+ N::PosInt(_) | N::NegInt(_) => false,
+ }
+ }
+
+ /// Returns the number represented as i64 if possible, or else None.
+ #[inline]
+ pub fn as_i64(&self) -> Option<i64> {
+ match self.0 {
+ N::PosInt(n) => NumCast::from(n),
+ N::NegInt(n) => Some(n),
+ N::Float(_) => None,
+ }
+ }
+
+ /// Returns the number represented as u64 if possible, or else None.
+ #[inline]
+ pub fn as_u64(&self) -> Option<u64> {
+ match self.0 {
+ N::PosInt(n) => Some(n),
+ N::NegInt(n) => NumCast::from(n),
+ N::Float(_) => None,
+ }
+ }
+
+ /// Returns the number represented as f64 if possible, or else None.
+ #[inline]
+ pub fn as_f64(&self) -> Option<f64> {
+ match self.0 {
+ N::PosInt(n) => NumCast::from(n),
+ N::NegInt(n) => NumCast::from(n),
+ N::Float(n) => Some(n),
+ }
+ }
+
+ /// Converts a finite f64 to a Number. Infinite or NaN values are not JSON
+ /// numbers.
+ #[inline]
+ pub fn from_f64(f: f64) -> Option<Number> {
+ if f.is_finite() {
+ Some(Number(N::Float(f)))
+ } else {
+ None
+ }
+ }
+}
+
+impl fmt::Display for Number {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ match self.0 {
+ N::PosInt(i) => i.fmt(formatter),
+ N::NegInt(i) => i.fmt(formatter),
+ N::Float(f) => f.fmt(formatter),
+ }
+ }
+}
+
+impl Serialize for Number {
+ #[inline]
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where S: Serializer
+ {
+ match self.0 {
+ N::PosInt(i) => serializer.serialize_u64(i),
+ N::NegInt(i) => serializer.serialize_i64(i),
+ N::Float(f) => serializer.serialize_f64(f),
+ }
+ }
+}
+
+impl Deserialize for Number {
+ #[inline]
+ fn deserialize<D>(deserializer: D) -> Result<Number, D::Error>
+ where D: Deserializer
+ {
+ struct NumberVisitor;
+
+ impl Visitor for NumberVisitor {
+ type Value = Number;
+
+ #[inline]
+ fn visit_i64<E>(self, value: i64) -> Result<Number, E> {
+ Ok(value.into())
+ }
+
+ #[inline]
+ fn visit_u64<E>(self, value: u64) -> Result<Number, E> {
+ Ok(value.into())
+ }
+
+ #[inline]
+ fn visit_f64<E>(self, value: f64) -> Result<Number, E>
+ where E: de::Error
+ {
+ Number::from_f64(value).ok_or_else(|| de::Error::custom("not a JSON number"))
+ }
+ }
+
+ deserializer.deserialize(NumberVisitor)
+ }
+}
+
+impl Deserializer for Number {
+ type Error = Error;
+
+ #[inline]
+ fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
+ where V: Visitor
+ {
+ match self.0 {
+ N::PosInt(i) => visitor.visit_u64(i),
+ N::NegInt(i) => visitor.visit_i64(i),
+ N::Float(f) => visitor.visit_f64(f),
+ }
+ }
+
+ forward_to_deserialize! {
+ bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
+ unit option seq seq_fixed_size bytes map unit_struct newtype_struct
+ tuple_struct struct struct_field tuple enum ignored_any
+ }
+}
+
+macro_rules! from_signed {
+ ($($signed_ty:ident)*) => {
+ $(
+ impl From<$signed_ty> for Number {
+ #[inline]
+ fn from(i: $signed_ty) -> Self {
+ if i < 0 {
+ Number(N::NegInt(i as i64))
+ } else {
+ Number(N::PosInt(i as u64))
+ }
+ }
+ }
+ )*
+ };
+}
+
+macro_rules! from_unsigned {
+ ($($unsigned_ty:ident)*) => {
+ $(
+ impl From<$unsigned_ty> for Number {
+ #[inline]
+ fn from(u: $unsigned_ty) -> Self {
+ Number(N::PosInt(u as u64))
+ }
+ }
+ )*
+ };
+}
+
+from_signed!(i8 i16 i32 i64 isize);
+from_unsigned!(u8 u16 u32 u64 usize);
diff --git a/json/src/value.rs b/json/src/value.rs
index e64d807c3..14d35a380 100644
--- a/json/src/value.rs
+++ b/json/src/value.rs
@@ -24,72 +24,48 @@
//!
//! fn main() {
//! let mut map = Map::new();
-//! map.insert(String::from("x"), Value::F64(1.0));
-//! map.insert(String::from("y"), Value::F64(2.0));
+//! map.insert(String::from("x"), 1.0.into());
+//! map.insert(String::from("y"), 2.0.into());
//! let value = Value::Object(map);
//!
-//! let map: Map<String, f64> = serde_json::from_value(value).unwrap();
+//! let map: Map<String, Value> = serde_json::from_value(value).unwrap();
//! }
//! ```
-#[cfg(not(feature = "preserve_order"))]
-use std::collections::{BTreeMap, btree_map};
-
-#[cfg(feature = "preserve_order")]
-use linked_hash_map::{self, LinkedHashMap};
-
use std::fmt;
+use std::i64;
use std::io;
use std::str;
use std::vec;
-use num_traits::NumCast;
-
use serde::de;
use serde::ser;
use serde::de::value::ValueDeserializer;
use error::{Error, ErrorCode};
-/// Represents a key/value type.
-#[cfg(not(feature = "preserve_order"))]
-pub type Map<K, V> = BTreeMap<K, V>;
-/// Represents a key/value type.
-#[cfg(feature = "preserve_order")]
-pub type Map<K, V> = LinkedHashMap<K, V>;
-
-/// Represents the `IntoIter` type.
-#[cfg(not(feature = "preserve_order"))]
-pub type MapIntoIter<K, V> = btree_map::IntoIter<K, V>;
-/// Represents the IntoIter type.
-#[cfg(feature = "preserve_order")]
-pub type MapIntoIter<K, V> = linked_hash_map::IntoIter<K, V>;
-
-/// Represents a JSON value
+pub use map::Map;
+pub use number::Number;
+
+/// Represents any valid JSON value.
#[derive(Clone, PartialEq)]
pub enum Value {
- /// Represents a JSON null value
+ /// Represents a JSON null value.
Null,
- /// Represents a JSON Boolean
+ /// Represents a JSON boolean.
Bool(bool),
- /// Represents a JSON signed integer
- I64(i64),
+ /// Represents a JSON number, whether integer or floating point.
+ Number(Number),
- /// Represents a JSON unsigned integer
- U64(u64),
-
- /// Represents a JSON floating point number
- F64(f64),
-
- /// Represents a JSON string
+ /// Represents a JSON string.
String(String),
- /// Represents a JSON array
+ /// Represents a JSON array.
Array(Vec<Value>),
- /// Represents a JSON object
+ /// Represents a JSON object.
Object(Map<String, Value>),
}
@@ -188,15 +164,15 @@ impl Value {
/// let mut value: Value = serde_json::from_str(s).unwrap();
///
/// // Check value using read-only pointer
- /// assert_eq!(value.pointer("/x"), Some(&Value::F64(1.0)));
+ /// assert_eq!(value.pointer("/x"), Some(&1.0.into()));
/// // Change value with direct assignment
- /// *value.pointer_mut("/x").unwrap() = Value::F64(1.5);
+ /// *value.pointer_mut("/x").unwrap() = 1.5.into();
/// // Check that new value was written
- /// assert_eq!(value.pointer("/x"), Some(&Value::F64(1.5)));
+ /// assert_eq!(value.pointer("/x"), Some(&1.5.into()));
///
/// // "Steal" ownership of a value. Can replace with any valid Value.
/// let old_x = value.pointer_mut("/x").map(|x| mem::replace(x, Value::Null)).unwrap();
- /// assert_eq!(old_x, Value::F64(1.5));
+ /// assert_eq!(old_x, 1.5.into());
/// assert_eq!(value.pointer("/x").unwrap(), &Value::Null);
/// }
/// ```
@@ -314,62 +290,58 @@ impl Value {
/// Returns true if the `Value` is a Number. Returns false otherwise.
pub fn is_number(&self) -> bool {
match *self {
- Value::I64(_) | Value::U64(_) | Value::F64(_) => true,
+ Value::Number(_) => true,
_ => false,
}
}
- /// Returns true if the `Value` is a i64. Returns false otherwise.
+ /// Returns true if the `Value` is a number that can be represented by i64.
pub fn is_i64(&self) -> bool {
match *self {
- Value::I64(_) => true,
+ Value::Number(ref n) => n.is_i64(),
_ => false,
}
}
- /// Returns true if the `Value` is a u64. Returns false otherwise.
+ /// Returns true if the `Value` is a number that can be represented by u64.
pub fn is_u64(&self) -> bool {
match *self {
- Value::U64(_) => true,
+ Value::Number(ref n) => n.is_u64(),
_ => false,
}
}
- /// Returns true if the `Value` is a f64. Returns false otherwise.
+ /// Returns true if the `Value` is a number that can be represented by f64.
pub fn is_f64(&self) -> bool {
match *self {
- Value::F64(_) => true,
+ Value::Number(ref n) => n.is_f64(),
_ => false,
}
}
- /// If the `Value` is a number, return or cast it to a i64.
+ /// If the `Value` is a number, represent it as i64 if possible.
/// Returns None otherwise.
pub fn as_i64(&self) -> Option<i64> {
match *self {
- Value::I64(n) => Some(n),
- Value::U64(n) => NumCast::from(n),
+ Value::Number(ref n) => n.as_i64(),
_ => None,
}
}
- /// If the `Value` is a number, return or cast it to a u64.
+ /// If the `Value` is a number, represent it as u64 if possible.
/// Returns None otherwise.
pub fn as_u64(&self) -> Option<u64> {
match *self {
- Value::I64(n) => NumCast::from(n),
- Value::U64(n) => Some(n),
+ Value::Number(ref n) => n.as_u64(),
_ => None,
}
}
- /// If the `Value` is a number, return or cast it to a f64.
+ /// If the `Value` is a number, represent it as f64 if possible.
/// Returns None otherwise.
pub fn as_f64(&self) -> Option<f64> {
match *self {
- Value::I64(n) => NumCast::from(n),
- Value::U64(n) => NumCast::from(n),
- Value::F64(n) => Some(n),
+ Value::Number(ref n) => n.as_f64(),
_ => None,
}
}
@@ -403,6 +375,35 @@ impl Value {
}
}
+macro_rules! from_integer {
+ ($($ty:ident)*) => {
+ $(
+ impl From<$ty> for Value {
+ fn from(n: $ty) -> Self {
+ Value::Number(n.into())
+ }
+ }
+ )*
+ };
+}
+
+from_integer! {
+ i8 i16 i32 i64 isize
+ u8 u16 u32 u64 usize
+}
+
+impl From<f32> for Value {
+ fn from(f: f32) -> Self {
+ From::from(f as f64)
+ }
+}
+
+impl From<f64> for Value {
+ fn from(f: f64) -> Self {
+ Number::from_f64(f).map_or(Value::Null, Value::Number)
+ }
+}
+
impl ser::Serialize for Value {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
@@ -411,9 +412,7 @@ impl ser::Serialize for Value {
match *self {
Value::Null => serializer.serialize_unit(),
Value::Bool(b) => serializer.serialize_bool(b),
- Value::I64(i) => serializer.serialize_i64(i),
- Value::U64(u) => serializer.serialize_u64(u),
- Value::F64(f) => serializer.serialize_f64(f),
+ Value::Number(ref n) => n.serialize(serializer),
Value::String(ref s) => serializer.serialize_str(s),
Value::Array(ref v) => v.serialize(serializer),
Value::Object(ref m) => {
@@ -446,21 +445,17 @@ impl de::Deserialize for Value {
#[inline]
fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
- if value < 0 {
- Ok(Value::I64(value))
- } else {
- Ok(Value::U64(value as u64))
- }
+ Ok(Value::Number(value.into()))
}
#[inline]
fn visit_u64<E>(self, value: u64) -> Result<Value, E> {
- Ok(Value::U64(value))
+ Ok(Value::Number(value.into()))
}
#[inline]
fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
- Ok(Value::F64(value))
+ Ok(Number::from_f64(value).map_or(Value::Null, Value::Number))
}
#[inline]
@@ -507,20 +502,7 @@ impl de::Deserialize for Value {
fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error>
where V: de::MapVisitor,
{
- // Work around not having attributes on statements in Rust 1.12.0
- #[cfg(not(feature = "preserve_order"))]
- macro_rules! init {
- () => {
- BTreeMap::new()
- };
- }
- #[cfg(feature = "preserve_order")]
- macro_rules! init {
- () => {
- LinkedHashMap::with_capacity(visitor.size_hint().0)
- };
- }
- let mut values = init!();
+ let mut values = Map::with_capacity(visitor.size_hint().0);
while let Some((key, value)) = try!(visitor.visit()) {
values.insert(key, value);
@@ -622,11 +604,7 @@ impl ser::Serializer for Serializer {
}
fn serialize_i64(self, value: i64) -> Result<Value, Error> {
- Ok(if value < 0 {
- Value::I64(value)
- } else {
- Value::U64(value as u64)
- })
+ Ok(Value::Number(value.into()))
}
#[inline]
@@ -651,7 +629,7 @@ impl ser::Serializer for Serializer {
#[inline]
fn serialize_u64(self, value: u64) -> Result<Value, Error> {
- Ok(Value::U64(value))
+ Ok(Value::Number(value.into()))
}
#[inline]
@@ -661,11 +639,7 @@ impl ser::Serializer for Serializer {
#[inline]
fn serialize_f64(self, value: f64) -> Result<Value, Error> {
- Ok(if value.is_finite() {
- Value::F64(value)
- } else {
- Value::Null
- })
+ Ok(Number::from_f64(value).map_or(Value::Null, Value::Number))
}
#[inline]
@@ -681,7 +655,7 @@ impl ser::Serializer for Serializer {
}
fn serialize_bytes(self, value: &[u8]) -> Result<Value, Error> {
- let vec = value.iter().map(|b| Value::U64(*b as u64)).collect();
+ let vec = value.iter().map(|&b| Value::Number(b.into())).collect();
Ok(Value::Array(vec))
}
@@ -986,9 +960,7 @@ impl de::Deserializer for Value {
match self {
Value::Null => visitor.visit_unit(),
Value::Bool(v) => visitor.visit_bool(v),
- Value::I64(v) => visitor.visit_i64(v),
- Value::U64(v) => visitor.visit_u64(v),
- Value::F64(v) => visitor.visit_f64(v),
+ Value::Number(n) => n.deserialize(visitor),
Value::String(v) => visitor.visit_string(v),
Value::Array(v) => {
let mut deserializer = SeqDeserializer::new(v);
@@ -1209,7 +1181,7 @@ impl de::SeqVisitor for SeqDeserializer {
}
struct MapDeserializer {
- iter: MapIntoIter<String, Value>,
+ iter: <Map<String, Value> as IntoIterator>::IntoIter,
value: Option<Value>,
}
|
diff --git a/json_tests/tests/test_json.rs b/json_tests/tests/test_json.rs
index 442e03ede..783d8365a 100644
--- a/json_tests/tests/test_json.rs
+++ b/json_tests/tests/test_json.rs
@@ -1,3 +1,4 @@
+use std::collections::BTreeMap;
use std::f64;
use std::fmt::Debug;
use std::i64;
@@ -24,13 +25,30 @@ use serde_json::{
use serde_json::error::{Error, ErrorCode};
macro_rules! treemap {
+ () => {
+ BTreeMap::new()
+ };
+ ($($k:expr => $v:expr),+) => {
+ {
+ let mut m = BTreeMap::new();
+ $(
+ m.insert($k, $v);
+ )+
+ m
+ }
+ };
+}
+
+macro_rules! jsonmap {
() => {
Map::new()
};
($($k:expr => $v:expr),+) => {
{
let mut m = Map::new();
- $(m.insert($k, $v);)+
+ $(
+ m.insert($k, to_value(&$v).unwrap());
+ )+
m
}
};
@@ -262,7 +280,7 @@ fn test_write_list() {
let long_test_list = Value::Array(vec![
Value::Bool(false),
Value::Null,
- Value::Array(vec![Value::String("foo\nbar".to_string()), Value::F64(3.5)])]);
+ Value::Array(vec![Value::String("foo\nbar".to_string()), 3.5.into()])]);
test_encode_ok(&[
(
@@ -473,11 +491,11 @@ fn test_write_object() {
),
]);
- let complex_obj = Value::Object(treemap!(
- "b".to_string() => Value::Array(vec![
- Value::Object(treemap!("c".to_string() => Value::String("\x0c\x1f\r".to_string()))),
- Value::Object(treemap!("d".to_string() => Value::String("".to_string())))
- ])
+ let complex_obj = Value::Object(jsonmap!(
+ "b".to_string() => vec![
+ Value::Object(jsonmap!("c".to_string() => "\x0c\x1f\r".to_string())),
+ Value::Object(jsonmap!("d".to_string() => "".to_string()))
+ ]
));
test_encode_ok(&[
@@ -663,7 +681,7 @@ fn test_write_option() {
#[test]
fn test_write_newtype_struct() {
#[derive(Serialize, PartialEq, Debug)]
- struct Newtype(Map<String, i32>);
+ struct Newtype(BTreeMap<String, i32>);
let inner = Newtype(treemap!(String::from("inner") => 123));
let outer = treemap!(String::from("outer") => to_value(&inner).unwrap());
@@ -1006,7 +1024,7 @@ fn test_parse_list() {
#[test]
fn test_parse_object() {
- test_parse_err::<Map<String, u32>>(vec![
+ test_parse_err::<BTreeMap<String, u32>>(vec![
("{", Error::Syntax(ErrorCode::EOFWhileParsingObject, 1, 1)),
("{ ", Error::Syntax(ErrorCode::EOFWhileParsingObject, 1, 2)),
("{1", Error::Syntax(ErrorCode::KeyMustBeAString, 1, 2)),
@@ -1209,7 +1227,7 @@ fn test_parse_trailing_whitespace() {
#[test]
fn test_multiline_errors() {
- test_parse_err::<Map<String, String>>(vec![
+ test_parse_err::<BTreeMap<String, String>>(vec![
("{\n \"foo\":\n \"bar\"", Error::Syntax(ErrorCode::EOFWhileParsingObject, 3, 6)),
]);
}
@@ -1227,11 +1245,11 @@ fn test_missing_option_field() {
let value: Foo = from_str("{\"x\": 5}").unwrap();
assert_eq!(value, Foo { x: Some(5) });
- let value: Foo = from_value(Value::Object(treemap!())).unwrap();
+ let value: Foo = from_value(Value::Object(jsonmap!())).unwrap();
assert_eq!(value, Foo { x: None });
- let value: Foo = from_value(Value::Object(treemap!(
- "x".to_string() => Value::I64(5)
+ let value: Foo = from_value(Value::Object(jsonmap!(
+ "x".to_string() => 5
))).unwrap();
assert_eq!(value, Foo { x: Some(5) });
}
@@ -1262,11 +1280,11 @@ fn test_missing_renamed_field() {
let value: Foo = from_str("{\"y\": 5}").unwrap();
assert_eq!(value, Foo { x: Some(5) });
- let value: Foo = from_value(Value::Object(treemap!())).unwrap();
+ let value: Foo = from_value(Value::Object(jsonmap!())).unwrap();
assert_eq!(value, Foo { x: None });
- let value: Foo = from_value(Value::Object(treemap!(
- "y".to_string() => Value::I64(5)
+ let value: Foo = from_value(Value::Object(jsonmap!(
+ "y".to_string() => 5
))).unwrap();
assert_eq!(value, Foo { x: Some(5) });
}
@@ -1275,8 +1293,8 @@ fn test_missing_renamed_field() {
fn test_find_path() {
let obj: Value = serde_json::from_str(r#"{"x": {"a": 1}, "y": 2}"#).unwrap();
- assert!(obj.find_path(&["x", "a"]).unwrap() == &Value::U64(1));
- assert!(obj.find_path(&["y"]).unwrap() == &Value::U64(2));
+ assert!(obj.find_path(&["x", "a"]).unwrap() == &1.into());
+ assert!(obj.find_path(&["y"]).unwrap() == &2.into());
assert!(obj.find_path(&["z"]).is_none());
}
@@ -1367,7 +1385,7 @@ fn test_serialize_seq_with_no_len() {
#[test]
fn test_serialize_map_with_no_len() {
#[derive(Clone, Debug, PartialEq)]
- struct MyMap<K, V>(Map<K, V>);
+ struct MyMap<K, V>(BTreeMap<K, V>);
impl<K, V> ser::Serialize for MyMap<K, V>
where K: ser::Serialize + Ord,
@@ -1401,14 +1419,14 @@ fn test_serialize_map_with_no_len() {
fn visit_unit<E>(self) -> Result<MyMap<K, V>, E>
where E: de::Error,
{
- Ok(MyMap(Map::new()))
+ Ok(MyMap(BTreeMap::new()))
}
#[inline]
fn visit_map<Visitor>(self, mut visitor: Visitor) -> Result<MyMap<K, V>, Visitor::Error>
where Visitor: de::MapVisitor,
{
- let mut values = Map::new();
+ let mut values = BTreeMap::new();
while let Some((key, value)) = try!(visitor.visit()) {
values.insert(key, value);
@@ -1429,9 +1447,9 @@ fn test_serialize_map_with_no_len() {
}
}
- let mut map = Map::new();
- map.insert("a", MyMap(Map::new()));
- map.insert("b", MyMap(Map::new()));
+ let mut map = BTreeMap::new();
+ map.insert("a", MyMap(BTreeMap::new()));
+ map.insert("b", MyMap(BTreeMap::new()));
let map: MyMap<_, MyMap<u32, u32>> = MyMap(map);
test_encode_ok(&[
@@ -1578,13 +1596,13 @@ fn test_json_stream_newlines() {
);
assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(),
- &Value::U64(39));
+ &39.into());
assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(),
- &Value::U64(40));
+ &40.into());
assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(),
- &Value::U64(41));
+ &41.into());
assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(),
- &Value::U64(42));
+ &42.into());
assert!(parsed.next().is_none());
}
@@ -1596,7 +1614,7 @@ fn test_json_stream_trailing_whitespaces() {
);
assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(),
- &Value::U64(42));
+ &42.into());
assert!(parsed.next().is_none());
}
@@ -1608,7 +1626,7 @@ fn test_json_stream_truncated() {
);
assert_eq!(parsed.next().unwrap().ok().unwrap().pointer("/x").unwrap(),
- &Value::U64(40));
+ &40.into());
assert!(parsed.next().unwrap().is_err());
assert!(parsed.next().is_none());
}
@@ -1644,15 +1662,15 @@ fn test_json_pointer() {
Value::String("baz".to_owned())]));
assert_eq!(data.pointer("/foo/0").unwrap(),
&Value::String("bar".to_owned()));
- assert_eq!(data.pointer("/").unwrap(), &Value::U64(0));
- assert_eq!(data.pointer("/a~1b").unwrap(), &Value::U64(1));
- assert_eq!(data.pointer("/c%d").unwrap(), &Value::U64(2));
- assert_eq!(data.pointer("/e^f").unwrap(), &Value::U64(3));
- assert_eq!(data.pointer("/g|h").unwrap(), &Value::U64(4));
- assert_eq!(data.pointer("/i\\j").unwrap(), &Value::U64(5));
- assert_eq!(data.pointer("/k\"l").unwrap(), &Value::U64(6));
- assert_eq!(data.pointer("/ ").unwrap(), &Value::U64(7));
- assert_eq!(data.pointer("/m~0n").unwrap(), &Value::U64(8));
+ assert_eq!(data.pointer("/").unwrap(), &0.into());
+ assert_eq!(data.pointer("/a~1b").unwrap(), &1.into());
+ assert_eq!(data.pointer("/c%d").unwrap(), &2.into());
+ assert_eq!(data.pointer("/e^f").unwrap(), &3.into());
+ assert_eq!(data.pointer("/g|h").unwrap(), &4.into());
+ assert_eq!(data.pointer("/i\\j").unwrap(), &5.into());
+ assert_eq!(data.pointer("/k\"l").unwrap(), &6.into());
+ assert_eq!(data.pointer("/ ").unwrap(), &7.into());
+ assert_eq!(data.pointer("/m~0n").unwrap(), &8.into());
// Invalid pointers
assert!(data.pointer("/unknown").is_none());
assert!(data.pointer("/e^f/ertz").is_none());
@@ -1684,15 +1702,15 @@ fn test_json_pointer_mut() {
Value::String("baz".to_owned())]));
assert_eq!(data.pointer_mut("/foo/0").unwrap(),
&Value::String("bar".to_owned()));
- assert_eq!(data.pointer_mut("/").unwrap(), &Value::U64(0));
- assert_eq!(data.pointer_mut("/a~1b").unwrap(), &Value::U64(1));
- assert_eq!(data.pointer_mut("/c%d").unwrap(), &Value::U64(2));
- assert_eq!(data.pointer_mut("/e^f").unwrap(), &Value::U64(3));
- assert_eq!(data.pointer_mut("/g|h").unwrap(), &Value::U64(4));
- assert_eq!(data.pointer_mut("/i\\j").unwrap(), &Value::U64(5));
- assert_eq!(data.pointer_mut("/k\"l").unwrap(), &Value::U64(6));
- assert_eq!(data.pointer_mut("/ ").unwrap(), &Value::U64(7));
- assert_eq!(data.pointer_mut("/m~0n").unwrap(), &Value::U64(8));
+ assert_eq!(data.pointer_mut("/").unwrap(), &0.into());
+ assert_eq!(data.pointer_mut("/a~1b").unwrap(), &1.into());
+ assert_eq!(data.pointer_mut("/c%d").unwrap(), &2.into());
+ assert_eq!(data.pointer_mut("/e^f").unwrap(), &3.into());
+ assert_eq!(data.pointer_mut("/g|h").unwrap(), &4.into());
+ assert_eq!(data.pointer_mut("/i\\j").unwrap(), &5.into());
+ assert_eq!(data.pointer_mut("/k\"l").unwrap(), &6.into());
+ assert_eq!(data.pointer_mut("/ ").unwrap(), &7.into());
+ assert_eq!(data.pointer_mut("/m~0n").unwrap(), &8.into());
// Invalid pointers
assert!(data.pointer_mut("/unknown").is_none());
@@ -1701,13 +1719,13 @@ fn test_json_pointer_mut() {
assert!(data.pointer_mut("/foo/01").is_none());
// Mutable pointer checks
- *data.pointer_mut("/").unwrap() = Value::U64(100);
- assert_eq!(data.pointer("/").unwrap(), &Value::U64(100));
+ *data.pointer_mut("/").unwrap() = 100.into();
+ assert_eq!(data.pointer("/").unwrap(), &100.into());
*data.pointer_mut("/foo/0").unwrap() = Value::String("buzz".to_owned());
assert_eq!(data.pointer("/foo/0").unwrap(), &Value::String("buzz".to_owned()));
// Example of ownership stealing
- assert_eq!(data.pointer_mut("/a~1b").map(|m| mem::replace(m, Value::Null)).unwrap(), Value::U64(1));
+ assert_eq!(data.pointer_mut("/a~1b").map(|m| mem::replace(m, Value::Null)).unwrap(), 1.into());
assert_eq!(data.pointer("/a~1b").unwrap(), &Value::Null);
// Need to compare against a clone so we don't anger the borrow checker
diff --git a/json_tests/tests/test_json_builder.rs b/json_tests/tests/test_json_builder.rs
index 2b312291f..44fcebadf 100644
--- a/json_tests/tests/test_json_builder.rs
+++ b/json_tests/tests/test_json_builder.rs
@@ -13,15 +13,17 @@ fn test_array_builder() {
.push(3)
.build();
assert_eq!(value,
- Value::Array(vec![Value::U64(1), Value::U64(2), Value::U64(3)]));
+ Value::Array(vec![Value::Number(1.into()),
+ Value::Number(2.into()),
+ Value::Number(3.into())]));
let value = ArrayBuilder::new()
.push_array(|bld| bld.push(1).push(2).push(3))
.build();
assert_eq!(value,
- Value::Array(vec![Value::Array(vec![Value::U64(1),
- Value::U64(2),
- Value::U64(3)])]));
+ Value::Array(vec![Value::Array(vec![Value::Number(1.into()),
+ Value::Number(2.into()),
+ Value::Number(3.into())])]));
let value = ArrayBuilder::new()
.push_object(|bld| {
@@ -31,8 +33,8 @@ fn test_array_builder() {
.build();
let mut map = Map::new();
- map.insert("a".to_string(), Value::U64(1));
- map.insert("b".to_string(), Value::U64(2));
+ map.insert("a".to_string(), Value::Number(1.into()));
+ map.insert("b".to_string(), Value::Number(2.into()));
assert_eq!(value, Value::Array(vec![Value::Object(map)]));
}
@@ -47,7 +49,7 @@ fn test_object_builder() {
.build();
let mut map = Map::new();
- map.insert("a".to_string(), Value::U64(1));
- map.insert("b".to_string(), Value::U64(2));
+ map.insert("a".to_string(), Value::Number(1.into()));
+ map.insert("b".to_string(), Value::Number(2.into()));
assert_eq!(value, Value::Object(map));
}
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
null |
serde-rs__json-187
| 187
|
[
"186"
] |
2017-01-15T18:48:26Z
|
This applies to ToJson::to_json as well.
|
d8cf0146aa7f633ff7169aa6d0b438ce7ba990a0
|
Return Result<Value, Error> from to_value
Currently `to_value` returns Value and panics if the conversion fails.
|
diff --git a/json/src/builder.rs b/json/src/builder.rs
index 0765dd84b..76d0d4e2e 100644
--- a/json/src/builder.rs
+++ b/json/src/builder.rs
@@ -55,8 +55,12 @@ impl ArrayBuilder {
}
/// Insert a value into the array.
+ ///
+ /// This method panics if the value cannot be represented as JSON. This can
+ /// happen if `T`'s implementation of `Serialize` decides to fail, or if `T`
+ /// contains a map with non-string keys.
pub fn push<T: ser::Serialize>(mut self, v: T) -> ArrayBuilder {
- self.array.push(value::to_value(&v));
+ self.array.push(value::to_value(&v).expect("value cannot be represented as JSON"));
self
}
@@ -99,11 +103,15 @@ impl ObjectBuilder {
}
/// Insert a key-value pair into the object.
+ ///
+ /// This method panics if the value cannot be represented as JSON. This can
+ /// happen if `T`'s implementation of `Serialize` decides to fail, or if `T`
+ /// contains a map with non-string keys.
pub fn insert<S, V>(mut self, key: S, value: V) -> ObjectBuilder
where S: Into<String>,
V: ser::Serialize,
{
- self.object.insert(key.into(), value::to_value(&value));
+ self.object.insert(key.into(), value::to_value(&value).expect("value cannot be represented as JSON"));
self
}
diff --git a/json/src/value.rs b/json/src/value.rs
index 3019935a5..76ed47729 100644
--- a/json/src/value.rs
+++ b/json/src/value.rs
@@ -755,7 +755,7 @@ impl ser::Serializer for Serializer {
where T: ser::Serialize,
{
let mut values = Map::new();
- values.insert(String::from(variant), to_value(&value));
+ values.insert(String::from(variant), try!(to_value(&value)));
Ok(Value::Object(values))
}
@@ -874,7 +874,7 @@ impl ser::SerializeSeq for SerializeVec {
fn serialize_element<T>(&mut self, value: T) -> Result<(), Error>
where T: ser::Serialize
{
- self.vec.push(to_value(&value));
+ self.vec.push(try!(to_value(&value)));
Ok(())
}
@@ -920,7 +920,7 @@ impl ser::SerializeTupleVariant for SerializeTupleVariant {
fn serialize_field<T>(&mut self, value: T) -> Result<(), Error>
where T: ser::Serialize
{
- self.vec.push(to_value(&value));
+ self.vec.push(try!(to_value(&value)));
Ok(())
}
@@ -940,7 +940,7 @@ impl ser::SerializeMap for SerializeMap {
fn serialize_key<T>(&mut self, key: T) -> Result<(), Error>
where T: ser::Serialize
{
- match to_value(&key) {
+ match try!(to_value(&key)) {
Value::String(s) => self.next_key = Some(s),
_ => return Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)),
};
@@ -951,7 +951,7 @@ impl ser::SerializeMap for SerializeMap {
where T: ser::Serialize
{
match self.next_key.take() {
- Some(key) => self.map.insert(key, to_value(&value)),
+ Some(key) => self.map.insert(key, try!(to_value(&value))),
None => {
return Err(Error::Syntax(ErrorCode::Custom("serialize_map_value without \
matching serialize_map_key".to_owned()),
@@ -989,7 +989,7 @@ impl ser::SerializeStructVariant for SerializeStructVariant {
fn serialize_field<V>(&mut self, key: &'static str, value: V) -> Result<(), Error>
where V: ser::Serialize
{
- self.map.insert(String::from(key), to_value(&value));
+ self.map.insert(String::from(key), try!(to_value(&value)));
Ok(())
}
@@ -1339,36 +1339,52 @@ impl de::Deserializer for MapDeserializer {
}
}
-/// Shortcut function to encode a `T` into a JSON `Value`
+/// Convert a `T` into `serde_json::Value` which is an enum that can represent
+/// any valid JSON data.
+///
+/// This conversion can fail if `T`'s implementation of `Serialize` decides to
+/// fail, or if `T` contains a map with non-string keys.
///
/// ```rust
-/// use serde_json::to_value;
-/// let val = to_value("foo");
-/// assert_eq!(val.as_str(), Some("foo"))
+/// # use serde_json::Value;
+/// let val = serde_json::to_value("s").unwrap();
+/// assert_eq!(val, Value::String("s".to_owned()));
/// ```
-pub fn to_value<T>(value: T) -> Value
+pub fn to_value<T>(value: T) -> Result<Value, Error>
where T: ser::Serialize,
{
- value.serialize(Serializer).expect("failed to serialize")
+ value.serialize(Serializer)
}
-/// Shortcut function to decode a JSON `Value` into a `T`
+/// Interpret a `serde_json::Value` as an instance of type `T`.
+///
+/// This conversion can fail if the structure of the Value does not match the
+/// structure expected by `T`, for example if `T` is a struct type but the Value
+/// contains something other than a JSON map. It can also fail if the structure
+/// is correct but `T`'s implementation of `Deserialize` decides that something
+/// is wrong with the data, for example required struct fields are missing from
+/// the JSON map or some number is too big to fit in the expected primitive
+/// type.
pub fn from_value<T>(value: Value) -> Result<T, Error>
where T: de::Deserialize,
{
de::Deserialize::deserialize(value)
}
-/// A trait for converting values to JSON
+/// Representation of any serializable data as a `serde_json::Value`.
pub trait ToJson {
- /// Converts the value of `self` to an instance of JSON
- fn to_json(&self) -> Value;
+ /// Represent `self` as a `serde_json::Value`. Note that `Value` is not a
+ /// JSON string. If you need a string, use `serde_json::to_string` instead.
+ ///
+ /// This conversion can fail if `T`'s implementation of `Serialize` decides
+ /// to fail, or if `T` contains a map with non-string keys.
+ fn to_json(&self) -> Result<Value, Error>;
}
impl<T: ?Sized> ToJson for T
where T: ser::Serialize,
{
- fn to_json(&self) -> Value {
- to_value(&self)
+ fn to_json(&self) -> Result<Value, Error> {
+ to_value(self)
}
}
|
diff --git a/json_tests/tests/test_json.rs b/json_tests/tests/test_json.rs
index f95755074..851b732b2 100644
--- a/json_tests/tests/test_json.rs
+++ b/json_tests/tests/test_json.rs
@@ -66,7 +66,7 @@ fn test_encode_ok<T>(errors: &[(T, &str)])
let s = serde_json::to_string(value).unwrap();
assert_eq!(s, out);
- let v = to_value(&value);
+ let v = to_value(&value).unwrap();
let s = serde_json::to_string(&v).unwrap();
assert_eq!(s, out);
}
@@ -81,7 +81,7 @@ fn test_pretty_encode_ok<T>(errors: &[(T, &str)])
let s = serde_json::to_string_pretty(value).unwrap();
assert_eq!(s, out);
- let v = to_value(&value);
+ let v = to_value(&value).unwrap();
let s = serde_json::to_string_pretty(&v).unwrap();
assert_eq!(s, out);
}
@@ -135,16 +135,16 @@ fn test_write_f64() {
#[test]
fn test_encode_nonfinite_float_yields_null() {
- let v = to_value(::std::f64::NAN);
+ let v = to_value(::std::f64::NAN).unwrap();
assert!(v.is_null());
- let v = to_value(::std::f64::INFINITY);
+ let v = to_value(::std::f64::INFINITY).unwrap();
assert!(v.is_null());
- let v = to_value(::std::f32::NAN);
+ let v = to_value(::std::f32::NAN).unwrap();
assert!(v.is_null());
- let v = to_value(::std::f32::INFINITY);
+ let v = to_value(::std::f32::INFINITY).unwrap();
assert!(v.is_null());
}
@@ -666,7 +666,7 @@ fn test_write_newtype_struct() {
struct Newtype(Map<String, i32>);
let inner = Newtype(treemap!(String::from("inner") => 123));
- let outer = treemap!(String::from("outer") => to_value(&inner));
+ let outer = treemap!(String::from("outer") => to_value(&inner).unwrap());
test_encode_ok(&[
(inner, r#"{"inner":123}"#),
@@ -692,7 +692,7 @@ fn test_parse_ok<T>(tests: Vec<(&str, T)>)
// Make sure we can deserialize into a `Value`.
let json_value: Value = from_str(s).unwrap();
- assert_eq!(json_value, to_value(&value));
+ assert_eq!(json_value, to_value(&value).unwrap());
// Make sure we can deserialize from a `Value`.
let v: T = from_value(json_value.clone()).unwrap();
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
null |
serde-rs__json-159
| 159
|
[
"157"
] |
2016-10-04T04:29:18Z
|
b35c3c7202dbaf107730928dd32915727cbe80be
|
Update tests to use serde_derive
The Travis build is failing because serde_macros no longer compiles.
|
diff --git a/build.rs b/build.rs
deleted file mode 100644
index b1aadd789..000000000
--- a/build.rs
+++ /dev/null
@@ -1,29 +0,0 @@
-#[cfg(not(feature = "serde_macros"))]
-mod inner {
- extern crate syntex;
- extern crate serde_codegen;
-
- use std::env;
- use std::path::Path;
-
- pub fn main() {
- let out_dir = env::var_os("OUT_DIR").unwrap();
-
- let src = Path::new("src/main.rs.in");
- let dst = Path::new(&out_dir).join("main.rs");
-
- let mut registry = syntex::Registry::new();
-
- serde_codegen::register(&mut registry);
- registry.expand("", &src, &dst).unwrap();
- }
-}
-
-#[cfg(feature = "serde_macros")]
-mod inner {
- pub fn main() {}
-}
-
-fn main() {
- inner::main();
-}
diff --git a/json/src/lib.rs b/json/src/lib.rs
index edf782b1b..2c2034d6f 100644
--- a/json/src/lib.rs
+++ b/json/src/lib.rs
@@ -81,11 +81,6 @@
//! ## Parsing a `str` to `Value` and reading the result
//!
//! ```rust
-//! #![feature(rustc_macro)]
-//!
-//! #[macro_use]
-//! extern crate serde_derive;
-//!
//! extern crate serde_json;
//!
//! use serde_json::Value;
|
diff --git a/json_tests/Cargo.toml b/json_tests/Cargo.toml
index b477d9bc7..6e44adf8f 100644
--- a/json_tests/Cargo.toml
+++ b/json_tests/Cargo.toml
@@ -5,7 +5,7 @@ authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
build = "build.rs"
[features]
-default = ["serde_macros"]
+default = ["serde_derive"]
with-syntex = ["syntex", "serde_codegen", "indoc/with-syntex"]
unstable-testing = ["clippy", "serde_json/clippy"]
@@ -22,7 +22,7 @@ num-traits = "*"
rustc-serialize = "*"
serde = "0.8.0"
serde_json = { path = "../json" }
-serde_macros = { version = "0.8.0", optional = true }
+serde_derive = { version = "0.8.0", optional = true }
skeptic = "^0.4.0"
[[test]]
diff --git a/json_tests/benches/bench.rs b/json_tests/benches/bench.rs
index b865ae170..28f789668 100644
--- a/json_tests/benches/bench.rs
+++ b/json_tests/benches/bench.rs
@@ -1,11 +1,14 @@
#![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
-#![cfg_attr(not(feature = "with-syntex"), feature(custom_attribute, custom_derive, plugin))]
-#![cfg_attr(not(feature = "with-syntex"), plugin(serde_macros, indoc))]
+#![cfg_attr(not(feature = "with-syntex"), feature(rustc_macro))]
#![feature(test)]
+#[cfg(not(feature = "with-syntex"))]
+#[macro_use]
+extern crate serde_derive;
+
extern crate num_traits;
extern crate rustc_serialize;
extern crate serde;
diff --git a/json_tests/tests/test.rs b/json_tests/tests/test.rs
index 92a689fdd..829e28216 100644
--- a/json_tests/tests/test.rs
+++ b/json_tests/tests/test.rs
@@ -1,8 +1,12 @@
#![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
-#![cfg_attr(not(feature = "with-syntex"), feature(custom_attribute, custom_derive, plugin))]
-#![cfg_attr(not(feature = "with-syntex"), plugin(serde_macros, indoc))]
+#![cfg_attr(not(feature = "with-syntex"), feature(rustc_macro, plugin))]
+#![cfg_attr(not(feature = "with-syntex"), plugin(indoc))]
+
+#[cfg(not(feature = "with-syntex"))]
+#[macro_use]
+extern crate serde_derive;
extern crate serde;
extern crate serde_json;
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
|
null |
serde-rs__json-156
| 156
|
[
"155"
] |
2016-09-25T19:33:26Z
|
I can look into this.
Looks like serializing `Value::F64(_)` simply proxies to `serialize_f64(v)`, where it should really check for `FpCategory::{Nan, Infinite}`, as serialization only works for finite values (https://tc39.github.io/ecma262/#sec-serializejsonproperty).
|
b4022a299a4664e6bd983471b4519c6353352a23
|
to_value(NAN) should be null
``` rust
extern crate serde_json;
fn main() {
let value = serde_json::to_value(::std::f64::NAN);
println!("value: {}", value);
println!("value.is_null(): {}", value.is_null());
}
```
Expected:
```
value: null
value.is_null(): true
```
Actual:
```
value: null
value.is_null(): false
```
|
diff --git a/json/src/value.rs b/json/src/value.rs
index ce6d9b5fe..d46f7b735 100644
--- a/json/src/value.rs
+++ b/json/src/value.rs
@@ -643,7 +643,11 @@ impl ser::Serializer for Serializer {
#[inline]
fn serialize_f64(&mut self, value: f64) -> Result<(), Error> {
- self.value = Value::F64(value);
+ self.value = if value.is_finite() {
+ Value::F64(value)
+ } else {
+ Value::Null
+ };
Ok(())
}
|
diff --git a/json_tests/tests/test_json.rs b/json_tests/tests/test_json.rs
index 7d7391701..0c8337a4b 100644
--- a/json_tests/tests/test_json.rs
+++ b/json_tests/tests/test_json.rs
@@ -132,6 +132,21 @@ fn test_write_f64() {
test_pretty_encode_ok(tests);
}
+#[test]
+fn test_encode_nonfinite_float_yields_null() {
+ let v = to_value(::std::f64::NAN);
+ assert!(v.is_null());
+
+ let v = to_value(::std::f64::INFINITY);
+ assert!(v.is_null());
+
+ let v = to_value(::std::f32::NAN);
+ assert!(v.is_null());
+
+ let v = to_value(::std::f32::INFINITY);
+ assert!(v.is_null());
+}
+
#[test]
fn test_write_str() {
let tests = &[
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
null |
serde-rs__json-143
| 143
|
[
"142"
] |
2016-08-25T21:56:26Z
|
I think this is a good idea as long as it does not affect performance when using CompactFormatter because people tend to care about that. Of the functions you suggested, I think we can make all of those work efficiently except `fn string(...)` because it would require heap-allocating the entire escaped string even in cases where serde_json currently [optimizes it away](https://github.com/serde-rs/json/blob/146cf17f78c0a86801b10f0250e86d1078d5f450/json/src/ser.rs#L853-L857). I would prefer to stick to lower-level calls.
I would suggest looking at all the writer calls made in the current serializer and turning those into Formatter methods. For example [this call](https://github.com/serde-rs/json/blob/146cf17f78c0a86801b10f0250e86d1078d5f450/json/src/ser.rs#L860) would become something like `fn string_fragment(&[u8])`.
A PR would be welcome.
Also feel free to not worry about backward compatibility. Based on GitHub search you are the only one using this API. It is a breaking change so it will need to go in 0.9.0, but you can change the Formatter trait in whatever way makes the most sense.
|
146cf17f78c0a86801b10f0250e86d1078d5f450
|
Expand Formatter support
I want to offer pretty printing of JSON objects beyond what the `PrettyFormatter` can supply, for example color support or intelligent line wrapping. For that, I'd like to expose more callbacks to control formatting.
Ideally I would like to be able to color every "token type" differently.
Currently, these things can be colored:
- `{` `}` `[` `]` `,` `:` trivially in `fn open(...)`, `fn colon(...)`, `fn comma(...)` and `fn close(...)`
- Field names (by checking if `ch == "{"` in `fn open(...)` and `fn comma(...)` and writing color info accordingly)
- Field values and array elements (by writing color info in `fn open(...)`, `fn comma(...)` and `fn close(...)`)
Note that values in general cannot be colored because when serializing an `i32` for example, no formatting callbacks are called. The current situation also leads to awkward code like this: https://github.com/dflemstr/rq/blob/bb845ea5318db377927cf10e75eff6d44194129c/src/value/json.rs#L142-L145
What would be nice is to have a callback for each JSON terminal. This would involve:
- [ ] Rename `fn open(...)` to `fn open_object/array(...)` (and `fn close(...)` to `fn close_object/array(...)`), but there can be a default method body for backwards compatibility.
- [ ] Add callbacks for all missing JSON terminals:
- [ ] `fn object_key(...)`
- [ ] `fn string(...)`
- [ ] `fn number(...)`
- [ ] `fn bool(..., bool)`
- [ ] `fn null(...)`
- [ ] Maybe add support for low-level terminals:
- [ ] `fn open/close_string(...)`.
- [ ] `fn string_char(..., char)`
- [ ] `fn string_escape(..., Escape)` where `enum Escape { Quote, ..., Unicode([u8; 4]) }` or something.
- [ ] `fn number_digit(..., char)` etc.
This probably means that the `Serializer` would never write to its `Write` on its own, but delegate everything to the `Formatter`.
I could implement this change if people think it's a good idea. I'm mostly seeking feedback on the approach first.
|
diff --git a/json/src/ser.rs b/json/src/ser.rs
index c81bff269..c758581d8 100644
--- a/json/src/ser.rs
+++ b/json/src/ser.rs
@@ -10,6 +10,7 @@ use super::error::{Error, ErrorCode, Result};
use itoa;
use dtoa;
+use num_traits;
/// A structure for serializing Rust values into JSON.
pub struct Serializer<W, F = CompactFormatter> {
@@ -56,6 +57,28 @@ impl<W, F> Serializer<W, F>
pub fn into_inner(self) -> W {
self.writer
}
+
+ #[inline]
+ fn write_integer<V>(&mut self, value: V) -> Result<()>
+ where V: itoa::Integer
+ {
+ try!(self.formatter.write_integer(&mut self.writer, value));
+ Ok(())
+ }
+
+ #[inline]
+ fn write_floating<V>(&mut self, value: V) -> Result<()>
+ where V: dtoa::Floating + num_traits::Float
+ {
+ match value.classify() {
+ FpCategory::Nan | FpCategory::Infinite => {
+ self.formatter.write_null(&mut self.writer)
+ },
+ _ => {
+ self.formatter.write_floating(&mut self.writer, value)
+ },
+ }
+ }
}
#[doc(hidden)]
@@ -82,71 +105,67 @@ impl<W, F> ser::Serializer for Serializer<W, F>
#[inline]
fn serialize_bool(&mut self, value: bool) -> Result<()> {
- if value {
- self.writer.write_all(b"true").map_err(From::from)
- } else {
- self.writer.write_all(b"false").map_err(From::from)
- }
+ self.formatter.write_bool(&mut self.writer, value)
}
#[inline]
fn serialize_isize(&mut self, value: isize) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.write_integer(value)
}
#[inline]
fn serialize_i8(&mut self, value: i8) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.write_integer(value)
}
#[inline]
fn serialize_i16(&mut self, value: i16) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.write_integer(value)
}
#[inline]
fn serialize_i32(&mut self, value: i32) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.write_integer(value)
}
#[inline]
fn serialize_i64(&mut self, value: i64) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.write_integer(value)
}
#[inline]
fn serialize_usize(&mut self, value: usize) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.write_integer(value)
}
#[inline]
fn serialize_u8(&mut self, value: u8) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.write_integer(value)
}
#[inline]
fn serialize_u16(&mut self, value: u16) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.write_integer(value)
}
#[inline]
fn serialize_u32(&mut self, value: u32) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.write_integer(value)
}
#[inline]
fn serialize_u64(&mut self, value: u64) -> Result<()> {
- itoa::write(&mut self.writer, value).map_err(From::from)
+ self.write_integer(value)
}
#[inline]
fn serialize_f32(&mut self, value: f32) -> Result<()> {
- fmt_f32_or_null(&mut self.writer, value).map_err(From::from)
+ self.write_floating(value)
}
#[inline]
fn serialize_f64(&mut self, value: f64) -> Result<()> {
- fmt_f64_or_null(&mut self.writer, value).map_err(From::from)
+ self.write_floating(value)
}
#[inline]
@@ -170,7 +189,7 @@ impl<W, F> ser::Serializer for Serializer<W, F>
#[inline]
fn serialize_unit(&mut self) -> Result<()> {
- self.writer.write_all(b"null").map_err(From::from)
+ self.formatter.write_null(&mut self.writer)
}
#[inline]
@@ -210,12 +229,15 @@ impl<W, F> ser::Serializer for Serializer<W, F>
) -> Result<()>
where T: ser::Serialize,
{
- try!(self.formatter.open(&mut self.writer, b'{'));
- try!(self.formatter.comma(&mut self.writer, true));
+ try!(self.formatter.begin_object(&mut self.writer));
+ try!(self.formatter.begin_object_key(&mut self.writer, true));
try!(self.serialize_str(variant));
- try!(self.formatter.colon(&mut self.writer));
+ try!(self.formatter.end_object_key(&mut self.writer));
+ try!(self.formatter.begin_object_value(&mut self.writer));
try!(value.serialize(self));
- self.formatter.close(&mut self.writer, b'}')
+ try!(self.formatter.end_object_value(&mut self.writer));
+ try!(self.formatter.end_object(&mut self.writer));
+ Ok(())
}
#[inline]
@@ -233,10 +255,11 @@ impl<W, F> ser::Serializer for Serializer<W, F>
#[inline]
fn serialize_seq(&mut self, len: Option<usize>) -> Result<State> {
if len == Some(0) {
- try!(self.writer.write_all(b"[]"));
+ try!(self.formatter.begin_array(&mut self.writer));
+ try!(self.formatter.end_array(&mut self.writer));
Ok(State::Empty)
} else {
- try!(self.formatter.open(&mut self.writer, b'['));
+ try!(self.formatter.begin_array(&mut self.writer));
Ok(State::First)
}
}
@@ -249,17 +272,19 @@ impl<W, F> ser::Serializer for Serializer<W, F>
) -> Result<()>
where T: ser::Serialize,
{
- try!(self.formatter.comma(&mut self.writer, *state == State::First));
+ try!(self.formatter.begin_array_value(&mut self.writer, *state == State::First));
*state = State::Rest;
+ try!(value.serialize(self));
+ try!(self.formatter.end_array_value(&mut self.writer));
- value.serialize(self)
+ Ok(())
}
#[inline]
fn serialize_seq_end(&mut self, state: State) -> Result<()> {
match state {
State::Empty => Ok(()),
- _ => self.formatter.close(&mut self.writer, b']'),
+ _ => self.formatter.end_array(&mut self.writer),
}
}
@@ -318,10 +343,11 @@ impl<W, F> ser::Serializer for Serializer<W, F>
variant: &'static str,
len: usize
) -> Result<State> {
- try!(self.formatter.open(&mut self.writer, b'{'));
- try!(self.formatter.comma(&mut self.writer, true));
+ try!(self.formatter.begin_object(&mut self.writer));
+ try!(self.formatter.begin_object_key(&mut self.writer, true));
try!(self.serialize_str(variant));
- try!(self.formatter.colon(&mut self.writer));
+ try!(self.formatter.end_object_key(&mut self.writer));
+ try!(self.formatter.begin_object_value(&mut self.writer));
self.serialize_seq(Some(len))
}
@@ -337,16 +363,19 @@ impl<W, F> ser::Serializer for Serializer<W, F>
#[inline]
fn serialize_tuple_variant_end(&mut self, state: State) -> Result<()> {
try!(self.serialize_seq_end(state));
- self.formatter.close(&mut self.writer, b'}')
+ try!(self.formatter.end_object_value(&mut self.writer));
+ try!(self.formatter.end_object(&mut self.writer));
+ Ok(())
}
#[inline]
fn serialize_map(&mut self, len: Option<usize>) -> Result<State> {
if len == Some(0) {
- try!(self.writer.write_all(b"{}"));
+ try!(self.formatter.begin_object(&mut self.writer));
+ try!(self.formatter.end_object(&mut self.writer));
Ok(State::Empty)
} else {
- try!(self.formatter.open(&mut self.writer, b'{'));
+ try!(self.formatter.begin_object(&mut self.writer));
Ok(State::First)
}
}
@@ -357,14 +386,15 @@ impl<W, F> ser::Serializer for Serializer<W, F>
state: &mut State,
key: T,
) -> Result<()> {
- try!(self.formatter.comma(&mut self.writer, *state == State::First));
+ try!(self.formatter.begin_object_key(&mut self.writer, *state == State::First));
*state = State::Rest;
try!(key.serialize(&mut MapKeySerializer {
ser: self,
}));
- self.formatter.colon(&mut self.writer)
+ try!(self.formatter.end_object_key(&mut self.writer));
+ Ok(())
}
#[inline]
@@ -373,14 +403,17 @@ impl<W, F> ser::Serializer for Serializer<W, F>
_: &mut State,
value: T,
) -> Result<()> {
- value.serialize(self)
+ try!(self.formatter.begin_object_value(&mut self.writer));
+ try!(value.serialize(self));
+ try!(self.formatter.end_object_value(&mut self.writer));
+ Ok(())
}
#[inline]
fn serialize_map_end(&mut self, state: State) -> Result<()> {
match state {
State::Empty => Ok(()),
- _ => self.formatter.close(&mut self.writer, b'}'),
+ _ => self.formatter.end_object(&mut self.writer),
}
}
@@ -417,10 +450,11 @@ impl<W, F> ser::Serializer for Serializer<W, F>
variant: &'static str,
len: usize
) -> Result<State> {
- try!(self.formatter.open(&mut self.writer, b'{'));
- try!(self.formatter.comma(&mut self.writer, true));
+ try!(self.formatter.begin_object(&mut self.writer));
+ try!(self.formatter.begin_object_key(&mut self.writer, true));
try!(self.serialize_str(variant));
- try!(self.formatter.colon(&mut self.writer));
+ try!(self.formatter.end_object_key(&mut self.writer));
+ try!(self.formatter.begin_object_value(&mut self.writer));
self.serialize_map(Some(len))
}
@@ -437,7 +471,9 @@ impl<W, F> ser::Serializer for Serializer<W, F>
#[inline]
fn serialize_struct_variant_end(&mut self, state: State) -> Result<()> {
try!(self.serialize_struct_end(state));
- self.formatter.close(&mut self.writer, b'}')
+ try!(self.formatter.end_object_value(&mut self.writer));
+ try!(self.formatter.end_object(&mut self.writer));
+ Ok(())
}
}
@@ -722,38 +758,167 @@ impl<'a, W, F> ser::Serializer for MapKeySerializer<'a, W, F>
}
}
+/// Represents a character escape code in a type-safe manner.
+pub enum CharEscape {
+ /// An escaped quote `"`
+ Quote,
+ /// An escaped reverse solidus `\`
+ ReverseSolidus,
+ /// An escaped solidus `/`
+ Solidus,
+ /// An escaped backspace character (usually escaped as `\b`)
+ Backspace,
+ /// An escaped form feed character (usually escaped as `\f`)
+ FormFeed,
+ /// An escaped line feed character (usually escaped as `\n`)
+ LineFeed,
+ /// An escaped carriage return character (usually escaped as `\r`)
+ CarriageReturn,
+ /// An escaped tab character (usually escaped as `\t`)
+ Tab,
+ /// An escaped ASCII plane control character (usually escaped as
+ /// `\u00XX` where `XX` are two hex characters)
+ AsciiControl(u8),
+}
+
+impl CharEscape {
+ #[inline]
+ fn from_escape_table(escape: u8, byte: u8) -> CharEscape {
+ match escape {
+ self::BB => CharEscape::Backspace,
+ self::TT => CharEscape::Tab,
+ self::NN => CharEscape::LineFeed,
+ self::FF => CharEscape::FormFeed,
+ self::RR => CharEscape::CarriageReturn,
+ self::QU => CharEscape::Quote,
+ self::BS => CharEscape::ReverseSolidus,
+ self::U => CharEscape::AsciiControl(byte),
+ _ => unreachable!(),
+ }
+ }
+}
+
/// This trait abstracts away serializing the JSON control characters, which allows the user to
/// optionally pretty print the JSON output.
pub trait Formatter {
- /// Called when serializing a '{' or '['.
- fn open<W>(&mut self, writer: &mut W, ch: u8) -> Result<()>
- where W: io::Write;
+ /// Writes a `null` value to the specified writer.
+ #[inline]
+ fn write_null<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ writer.write_all(b"null").map_err(From::from)
+ }
- /// Called when serializing a ','.
- fn comma<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
- where W: io::Write;
+ /// Writes a `true` or `false` value to the specified writer.
+ #[inline]
+ fn write_bool<W>(&mut self, writer: &mut W, value: bool) -> Result<()>
+ where W: io::Write
+ {
+ let s = if value {
+ b"true" as &[u8]
+ } else {
+ b"false" as &[u8]
+ };
+ writer.write_all(s).map_err(From::from)
+ }
- /// Called when serializing a ':'.
- fn colon<W>(&mut self, writer: &mut W) -> Result<()> where W: io::Write;
+ /// Writes an integer value like `-123` to the specified writer.
+ #[inline]
+ fn write_integer<W, I>(&mut self, writer: &mut W, value: I) -> Result<()>
+ where W: io::Write,
+ I: itoa::Integer
+ {
+ itoa::write(writer, value).map_err(From::from)
+ }
- /// Called when serializing a '}' or ']'.
- fn close<W>(&mut self, writer: &mut W, ch: u8) -> Result<()>
- where W: io::Write;
-}
+ /// Writes a floating point value like `-31.26e+12` to the
+ /// specified writer.
+ #[inline]
+ fn write_floating<W, F>(&mut self, writer: &mut W, value: F) -> Result<()>
+ where W: io::Write,
+ F: dtoa::Floating
+ {
+ dtoa::write(writer, value).map_err(From::from)
+ }
-/// This structure compacts a JSON value with no extra whitespace.
-#[derive(Clone, Debug)]
-pub struct CompactFormatter;
+ /// Called before each series of `write_string_fragment` and
+ /// `write_char_escape`. Writes a `"` to the specified writer.
+ #[inline]
+ fn begin_string<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ writer.write_all(b"\"").map_err(From::from)
+ }
-impl Formatter for CompactFormatter {
- fn open<W>(&mut self, writer: &mut W, ch: u8) -> Result<()>
- where W: io::Write,
+ /// Called after each series of `write_string_fragment` and
+ /// `write_char_escape`. Writes a `"` to the specified writer.
+ #[inline]
+ fn end_string<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
{
- writer.write_all(&[ch]).map_err(From::from)
+ writer.write_all(b"\"").map_err(From::from)
}
- fn comma<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
- where W: io::Write,
+ /// Writes a string fragment that doesn't need any escaping to the
+ /// specified writer.
+ #[inline]
+ fn write_string_fragment<W>(&mut self, writer: &mut W, fragment: &[u8]) -> Result<()>
+ where W: io::Write
+ {
+ writer.write_all(fragment).map_err(From::from)
+ }
+
+ /// Writes a character escape code to the specified writer.
+ #[inline]
+ fn write_char_escape<W>(&mut self, writer: &mut W, char_escape: CharEscape) -> Result<()>
+ where W: io::Write
+ {
+ use self::CharEscape::*;
+
+ let s = match char_escape {
+ Quote => b"\\\"",
+ ReverseSolidus => b"\\\\",
+ Solidus => b"\\/",
+ Backspace => b"\\b",
+ FormFeed => b"\\f",
+ LineFeed => b"\\n",
+ CarriageReturn => b"\\r",
+ Tab => b"\\t",
+ AsciiControl(byte) => {
+ static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";
+ let bytes = &[b'\\', b'u', b'0', b'0',
+ HEX_DIGITS[(byte >> 4) as usize],
+ HEX_DIGITS[(byte & 0xF) as usize]];
+ return writer.write_all(bytes).map_err(From::from);
+ }
+ };
+
+ writer.write_all(s).map_err(From::from)
+ }
+
+ /// Called before every array. Writes a `[` to the specified
+ /// writer.
+ #[inline]
+ fn begin_array<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ writer.write_all(b"[").map_err(From::from)
+ }
+
+ /// Called after every array. Writes a `]` to the specified
+ /// writer.
+ #[inline]
+ fn end_array<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ writer.write_all(b"]").map_err(From::from)
+ }
+
+ /// Called before every array value. Writes a `,` if needed to
+ /// the specified writer.
+ #[inline]
+ fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
+ where W: io::Write
{
if first {
Ok(())
@@ -762,23 +927,84 @@ impl Formatter for CompactFormatter {
}
}
- fn colon<W>(&mut self, writer: &mut W) -> Result<()>
- where W: io::Write,
+ /// Called after every array value.
+ #[inline]
+ fn end_array_value<W>(&mut self, _writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ Ok(())
+ }
+
+ /// Called before every object. Writes a `{` to the specified
+ /// writer.
+ #[inline]
+ fn begin_object<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ writer.write_all(b"{").map_err(From::from)
+ }
+
+ /// Called after every object. Writes a `}` to the specified
+ /// writer.
+ #[inline]
+ fn end_object<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ writer.write_all(b"}").map_err(From::from)
+ }
+
+ /// Called before every object key.
+ #[inline]
+ fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
+ where W: io::Write
+ {
+ if first {
+ Ok(())
+ } else {
+ writer.write_all(b",").map_err(From::from)
+ }
+ }
+
+ /// Called after every object key. A `:` should be written to the
+ /// specified writer by either this method or
+ /// `begin_object_value`.
+ #[inline]
+ fn end_object_key<W>(&mut self, _writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ Ok(())
+ }
+
+ /// Called before every object value. A `:` should be written to
+ /// the specified writer by either this method or
+ /// `end_object_key`.
+ #[inline]
+ fn begin_object_value<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
{
writer.write_all(b":").map_err(From::from)
}
- fn close<W>(&mut self, writer: &mut W, ch: u8) -> Result<()>
- where W: io::Write,
+ /// Called after every object value.
+ #[inline]
+ fn end_object_value<W>(&mut self, _writer: &mut W) -> Result<()>
+ where W: io::Write
{
- writer.write_all(&[ch]).map_err(From::from)
+ Ok(())
}
}
+/// This structure compacts a JSON value with no extra whitespace.
+#[derive(Clone, Debug)]
+pub struct CompactFormatter;
+
+impl Formatter for CompactFormatter {}
+
/// This structure pretty prints a JSON value to make it human readable.
#[derive(Clone, Debug)]
pub struct PrettyFormatter<'a> {
current_indent: usize,
+ has_value: bool,
indent: &'a [u8],
}
@@ -792,6 +1018,7 @@ impl<'a> PrettyFormatter<'a> {
pub fn with_indent(indent: &'a [u8]) -> Self {
PrettyFormatter {
current_indent: 0,
+ has_value: false,
indent: indent,
}
}
@@ -804,49 +1031,115 @@ impl<'a> Default for PrettyFormatter<'a> {
}
impl<'a> Formatter for PrettyFormatter<'a> {
- fn open<W>(&mut self, writer: &mut W, ch: u8) -> Result<()>
- where W: io::Write,
+ #[inline]
+ fn begin_array<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
{
self.current_indent += 1;
- writer.write_all(&[ch]).map_err(From::from)
+ self.has_value = false;
+ writer.write_all(b"[").map_err(From::from)
}
- fn comma<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
- where W: io::Write,
+ #[inline]
+ fn end_array<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ self.current_indent -= 1;
+
+ if self.has_value {
+ try!(writer.write(b"\n"));
+ try!(indent(writer, self.current_indent, self.indent));
+ }
+
+ writer.write_all(b"]").map_err(From::from)
+ }
+
+ #[inline]
+ fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
+ where W: io::Write
{
if first {
try!(writer.write_all(b"\n"));
} else {
try!(writer.write_all(b",\n"));
}
+ try!(indent(writer, self.current_indent, self.indent));
+ Ok(())
+ }
- indent(writer, self.current_indent, self.indent)
+ #[inline]
+ fn end_array_value<W>(&mut self, _writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ self.has_value = true;
+ Ok(())
}
- fn colon<W>(&mut self, writer: &mut W) -> Result<()>
- where W: io::Write,
+ #[inline]
+ fn begin_object<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
{
- writer.write_all(b": ").map_err(From::from)
+ self.current_indent += 1;
+ self.has_value = false;
+ writer.write_all(b"{").map_err(From::from)
}
- fn close<W>(&mut self, writer: &mut W, ch: u8) -> Result<()>
- where W: io::Write,
+ #[inline]
+ fn end_object<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
{
self.current_indent -= 1;
- try!(writer.write(b"\n"));
- try!(indent(writer, self.current_indent, self.indent));
- writer.write_all(&[ch]).map_err(From::from)
+ if self.has_value {
+ try!(writer.write(b"\n"));
+ try!(indent(writer, self.current_indent, self.indent));
+ }
+
+ writer.write_all(b"}").map_err(From::from)
+ }
+
+ #[inline]
+ fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
+ where W: io::Write
+ {
+ if first {
+ try!(writer.write_all(b"\n"));
+ } else {
+ try!(writer.write_all(b",\n"));
+ }
+ indent(writer, self.current_indent, self.indent)
+ }
+
+ #[inline]
+ fn begin_object_value<W>(&mut self, writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ writer.write_all(b": ").map_err(From::from)
+ }
+
+ #[inline]
+ fn end_object_value<W>(&mut self, _writer: &mut W) -> Result<()>
+ where W: io::Write
+ {
+ self.has_value = true;
+ Ok(())
}
}
/// Serializes and escapes a `&str` into a JSON string.
pub fn escape_str<W>(wr: &mut W, value: &str) -> Result<()>
+ where W: io::Write
+{
+ format_escaped_str(wr, &mut CompactFormatter, value)
+}
+
+fn format_escaped_str<W, F>(writer: &mut W, formatter: &mut F, value: &str) -> Result<()>
where W: io::Write,
+ F: Formatter
{
let bytes = value.as_bytes();
- try!(wr.write_all(b"\""));
+ try!(formatter.begin_string(writer));
let mut start = 0;
@@ -857,29 +1150,20 @@ pub fn escape_str<W>(wr: &mut W, value: &str) -> Result<()>
}
if start < i {
- try!(wr.write_all(&bytes[start..i]));
+ try!(formatter.write_string_fragment(writer, &bytes[start..i]));
}
- if escape == b'u' {
- static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";
- try!(wr.write_all(&[b'\\',
- b'u',
- b'0',
- b'0',
- HEX_DIGITS[(byte >> 4) as usize],
- HEX_DIGITS[(byte & 0xF) as usize]]));
- } else {
- try!(wr.write_all(&[b'\\', escape]));
- }
+ let char_escape = CharEscape::from_escape_table(escape, byte);
+ try!(formatter.write_char_escape(writer, char_escape));
start = i + 1;
}
if start != bytes.len() {
- try!(wr.write_all(&bytes[start..]));
+ try!(formatter.write_string_fragment(writer, &bytes[start..]));
}
- try!(wr.write_all(b"\""));
+ try!(formatter.end_string(writer));
Ok(())
}
@@ -926,28 +1210,6 @@ fn escape_char<W>(wr: &mut W, value: char) -> Result<()>
escape_str(wr, &s)
}
-fn fmt_f32_or_null<W>(wr: &mut W, value: f32) -> Result<()>
- where W: io::Write,
-{
- match value.classify() {
- FpCategory::Nan | FpCategory::Infinite => try!(wr.write_all(b"null")),
- _ => try!(dtoa::write(wr, value)),
- }
-
- Ok(())
-}
-
-fn fmt_f64_or_null<W>(wr: &mut W, value: f64) -> Result<()>
- where W: io::Write,
-{
- match value.classify() {
- FpCategory::Nan | FpCategory::Infinite => try!(wr.write_all(b"null")),
- _ => try!(dtoa::write(wr, value)),
- }
-
- Ok(())
-}
-
/// Encode the specified struct into a json `[u8]` writer.
#[inline]
pub fn to_writer<W, T>(writer: &mut W, value: &T) -> Result<()>
|
diff --git a/json_tests/tests/test_json.rs b/json_tests/tests/test_json.rs
index 7d7391701..56c7071c4 100644
--- a/json_tests/tests/test_json.rs
+++ b/json_tests/tests/test_json.rs
@@ -1350,10 +1350,8 @@ fn test_serialize_seq_with_no_len() {
let s = serde_json::to_string_pretty(&vec).unwrap();
let expected = indoc!("
[
- [
- ],
- [
- ]
+ [],
+ []
]");
assert_eq!(s, expected);
}
@@ -1439,10 +1437,8 @@ fn test_serialize_map_with_no_len() {
let s = serde_json::to_string_pretty(&map).unwrap();
let expected = indoc!(r#"
{
- "a": {
- },
- "b": {
- }
+ "a": {},
+ "b": {}
}"#);
assert_eq!(s, expected);
}
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
null |
serde-rs__json-115
| 115
|
[
"77"
] |
2016-07-12T05:07:26Z
|
4cc85e55f61e6220b587854209b0d587f2ba1bab
|
Unexpected brackets in to_value of a newtype struct
``` rust
#![feature(custom_derive, plugin)]
#![plugin(serde_macros)]
use std::collections::BTreeMap;
extern crate serde_json;
#[derive(Serialize, Deserialize)]
struct Bar(BTreeMap<String, i32>);
fn main() {
let mut b = Bar(BTreeMap::new());
b.0.insert(String::from("foo"), 123);
// prints {"foo":123}
println!("{}", serde_json::to_string(&b).unwrap());
let mut outer = BTreeMap::new();
outer.insert(String::from("outer"), serde_json::to_value(&b));
// prints {"outer":[{"foo":123}]}
println!("{}", serde_json::to_string(&outer).unwrap());
}
```
I would expect the second print to be `{"outer":{"foo":123}}`.
|
diff --git a/json/src/value.rs b/json/src/value.rs
index f31962db4..af7057850 100644
--- a/json/src/value.rs
+++ b/json/src/value.rs
@@ -611,6 +611,15 @@ impl ser::Serializer for Serializer {
self.serialize_str(variant)
}
+ #[inline]
+ fn serialize_newtype_struct<T>(&mut self,
+ _name: &'static str,
+ value: T) -> Result<(), Self::Error>
+ where T: ser::Serialize,
+ {
+ value.serialize(self)
+ }
+
#[inline]
fn serialize_newtype_variant<T>(&mut self,
_name: &str,
|
diff --git a/json_tests/tests/test_json.rs b/json_tests/tests/test_json.rs
index 6a9442e75..b91691451 100644
--- a/json_tests/tests/test_json.rs
+++ b/json_tests/tests/test_json.rs
@@ -644,6 +644,23 @@ fn test_write_option() {
]);
}
+#[test]
+fn test_write_newtype_struct() {
+ #[derive(Serialize, PartialEq, Debug)]
+ struct Newtype(Map<String, i32>);
+
+ let inner = Newtype(treemap!(String::from("inner") => 123));
+ let outer = treemap!(String::from("outer") => to_value(&inner));
+
+ test_encode_ok(&[
+ (inner, r#"{"inner":123}"#),
+ ]);
+
+ test_encode_ok(&[
+ (outer, r#"{"outer":{"inner":123}}"#),
+ ]);
+}
+
fn test_parse_ok<T>(tests: Vec<(&str, T)>)
where T: Clone + Debug + PartialEq + ser::Serialize + de::Deserialize,
{
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
|
null |
serde-rs__json-114
| 114
|
[
"112"
] |
2016-07-11T18:37:28Z
|
4cc85e55f61e6220b587854209b0d587f2ba1bab
|
Error on large numbers instead of parsing infinity
Not only does it break round tripping, it's also very confusing to get an infinity from a non-infinite number.
|
diff --git a/json/src/de.rs b/json/src/de.rs
index a6dec2420..c296675fc 100644
--- a/json/src/de.rs
+++ b/json/src/de.rs
@@ -404,12 +404,7 @@ impl<R: Read> DeserializerImpl<R> {
let digit = (c - b'0') as i32;
if overflow!(exp * 10 + digit, i32::MAX) {
- // Really big exponent, just ignore the rest.
- while let b'0' ... b'9' = try!(self.peek_or_null()) {
- self.eat_char();
- }
- exp = i32::MAX;
- break;
+ return self.parse_exponent_overflow(pos, significand, pos_exp, visitor);
}
exp = exp * 10 + digit;
@@ -424,29 +419,63 @@ impl<R: Read> DeserializerImpl<R> {
self.visit_f64_from_parts(pos, significand, final_exp, visitor)
}
+ // This cold code should not be inlined into the middle of the hot
+ // exponent-parsing loop above.
+ #[cold]
+ #[inline(never)]
+ // https://github.com/Manishearth/rust-clippy/issues/1086
+ #[cfg_attr(feature = "clippy", allow(if_same_then_else))]
+ fn parse_exponent_overflow<V>(&mut self,
+ pos: bool,
+ significand: u64,
+ pos_exp: bool,
+ mut visitor: V) -> Result<V::Value>
+ where V: de::Visitor,
+ {
+ // Error instead of +/- infinity.
+ if significand != 0 && pos_exp {
+ return Err(self.error(ErrorCode::NumberOutOfRange));
+ }
+
+ while let b'0' ... b'9' = try!(self.peek_or_null()) {
+ self.eat_char();
+ }
+ visitor.visit_f64(if pos { 0.0 } else { -0.0 })
+ }
+
fn visit_f64_from_parts<V>(&mut self,
pos: bool,
significand: u64,
- exponent: i32,
+ mut exponent: i32,
mut visitor: V) -> Result<V::Value>
where V: de::Visitor,
{
- let f = match POW10.get(exponent.abs() as usize) {
- Some(pow) => {
- if exponent >= 0 {
- significand as f64 * pow
- } else {
- significand as f64 / pow
+ let mut f = significand as f64;
+ loop {
+ match POW10.get(exponent.abs() as usize) {
+ Some(&pow) => {
+ if exponent >= 0 {
+ f *= pow;
+ if f.is_infinite() {
+ return Err(self.error(ErrorCode::NumberOutOfRange));
+ }
+ } else {
+ f /= pow;
+ }
+ break;
}
- }
- None => {
- if exponent >= 0 && significand != 0 {
- f64::INFINITY
- } else {
- 0.0
+ None => {
+ if f == 0.0 {
+ break;
+ }
+ if exponent >= 0 {
+ return Err(self.error(ErrorCode::NumberOutOfRange));
+ }
+ f /= 1e308;
+ exponent += 308;
}
}
- };
+ }
visitor.visit_f64(if pos { f } else { -f })
}
diff --git a/json/src/error.rs b/json/src/error.rs
index e984e6351..8c0d5b60c 100644
--- a/json/src/error.rs
+++ b/json/src/error.rs
@@ -68,6 +68,9 @@ pub enum ErrorCode {
/// Invalid number.
InvalidNumber,
+ /// Number is bigger than the maximum value of its type.
+ NumberOutOfRange,
+
/// Invalid unicode code point.
InvalidUnicodeCodePoint,
@@ -105,6 +108,7 @@ impl fmt::Display for ErrorCode {
ErrorCode::ExpectedSomeValue => "expected value".fmt(f),
ErrorCode::InvalidEscape => "invalid escape".fmt(f),
ErrorCode::InvalidNumber => "invalid number".fmt(f),
+ ErrorCode::NumberOutOfRange => "number out of range".fmt(f),
ErrorCode::InvalidUnicodeCodePoint => "invalid unicode code point".fmt(f),
ErrorCode::KeyMustBeAString => "key must be a string".fmt(f),
ErrorCode::LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape".fmt(f),
|
diff --git a/json_tests/tests/test_json.rs b/json_tests/tests/test_json.rs
index 6a9442e75..3bc52eac5 100644
--- a/json_tests/tests/test_json.rs
+++ b/json_tests/tests/test_json.rs
@@ -771,6 +771,29 @@ fn test_parse_number_errors() {
("1e", Error::Syntax(ErrorCode::InvalidNumber, 1, 2)),
("1e+", Error::Syntax(ErrorCode::InvalidNumber, 1, 3)),
("1a", Error::Syntax(ErrorCode::TrailingCharacters, 1, 2)),
+ ("100e777777777777777777777777777", Error::Syntax(ErrorCode::NumberOutOfRange, 1, 14)),
+ ("-100e777777777777777777777777777", Error::Syntax(ErrorCode::NumberOutOfRange, 1, 15)),
+ ("1000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000", // 1e309
+ Error::Syntax(ErrorCode::NumberOutOfRange, 1, 310)),
+ ("1000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ .0e9", // 1e309
+ Error::Syntax(ErrorCode::NumberOutOfRange, 1, 305)),
+ ("1000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ e9", // 1e309
+ Error::Syntax(ErrorCode::NumberOutOfRange, 1, 303)),
]);
}
@@ -802,6 +825,7 @@ fn test_parse_negative_zero() {
"-0e2",
"-0.0e2",
"-1e-400",
+ "-1e-4000000000000000000000000000000000000000000000000",
] {
assert_eq!(0, from_str::<u32>(negative_zero).unwrap());
assert!(from_str::<f64>(negative_zero).unwrap().is_sign_negative(),
@@ -833,11 +857,34 @@ fn test_parse_f64() {
(&format!("{:?}", (u64::MAX as f64) + 1.0), (u64::MAX as f64) + 1.0),
(&format!("{:?}", f64::EPSILON), f64::EPSILON),
("0.0000000000000000000000000000000000000000000000000123e50", 1.23),
- ("100e777777777777777777777777777", f64::INFINITY),
- ("-100e777777777777777777777777777", f64::NEG_INFINITY),
("100e-777777777777777777777777777", 0.0),
("1010101010101010101010101010101010101010", 10101010101010101010e20),
("0.1010101010101010101010101010101010101010", 0.1010101010101010101),
+ ("0e1000000000000000000000000000000000000000000000", 0.0),
+ ("1000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 00000000", 1e308),
+ ("1000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ .0e8", 1e308),
+ ("1000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ e8", 1e308),
+ ("1000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000000000000000000000000000000000000000000000\
+ 000000000000000000e-10", 1e308),
]);
}
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
|
null |
serde-rs__json-111
| 111
|
[
"103"
] |
2016-07-11T07:52:56Z
|
e059d03aea557bbd2c53ff5af18951c65da8f509
|
Rename feature "nightly-testing" to "unstable-testing"
See https://github.com/serde-rs/serde/issues/404.
> From what I understand, the community has started to use the feature `unstable*` instead of `nightly*` for things that may depend on the nightly compiler. If this is the case, when we do 0.8, we should consider renaming this feature.
|
diff --git a/.travis.yml b/.travis.yml
index f910ad7b1..d567d1127 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -32,7 +32,7 @@ script:
(cd json && travis-cargo build) &&
(cd json && travis-cargo --only nightly test) &&
(cd json_tests && travis-cargo --skip nightly test -- --features with-syntex --no-default-features) &&
- (cd json_tests && travis-cargo --only nightly test -- --features nightly-testing) &&
+ (cd json_tests && travis-cargo --only nightly test -- --features unstable-testing) &&
(cd json && travis-cargo --only stable doc)
else
(cd json_tests && travis-cargo bench)
diff --git a/json/Cargo.toml b/json/Cargo.toml
index 5ec636795..aaa75f88a 100644
--- a/json/Cargo.toml
+++ b/json/Cargo.toml
@@ -10,7 +10,7 @@ readme = "../README.md"
keywords = ["json", "serde", "serialization"]
[features]
-nightly-testing = ["clippy"]
+unstable-testing = ["clippy"]
preserve_order = ["linked-hash-map", "linked-hash-map/serde_impl"]
[dependencies]
|
diff --git a/json_tests/Cargo.toml b/json_tests/Cargo.toml
index 8775683db..facb98908 100644
--- a/json_tests/Cargo.toml
+++ b/json_tests/Cargo.toml
@@ -7,7 +7,7 @@ build = "build.rs"
[features]
default = ["serde_macros"]
with-syntex = ["syntex", "serde_codegen", "indoc/with-syntex"]
-nightly-testing = ["clippy", "serde_json/clippy"]
+unstable-testing = ["clippy", "serde_json/clippy"]
[build-dependencies]
indoc = "*"
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
|
null |
serde-rs__json-110
| 110
|
[
"108",
"109"
] |
2016-07-11T07:40:17Z
|
e059d03aea557bbd2c53ff5af18951c65da8f509
|
Parsing floats is slow
These two lines are extremely expensive:

We can entirely avoid the division and multiplication by using a lookup table, or some other better approach.
Long integer causes the following byte to be lost
``` rust
serde_json::from_str::<Vec<f64>>("[123456789012345678901]").unwrap();
```
```
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value:
Syntax("EOF while parsing a list", 1, 23)'
```
Here is the buggy code: [json/src/de.rs#L294-L302](https://github.com/serde-rs/json/blob/e059d03aea557bbd2c53ff5af18951c65da8f509/json/src/de.rs#L294-L302). The first one needs to be a peek.
|
diff --git a/json/src/de.rs b/json/src/de.rs
index ab3e3e3a2..dece310d3 100644
--- a/json/src/de.rs
+++ b/json/src/de.rs
@@ -2,9 +2,8 @@
//!
//! This module provides for JSON deserialization with the type `Deserializer`.
-use std::i32;
+use std::{f64, i32, i64, u64};
use std::io;
-use std::str;
use std::marker::PhantomData;
use serde::de;
@@ -87,12 +86,9 @@ struct DeserializerImpl<R: Read> {
str_buf: Vec<u8>,
}
-macro_rules! try_or_invalid {
- ($self_:expr, $e:expr) => {
- match $e {
- Some(v) => v,
- None => { return Err($self_.error(ErrorCode::InvalidNumber)); }
- }
+macro_rules! overflow {
+ ($a:ident * 10 + $b:ident, $c:expr) => {
+ $a >= $c / 10 && ($a > $c / 10 || $b > $c % 10)
}
}
@@ -248,29 +244,27 @@ impl<R: Read> DeserializerImpl<R> {
self.parse_number(pos, 0, visitor)
}
}
- },
+ }
c @ b'1' ... b'9' => {
- let mut res: u64 = (c as u64) - ('0' as u64);
+ let mut res = (c - b'0') as u64;
loop {
match try!(self.peek_or_null()) {
c @ b'0' ... b'9' => {
self.eat_char();
-
- let digit = (c as u64) - ('0' as u64);
+ let digit = (c - b'0') as u64;
// We need to be careful with overflow. If we can, try to keep the
// number as a `u64` until we grow too large. At that point, switch to
// parsing the value as a `f64`.
- match res.checked_mul(10).and_then(|val| val.checked_add(digit)) {
- Some(res_) => { res = res_; }
- None => {
- return self.parse_float(
- pos,
- (res as f64) * 10.0 + (digit as f64),
- visitor);
- }
+ if overflow!(res * 10 + digit, u64::MAX) {
+ return self.parse_long_integer(
+ pos,
+ res, 1, // res * 10^1
+ visitor);
}
+
+ res = res * 10 + digit;
}
_ => {
return self.parse_number(pos, res, visitor);
@@ -284,36 +278,29 @@ impl<R: Read> DeserializerImpl<R> {
}
}
- fn parse_float<V>(&mut self,
- pos: bool,
- mut res: f64,
- mut visitor: V) -> Result<V::Value>
+ fn parse_long_integer<V>(&mut self,
+ pos: bool,
+ significand: u64,
+ mut exponent: i32,
+ visitor: V) -> Result<V::Value>
where V: de::Visitor,
{
loop {
- match try!(self.next_char_or_null()) {
- c @ b'0' ... b'9' => {
- let digit = (c as u64) - ('0' as u64);
-
- res *= 10.0;
- res += digit as f64;
+ match try!(self.peek_or_null()) {
+ b'0' ... b'9' => {
+ self.eat_char();
+ // This could overflow... if your integer is gigabytes long.
+ // Ignore that possibility.
+ exponent += 1;
+ }
+ b'.' => {
+ return self.parse_decimal(pos, significand, exponent, visitor);
+ }
+ b'e' | b'E' => {
+ return self.parse_exponent(pos, significand, exponent, visitor);
}
_ => {
- match try!(self.peek_or_null()) {
- b'.' => {
- return self.parse_decimal(pos, res, visitor);
- }
- b'e' | b'E' => {
- return self.parse_exponent(pos, res, visitor);
- }
- _ => {
- if !pos {
- res = -res;
- }
-
- return visitor.visit_f64(res);
- }
- }
+ return self.visit_f64_from_parts(pos, significand, exponent, visitor);
}
}
}
@@ -321,28 +308,28 @@ impl<R: Read> DeserializerImpl<R> {
fn parse_number<V>(&mut self,
pos: bool,
- res: u64,
+ significand: u64,
mut visitor: V) -> Result<V::Value>
where V: de::Visitor,
{
match try!(self.peek_or_null()) {
b'.' => {
- self.parse_decimal(pos, res as f64, visitor)
+ self.parse_decimal(pos, significand, 0, visitor)
}
b'e' | b'E' => {
- self.parse_exponent(pos, res as f64, visitor)
+ self.parse_exponent(pos, significand, 0, visitor)
}
_ => {
if pos {
- visitor.visit_u64(res)
+ visitor.visit_u64(significand)
} else {
- let res_i64 = (res as i64).wrapping_neg();
+ let neg = (significand as i64).wrapping_neg();
// Convert into a float if we underflow.
- if res_i64 > 0 {
- visitor.visit_f64(-(res as f64))
+ if neg > 0 {
+ visitor.visit_f64(-(significand as f64))
} else {
- visitor.visit_i64(res_i64)
+ visitor.visit_i64(neg)
}
}
}
@@ -351,48 +338,51 @@ impl<R: Read> DeserializerImpl<R> {
fn parse_decimal<V>(&mut self,
pos: bool,
- mut res: f64,
- mut visitor: V) -> Result<V::Value>
+ mut significand: u64,
+ mut exponent: i32,
+ visitor: V) -> Result<V::Value>
where V: de::Visitor,
{
self.eat_char();
- let mut dec = 0.1;
+ let mut at_least_one_digit = false;
+ while let c @ b'0' ... b'9' = try!(self.peek_or_null()) {
+ self.eat_char();
+ let digit = (c - b'0') as u64;
+ at_least_one_digit = true;
- // Make sure a digit follows the decimal place.
- match try!(self.next_char_or_null()) {
- c @ b'0' ... b'9' => {
- res += (((c as u64) - (b'0' as u64)) as f64) * dec;
+ if overflow!(significand * 10 + digit, u64::MAX) {
+ // The next multiply/add would overflow, so just ignore all
+ // further digits.
+ while let b'0' ... b'9' = try!(self.peek_or_null()) {
+ self.eat_char();
+ }
+ break;
}
- _ => { return Err(self.error(ErrorCode::InvalidNumber)); }
- }
- while let c @ b'0' ... b'9' = try!(self.peek_or_null()) {
- self.eat_char();
+ significand = significand * 10 + digit;
+ exponent -= 1;
+ }
- dec /= 10.0;
- res += (((c as u64) - (b'0' as u64)) as f64) * dec;
+ if !at_least_one_digit {
+ return Err(self.peek_error(ErrorCode::InvalidNumber));
}
match try!(self.peek_or_null()) {
b'e' | b'E' => {
- self.parse_exponent(pos, res, visitor)
+ self.parse_exponent(pos, significand, exponent, visitor)
}
_ => {
- if pos {
- visitor.visit_f64(res)
- } else {
- visitor.visit_f64(-res)
- }
+ self.visit_f64_from_parts(pos, significand, exponent, visitor)
}
}
-
}
fn parse_exponent<V>(&mut self,
pos: bool,
- mut res: f64,
- mut visitor: V) -> Result<V::Value>
+ significand: u64,
+ starting_exp: i32,
+ visitor: V) -> Result<V::Value>
where V: de::Visitor,
{
self.eat_char();
@@ -404,35 +394,60 @@ impl<R: Read> DeserializerImpl<R> {
};
// Make sure a digit follows the exponent place.
- let mut expi = match try!(self.next_char_or_null()) {
- c @ b'0' ... b'9' => { (c as u64) - (b'0' as u64) }
+ let mut exp = match try!(self.next_char_or_null()) {
+ c @ b'0' ... b'9' => { (c - b'0') as i32 }
_ => { return Err(self.error(ErrorCode::InvalidNumber)); }
};
while let c @ b'0' ... b'9' = try!(self.peek_or_null()) {
self.eat_char();
+ let digit = (c - b'0') as i32;
+
+ if overflow!(exp * 10 + digit, i32::MAX) {
+ // Really big exponent, just ignore the rest.
+ while let b'0' ... b'9' = try!(self.peek_or_null()) {
+ self.eat_char();
+ }
+ exp = i32::MAX;
+ break;
+ }
- expi = try_or_invalid!(self, expi.checked_mul(10));
- expi = try_or_invalid!(self, expi.checked_add((c as u64) - (b'0' as u64)));
+ exp = exp * 10 + digit;
}
- let expf = if expi <= i32::MAX as u64 {
- 10_f64.powi(expi as i32)
+ let final_exp = if pos_exp {
+ starting_exp.saturating_add(exp)
} else {
- return Err(self.peek_error(ErrorCode::InvalidNumber));
+ starting_exp.saturating_sub(exp)
};
- if pos_exp {
- res *= expf;
- } else {
- res /= expf;
- }
+ self.visit_f64_from_parts(pos, significand, final_exp, visitor)
+ }
- if pos {
- visitor.visit_f64(res)
- } else {
- visitor.visit_f64(-res)
- }
+ fn visit_f64_from_parts<V>(&mut self,
+ pos: bool,
+ significand: u64,
+ exponent: i32,
+ mut visitor: V) -> Result<V::Value>
+ where V: de::Visitor,
+ {
+ let f = match POW10.get(exponent.abs() as usize) {
+ Some(pow) => {
+ if exponent >= 0 {
+ significand as f64 * pow
+ } else {
+ significand as f64 / pow
+ }
+ }
+ None => {
+ if exponent >= 0 && significand != 0 {
+ f64::INFINITY
+ } else {
+ 0.0
+ }
+ }
+ };
+ visitor.visit_f64(if pos { f } else { -f })
}
fn parse_object_colon(&mut self) -> Result<()> {
@@ -449,6 +464,40 @@ impl<R: Read> DeserializerImpl<R> {
}
}
+static POW10: [f64; 309] = [
+ 1e000, 1e001, 1e002, 1e003, 1e004, 1e005, 1e006, 1e007, 1e008, 1e009,
+ 1e010, 1e011, 1e012, 1e013, 1e014, 1e015, 1e016, 1e017, 1e018, 1e019,
+ 1e020, 1e021, 1e022, 1e023, 1e024, 1e025, 1e026, 1e027, 1e028, 1e029,
+ 1e030, 1e031, 1e032, 1e033, 1e034, 1e035, 1e036, 1e037, 1e038, 1e039,
+ 1e040, 1e041, 1e042, 1e043, 1e044, 1e045, 1e046, 1e047, 1e048, 1e049,
+ 1e050, 1e051, 1e052, 1e053, 1e054, 1e055, 1e056, 1e057, 1e058, 1e059,
+ 1e060, 1e061, 1e062, 1e063, 1e064, 1e065, 1e066, 1e067, 1e068, 1e069,
+ 1e070, 1e071, 1e072, 1e073, 1e074, 1e075, 1e076, 1e077, 1e078, 1e079,
+ 1e080, 1e081, 1e082, 1e083, 1e084, 1e085, 1e086, 1e087, 1e088, 1e089,
+ 1e090, 1e091, 1e092, 1e093, 1e094, 1e095, 1e096, 1e097, 1e098, 1e099,
+ 1e100, 1e101, 1e102, 1e103, 1e104, 1e105, 1e106, 1e107, 1e108, 1e109,
+ 1e110, 1e111, 1e112, 1e113, 1e114, 1e115, 1e116, 1e117, 1e118, 1e119,
+ 1e120, 1e121, 1e122, 1e123, 1e124, 1e125, 1e126, 1e127, 1e128, 1e129,
+ 1e130, 1e131, 1e132, 1e133, 1e134, 1e135, 1e136, 1e137, 1e138, 1e139,
+ 1e140, 1e141, 1e142, 1e143, 1e144, 1e145, 1e146, 1e147, 1e148, 1e149,
+ 1e150, 1e151, 1e152, 1e153, 1e154, 1e155, 1e156, 1e157, 1e158, 1e159,
+ 1e160, 1e161, 1e162, 1e163, 1e164, 1e165, 1e166, 1e167, 1e168, 1e169,
+ 1e170, 1e171, 1e172, 1e173, 1e174, 1e175, 1e176, 1e177, 1e178, 1e179,
+ 1e180, 1e181, 1e182, 1e183, 1e184, 1e185, 1e186, 1e187, 1e188, 1e189,
+ 1e190, 1e191, 1e192, 1e193, 1e194, 1e195, 1e196, 1e197, 1e198, 1e199,
+ 1e200, 1e201, 1e202, 1e203, 1e204, 1e205, 1e206, 1e207, 1e208, 1e209,
+ 1e210, 1e211, 1e212, 1e213, 1e214, 1e215, 1e216, 1e217, 1e218, 1e219,
+ 1e220, 1e221, 1e222, 1e223, 1e224, 1e225, 1e226, 1e227, 1e228, 1e229,
+ 1e230, 1e231, 1e232, 1e233, 1e234, 1e235, 1e236, 1e237, 1e238, 1e239,
+ 1e240, 1e241, 1e242, 1e243, 1e244, 1e245, 1e246, 1e247, 1e248, 1e249,
+ 1e250, 1e251, 1e252, 1e253, 1e254, 1e255, 1e256, 1e257, 1e258, 1e259,
+ 1e260, 1e261, 1e262, 1e263, 1e264, 1e265, 1e266, 1e267, 1e268, 1e269,
+ 1e270, 1e271, 1e272, 1e273, 1e274, 1e275, 1e276, 1e277, 1e278, 1e279,
+ 1e280, 1e281, 1e282, 1e283, 1e284, 1e285, 1e286, 1e287, 1e288, 1e289,
+ 1e290, 1e291, 1e292, 1e293, 1e294, 1e295, 1e296, 1e297, 1e298, 1e299,
+ 1e300, 1e301, 1e302, 1e303, 1e304, 1e305, 1e306, 1e307, 1e308,
+];
+
impl<R: Read> de::Deserializer for DeserializerImpl<R> {
type Error = Error;
|
diff --git a/json_tests/tests/test_json.rs b/json_tests/tests/test_json.rs
index 391b97452..6faaaa12d 100644
--- a/json_tests/tests/test_json.rs
+++ b/json_tests/tests/test_json.rs
@@ -750,11 +750,14 @@ fn test_parse_number_errors() {
(".", Error::Syntax(ErrorCode::ExpectedSomeValue, 1, 1)),
("-", Error::Syntax(ErrorCode::InvalidNumber, 1, 1)),
("00", Error::Syntax(ErrorCode::InvalidNumber, 1, 2)),
+ ("0x80", Error::Syntax(ErrorCode::TrailingCharacters, 1, 2)),
+ ("\\0", Error::Syntax(ErrorCode::ExpectedSomeValue, 1, 1)),
("1.", Error::Syntax(ErrorCode::InvalidNumber, 1, 2)),
+ ("1.a", Error::Syntax(ErrorCode::InvalidNumber, 1, 3)),
+ ("1.e1", Error::Syntax(ErrorCode::InvalidNumber, 1, 3)),
("1e", Error::Syntax(ErrorCode::InvalidNumber, 1, 2)),
("1e+", Error::Syntax(ErrorCode::InvalidNumber, 1, 3)),
("1a", Error::Syntax(ErrorCode::TrailingCharacters, 1, 2)),
- ("1e777777777777777777777777777", Error::Syntax(ErrorCode::InvalidNumber, 1, 22)),
]);
}
@@ -781,10 +784,16 @@ fn test_parse_u64() {
#[test]
fn test_parse_negative_zero() {
- assert_eq!(0, from_str::<u32>("-0").unwrap());
- assert_eq!(0, from_str::<u32>("-0.0").unwrap());
- assert_eq!(0, from_str::<u32>("-0e2").unwrap());
- assert_eq!(0, from_str::<u32>("-0.0e2").unwrap());
+ for negative_zero in &[
+ "-0.0",
+ "-0e2",
+ "-0.0e2",
+ "-1e-400",
+ ] {
+ assert_eq!(0, from_str::<u32>(negative_zero).unwrap());
+ assert!(from_str::<f64>(negative_zero).unwrap().is_sign_negative(),
+ "should have been negative: {:?}", negative_zero);
+ }
}
#[test]
@@ -810,6 +819,12 @@ fn test_parse_f64() {
(&format!("{:?}", (i64::MIN as f64) - 1.0), (i64::MIN as f64) - 1.0),
(&format!("{:?}", (u64::MAX as f64) + 1.0), (u64::MAX as f64) + 1.0),
(&format!("{:?}", f64::EPSILON), f64::EPSILON),
+ ("0.0000000000000000000000000000000000000000000000000123e50", 1.23),
+ ("100e777777777777777777777777777", f64::INFINITY),
+ ("-100e777777777777777777777777777", f64::NEG_INFINITY),
+ ("100e-777777777777777777777777777", 0.0),
+ ("1010101010101010101010101010101010101010", 10101010101010101010e20),
+ ("0.1010101010101010101010101010101010101010", 0.1010101010101010101),
]);
}
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
|
null |
serde-rs__json-93
| 93
|
[
"53"
] |
2016-07-03T16:48:14Z
|
I'd suggest `build` as the new name because it's shorter than `to_value` while being at least as clear.
:+1: for `build`. Same thing for ArrayBuilder.
+1 to `build`, especially since it's a builder.
|
12f617d966e2169bfe90bb26397bc1ea7c124501
|
ObjectBuilder: Rename unwrap?
Correct me if I'm wrong, but `ObjectBuilder::unwrap` doesn't actually `panic!()`, right? If so, I think it should be renamed to `to_value` or something like that.
|
diff --git a/json/src/builder.rs b/json/src/builder.rs
index 142a3e458..8a00b7222 100644
--- a/json/src/builder.rs
+++ b/json/src/builder.rs
@@ -30,7 +30,7 @@
//! builder.insert("x", 3).insert("y", 4)
//! })
//! })
-//! .unwrap();
+//! .build();
//! ```
use serde::ser;
@@ -49,7 +49,7 @@ impl ArrayBuilder {
}
/// Return the constructed `Value`.
- pub fn unwrap(self) -> Value {
+ pub fn build(self) -> Value {
Value::Array(self.array)
}
@@ -65,7 +65,7 @@ impl ArrayBuilder {
F: FnOnce(ArrayBuilder) -> ArrayBuilder
{
let builder = ArrayBuilder::new();
- self.array.push(f(builder).unwrap());
+ self.array.push(f(builder).build());
self
}
@@ -75,7 +75,7 @@ impl ArrayBuilder {
F: FnOnce(ObjectBuilder) -> ObjectBuilder
{
let builder = ObjectBuilder::new();
- self.array.push(f(builder).unwrap());
+ self.array.push(f(builder).build());
self
}
}
@@ -93,7 +93,7 @@ impl ObjectBuilder {
}
/// Return the constructed `Value`.
- pub fn unwrap(self) -> Value {
+ pub fn build(self) -> Value {
Value::Object(self.object)
}
@@ -113,7 +113,7 @@ impl ObjectBuilder {
F: FnOnce(ArrayBuilder) -> ArrayBuilder
{
let builder = ArrayBuilder::new();
- self.object.insert(key.into(), f(builder).unwrap());
+ self.object.insert(key.into(), f(builder).build());
self
}
@@ -124,7 +124,7 @@ impl ObjectBuilder {
F: FnOnce(ObjectBuilder) -> ObjectBuilder
{
let builder = ObjectBuilder::new();
- self.object.insert(key.into(), f(builder).unwrap());
+ self.object.insert(key.into(), f(builder).build());
self
}
}
|
diff --git a/json_tests/tests/test_json_builder.rs b/json_tests/tests/test_json_builder.rs
index 948aa511e..189b0d3a3 100644
--- a/json_tests/tests/test_json_builder.rs
+++ b/json_tests/tests/test_json_builder.rs
@@ -4,19 +4,19 @@ use serde_json::builder::{ArrayBuilder, ObjectBuilder};
#[test]
fn test_array_builder() {
- let value = ArrayBuilder::new().unwrap();
+ let value = ArrayBuilder::new().build();
assert_eq!(value, Value::Array(Vec::new()));
let value = ArrayBuilder::new()
.push(1)
.push(2)
.push(3)
- .unwrap();
+ .build();
assert_eq!(value, Value::Array(vec!(Value::U64(1), Value::U64(2), Value::U64(3))));
let value = ArrayBuilder::new()
.push_array(|bld| bld.push(1).push(2).push(3))
- .unwrap();
+ .build();
assert_eq!(value, Value::Array(vec!(Value::Array(vec!(Value::U64(1), Value::U64(2), Value::U64(3))))));
let value = ArrayBuilder::new()
@@ -24,7 +24,7 @@ fn test_array_builder() {
bld
.insert("a".to_string(), 1)
.insert("b".to_string(), 2))
- .unwrap();
+ .build();
let mut map = Map::new();
map.insert("a".to_string(), Value::U64(1));
@@ -34,13 +34,13 @@ fn test_array_builder() {
#[test]
fn test_object_builder() {
- let value = ObjectBuilder::new().unwrap();
+ let value = ObjectBuilder::new().build();
assert_eq!(value, Value::Object(Map::new()));
let value = ObjectBuilder::new()
.insert("a".to_string(), 1)
.insert("b".to_string(), 2)
- .unwrap();
+ .build();
let mut map = Map::new();
map.insert("a".to_string(), Value::U64(1));
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
null |
serde-rs__json-85
| 85
|
[
"65",
"51"
] |
2016-06-25T21:51:25Z
|
A PR would be appreciated!
|
4ef396bf6af251ae835c22db78bc08fca91c8dd6
|
Correctly escape ASCII control characters in strings
This patch escapes ASCII control characters in the range 0x00...0x1f, in accordance with the JSON spec.
Fixes #51
Need to escape ASCII control characters
Serializing control characters such as `"\x01"` results in these characters being passed through, ie `"\"\x01\""` rather than the correct `"\"\\u0001\""`. The [JSON spec](https://tools.ietf.org/html/rfc7159#section-7) is quite clear that these characters must be escaped, and at least one JSON implementation (Swift's) rejects the unescaped variant as invalid JSON.
I'm happy to provide a patch, not sure if you prefer that or to write your own.
|
diff --git a/json/src/ser.rs b/json/src/ser.rs
index e2d4479e2..bbac3cf74 100644
--- a/json/src/ser.rs
+++ b/json/src/ser.rs
@@ -504,6 +504,7 @@ pub fn escape_bytes<W>(wr: &mut W, bytes: &[u8]) -> Result<()>
b'\n' => b"\\n",
b'\r' => b"\\r",
b'\t' => b"\\t",
+ b'\x00' ... b'\x1F' => b"\\u",
_ => { continue; }
};
@@ -512,6 +513,9 @@ pub fn escape_bytes<W>(wr: &mut W, bytes: &[u8]) -> Result<()>
}
try!(wr.write_all(escaped));
+ if escaped[1] == b'u' {
+ try!(write!(wr, "{:04x}", *byte));
+ }
start = i + 1;
}
|
diff --git a/json_tests/tests/test_json.rs b/json_tests/tests/test_json.rs
index faf2f8d7f..f67a3eef2 100644
--- a/json_tests/tests/test_json.rs
+++ b/json_tests/tests/test_json.rs
@@ -461,7 +461,7 @@ fn test_write_object() {
let complex_obj = Value::Object(treemap!(
"b".to_string() => Value::Array(vec![
- Value::Object(treemap!("c".to_string() => Value::String("\x0c\r".to_string()))),
+ Value::Object(treemap!("c".to_string() => Value::String("\x0c\x1f\r".to_string()))),
Value::Object(treemap!("d".to_string() => Value::String("".to_string())))
])
));
@@ -471,7 +471,7 @@ fn test_write_object() {
complex_obj.clone(),
"{\
\"b\":[\
- {\"c\":\"\\f\\r\"},\
+ {\"c\":\"\\f\\u001f\\r\"},\
{\"d\":\"\"}\
]\
}"
@@ -485,7 +485,7 @@ fn test_write_object() {
{
"b": [
{
- "c": "\f\r"
+ "c": "\f\u001f\r"
},
{
"d": ""
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
null |
serde-rs__json-41
| 41
|
[
"9"
] |
2016-02-27T15:14:29Z
|
A belated sure! That would be awesome!
|
7bc9b0a98ec65b90f8c4600d5966d1ca0679b089
|
Consider using JSON pointers
JSON values provide a convenience to look up nested values called [`Value.lookup`](http://serde-rs.github.io/json/serde_json/value/enum.Value.html#method.lookup). The path is given separated by dots. It is impossible to escape dots in key names with the current method. I propose to use JSON pointers as described in [RFC6901](https://tools.ietf.org/html/rfc6901) as they provide a standard way to access nested values.
If you want to use JSON pointers I can also implement the change.
|
diff --git a/json/Cargo.toml b/json/Cargo.toml
index 3c4765c52..0a82dc7c4 100644
--- a/json/Cargo.toml
+++ b/json/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_json"
-version = "0.7.0"
+version = "0.7.1"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "A JSON serialization file format"
diff --git a/json/src/value.rs b/json/src/value.rs
index efffb9262..bdac81927 100644
--- a/json/src/value.rs
+++ b/json/src/value.rs
@@ -98,6 +98,8 @@ impl Value {
Some(target)
}
+ /// **Deprecated**: Use `Value.pointer()` and pointer syntax instead.
+ ///
/// Looks up a value by path.
///
/// This is a convenience method that splits the path by `'.'`
@@ -120,6 +122,46 @@ impl Value {
Some(target)
}
+ /// Looks up a value by a JSON Pointer.
+ ///
+ /// JSON Pointer defines a string syntax for identifying a specific value
+ /// within a JavaScript Object Notation (JSON) document.
+ ///
+ /// A Pointer is a Unicode string with the reference tokens separated by `/`.
+ /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
+ /// addressed value is returned and if there is no such value `None` is
+ /// returned.
+ ///
+ /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
+ pub fn pointer<'a>(&'a self, pointer: &str) -> Option<&'a Value> {
+ fn parse_index(s: &str) -> Option<usize> {
+ if s.starts_with("+") || (s.starts_with("0") && s.len() != 1) {
+ return None
+ }
+ s.parse().ok()
+ }
+ if pointer == "" {
+ return Some(self);
+ }
+ if !pointer.starts_with('/') {
+ return None;
+ }
+ let mut target = self;
+ for escaped_token in pointer.split('/').skip(1) {
+ let token = escaped_token.replace("~1", "/").replace("~0", "~");
+ let target_opt = match target {
+ &Value::Object(ref map) => map.get(&token[..]),
+ &Value::Array(ref list) => parse_index(&token[..])
+ .and_then(|x| list.get(x)),
+ _ => return None,
+ };
+ if let Some(t) = target_opt {
+ target = t;
+ } else { return None }
+ }
+ Some(target)
+ }
+
/// If the `Value` is an Object, performs a depth-first search until
/// a value associated with the provided key is found. If no value is found
/// or the `Value` is not an Object, returns None.
|
diff --git a/json_tests/tests/test_json.rs b/json_tests/tests/test_json.rs
index fa765fd98..716b7195b 100644
--- a/json_tests/tests/test_json.rs
+++ b/json_tests/tests/test_json.rs
@@ -1447,3 +1447,40 @@ fn test_json_stream_empty() {
assert!(parsed.next().is_none());
}
+
+#[test]
+fn test_json_pointer() {
+ // Test case taken from https://tools.ietf.org/html/rfc6901#page-5
+ let data: Value = serde_json::from_str(r#"{
+ "foo": ["bar", "baz"],
+ "": 0,
+ "a/b": 1,
+ "c%d": 2,
+ "e^f": 3,
+ "g|h": 4,
+ "i\\j": 5,
+ "k\"l": 6,
+ " ": 7,
+ "m~n": 8
+ }"#).unwrap();
+ assert_eq!(data.pointer("").unwrap(), &data);
+ assert_eq!(data.pointer("/foo").unwrap(),
+ &Value::Array(vec![Value::String("bar".to_owned()),
+ Value::String("baz".to_owned())]));
+ assert_eq!(data.pointer("/foo/0").unwrap(),
+ &Value::String("bar".to_owned()));
+ assert_eq!(data.pointer("/").unwrap(), &Value::U64(0));
+ assert_eq!(data.pointer("/a~1b").unwrap(), &Value::U64(1));
+ assert_eq!(data.pointer("/c%d").unwrap(), &Value::U64(2));
+ assert_eq!(data.pointer("/e^f").unwrap(), &Value::U64(3));
+ assert_eq!(data.pointer("/g|h").unwrap(), &Value::U64(4));
+ assert_eq!(data.pointer("/i\\j").unwrap(), &Value::U64(5));
+ assert_eq!(data.pointer("/k\"l").unwrap(), &Value::U64(6));
+ assert_eq!(data.pointer("/ ").unwrap(), &Value::U64(7));
+ assert_eq!(data.pointer("/m~0n").unwrap(), &Value::U64(8));
+ // Invalid pointers
+ assert!(data.pointer("/unknown").is_none());
+ assert!(data.pointer("/e^f/ertz").is_none());
+ assert!(data.pointer("/foo/00").is_none());
+ assert!(data.pointer("/foo/01").is_none());
+}
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
null |
serde-rs__json-31
| 31
|
[
"30"
] |
2016-01-23T12:59:26Z
|
b7a6592d8cb76c2eeef6e25c8f7b374883a0edbc
|
Missing () field in a struct is not reported as an error
If a `()` struct field is missing when deserializing JSON input, no error is reported. This means there's no distinction between `()` and `Option<()>`.
This is related to issue #29, which is about missing `Vec<_>` fields going unreported, and issue #22, which is about `serde_json` reporting missing fields incorrectly in general.
The following program demonstrates the behavior for the `()` case.
Expected output: (none)
Actual output:
```
thread '<main>' panicked at 'Got unexpected OK result: Ok(Foo { a: () })', main.rs:91
Process didn't exit successfully: `/home/craig/art/serde_json-cmbrandenburg/issue_x_test/target/debug/issue_x_test` (exit code: 101)
```
```
extern crate serde;
extern crate serde_json;
#[derive(Debug)]
struct Foo {
a: (),
}
impl serde::Deserialize for Foo {
fn deserialize<D>(d: &mut D) -> Result<Self, D::Error>
where D: serde::Deserializer
{
enum Field {
A,
}
impl serde::Deserialize for Field {
fn deserialize<D>(d: &mut D) -> Result<Self, D::Error>
where D: serde::Deserializer
{
struct Visitor;
impl serde::de::Visitor for Visitor {
type Value = Field;
fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E>
where E: serde::de::Error
{
match value {
"a" => Ok(Field::A),
_ => Err(E::unknown_field(value)),
}
}
}
d.visit(Visitor)
}
}
struct Visitor;
impl serde::de::Visitor for Visitor {
type Value = Foo;
fn visit_map<V>(&mut self, mut visitor: V) -> Result<Foo, V::Error>
where V: serde::de::MapVisitor
{
let mut a = None;
loop {
match try!(visitor.visit_key()) {
Some(Field::A) => {
a = Some(try!(visitor.visit_value()));
}
None => {
break;
}
}
}
try!(visitor.end());
let a = match a {
Some(x) => x,
None => try!(visitor.missing_field("a")),
};
let v = Foo { a: a };
Ok(v)
}
}
static FIELDS: &'static [&'static str] = &["a"];
d.visit_struct("Foo", FIELDS, Visitor)
}
}
fn main() {
let s = "{}";
let got = serde_json::from_str::<Foo>(&s);
match got {
Err(serde_json::Error::SyntaxError(serde_json::ErrorCode::MissingField(field),
line,
column)) => {
assert_eq!(("a", 1, 2), (field, line, column));
}
Ok(_) => {
panic!("Got unexpected OK result: {:?}", got);
}
_ => {
panic!("Got unexpected error result: {:?}", got);
}
}
}
```
|
diff --git a/json/src/de.rs b/json/src/de.rs
index 7b9bc8e60..02b22c22b 100644
--- a/json/src/de.rs
+++ b/json/src/de.rs
@@ -745,10 +745,31 @@ impl<'a, Iter> de::MapVisitor for MapVisitor<'a, Iter>
}
}
- fn missing_field<V>(&mut self, _field: &'static str) -> Result<V>
+ fn missing_field<V>(&mut self, field: &'static str) -> Result<V>
where V: de::Deserialize,
{
- let mut de = de::value::ValueDeserializer::into_deserializer(());
+ use std;
+
+ struct MissingFieldDeserializer(&'static str);
+
+ impl de::Deserializer for MissingFieldDeserializer {
+ type Error = de::value::Error;
+
+ fn visit<V>(&mut self, _visitor: V) -> std::result::Result<V::Value, Self::Error>
+ where V: de::Visitor,
+ {
+ let &mut MissingFieldDeserializer(field) = self;
+ Err(de::value::Error::MissingFieldError(field))
+ }
+
+ fn visit_option<V>(&mut self, mut visitor: V) -> std::result::Result<V::Value, Self::Error>
+ where V: de::Visitor,
+ {
+ visitor.visit_none()
+ }
+ }
+
+ let mut de = MissingFieldDeserializer(field);
Ok(try!(de::Deserialize::deserialize(&mut de)))
}
}
|
diff --git a/json_tests/tests/test_json.rs b/json_tests/tests/test_json.rs
index d5ad4c9a9..dd4e85762 100644
--- a/json_tests/tests/test_json.rs
+++ b/json_tests/tests/test_json.rs
@@ -911,6 +911,8 @@ fn test_parse_struct() {
("5", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 1)),
("\"hello\"", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 7)),
("{\"inner\": true}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 14)),
+ ("{}", Error::SyntaxError(ErrorCode::MissingField("inner"), 1, 2)),
+ (r#"{"inner": [{"b": 42, "c": []}]}"#, Error::SyntaxError(ErrorCode::MissingField("a"), 1, 29)),
]);
test_parse_ok(vec![
@@ -936,15 +938,6 @@ fn test_parse_struct() {
),
]);
- let v: Outer = from_str("{}").unwrap();
-
- assert_eq!(
- v,
- Outer {
- inner: vec![],
- }
- );
-
let v: Outer = from_str(
"[
[
@@ -1057,7 +1050,7 @@ fn test_multiline_errors() {
}
#[test]
-fn test_missing_field() {
+fn test_missing_option_field() {
#[derive(Debug, PartialEq, Deserialize)]
struct Foo {
x: Option<u32>,
@@ -1078,6 +1071,18 @@ fn test_missing_field() {
assert_eq!(value, Foo { x: Some(5) });
}
+#[test]
+fn test_missing_nonoption_field() {
+ #[derive(Debug, PartialEq, Deserialize)]
+ struct Foo {
+ x: u32,
+ }
+
+ test_parse_err::<Foo>(vec![
+ ("{}", Error::SyntaxError(ErrorCode::MissingField("x"), 1, 2)),
+ ]);
+}
+
#[test]
fn test_missing_renamed_field() {
#[derive(Debug, PartialEq, Deserialize)]
|
serde-rs/json
|
d37fc6cc7e94238c4f533560061aa768f1f2b8fd
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.