version
stringclasses 2
values | instance_id
stringlengths 17
19
| pull_number
int64 31
1.18k
| issue_numbers
sequencelengths 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
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 1