Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added to_string_mut and to_string_mut_pretty #1171

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -389,11 +389,13 @@ pub use crate::de::{from_slice, from_str, Deserializer, StreamDeserializer};
#[doc(inline)]
pub use crate::error::{Error, Result};
#[doc(inline)]
pub use crate::ser::{to_string, to_string_pretty, to_vec, to_vec_pretty};
pub use crate::ser::{
to_string, to_string_pretty, to_vec, to_vec_pretty, to_writer, to_writer_pretty,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#1122 describes some considerations about exposing no-std to_writer. What's done in this PR is not going to work.

};
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
#[doc(inline)]
pub use crate::ser::{to_writer, to_writer_pretty, Serializer};
pub use crate::ser::{to_string_mut, to_string_mut_pretty, Serializer};
#[doc(inline)]
pub use crate::value::{from_value, to_value, Map, Number, Value};

Expand Down
40 changes: 38 additions & 2 deletions src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2135,7 +2135,6 @@ static ESCAPE: [u8; 256] = [
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
/// fail, or if `T` contains a map with non-string keys.
#[inline]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub fn to_writer<W, T>(writer: W, value: &T) -> Result<()>
where
W: io::Write,
Expand All @@ -2145,6 +2144,25 @@ where
value.serialize(&mut ser)
}

/// Serialize the given data structure as JSON into the pre-existing [`String``].
///
/// # Errors
///
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
/// fail, or if `T` contains a map with non-string keys.
#[inline]
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub fn to_string_mut<T>(s: &mut String, value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
// to_writer() guarantees that it feeds only valid UTF-8 to the writer.
let buf = unsafe { s.as_mut_vec() };
let mut writer = std::io::Cursor::new(buf);
to_writer(&mut writer, value)
}

/// Serialize the given data structure as pretty-printed JSON into the I/O
/// stream.
///
Expand All @@ -2155,7 +2173,6 @@ where
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
/// fail, or if `T` contains a map with non-string keys.
#[inline]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub fn to_writer_pretty<W, T>(writer: W, value: &T) -> Result<()>
where
W: io::Write,
Expand All @@ -2165,6 +2182,25 @@ where
value.serialize(&mut ser)
}

/// Serialize the given data structure as pretty-printed JSON into the pre-existing [`String`].
///
/// # Errors
///
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
/// fail, or if `T` contains a map with non-string keys.
#[inline]
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub fn to_string_mut_pretty<T>(s: &mut String, value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
// to_writer_pretty() guarantees that it feeds only valid UTF-8 to the writer.
let buf = unsafe { s.as_mut_vec() };
let mut writer = std::io::Cursor::new(buf);
to_writer_pretty(&mut writer, value)
}

/// Serialize the given data structure as a JSON byte vector.
///
/// # Errors
Expand Down
1 change: 1 addition & 0 deletions tests/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ macro_rules! test_stream {
assert_eq!($stream.byte_offset(), 0);
$test
}
#[cfg(feature = "std")]
{
let mut bytes = $data.as_bytes();
let de = Deserializer::from_reader(&mut bytes);
Expand Down
43 changes: 29 additions & 14 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,13 @@ use serde::de::{self, IgnoredAny, IntoDeserializer};
use serde::ser::{self, SerializeMap, SerializeSeq, Serializer};
use serde::{Deserialize, Serialize};
use serde_bytes::{ByteBuf, Bytes};
#[cfg(feature = "std")]
use serde_json::from_reader;
#[cfg(feature = "raw_value")]
use serde_json::value::RawValue;
use serde_json::{
from_reader, from_slice, from_str, from_value, json, to_string, to_string_pretty, to_value,
to_vec, Deserializer, Number, Value,
from_slice, from_str, from_value, json, to_string, to_string_pretty, to_value, to_vec,
Deserializer, Number, Value,
};
use std::collections::BTreeMap;
#[cfg(feature = "raw_value")]
Expand All @@ -39,6 +41,7 @@ use std::fmt::{self, Debug};
use std::hash::BuildHasher;
#[cfg(feature = "raw_value")]
use std::hash::{Hash, Hasher};
#[cfg(feature = "std")]
use std::io;
use std::iter;
use std::marker::PhantomData;
Expand Down Expand Up @@ -1622,7 +1625,7 @@ fn test_serialize_map_with_no_len() {
assert_eq!(s, expected);
}

#[cfg(not(miri))]
#[cfg(all(not(miri), feature = "std"))]
#[test]
fn test_deserialize_from_stream() {
use serde_json::to_writer;
Expand Down Expand Up @@ -2146,8 +2149,10 @@ fn test_partialeq_bool() {
assert_ne!(v, 0);
}

#[cfg(feature = "std")]
struct FailReader(io::ErrorKind);

#[cfg(feature = "std")]
impl io::Read for FailReader {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
Err(io::Error::new(self.0, "oh no!"))
Expand Down Expand Up @@ -2188,13 +2193,17 @@ fn test_category() {
.unwrap_err()
.is_eof());

let fail = FailReader(io::ErrorKind::NotConnected);
assert!(from_reader::<_, String>(fail).unwrap_err().is_io());
#[cfg(feature = "std")]
{
let fail = FailReader(io::ErrorKind::NotConnected);
assert!(from_reader::<_, String>(fail).unwrap_err().is_io());
}
}

#[test]
// Clippy false positive: https://github.com/Manishearth/rust-clippy/issues/292
#[allow(clippy::needless_lifetimes)]
#[cfg(feature = "std")]
fn test_into_io_error() {
fn io_error<'de, T: Deserialize<'de> + Debug>(j: &'static str) -> io::Error {
from_str::<T>(j).unwrap_err().into()
Expand Down Expand Up @@ -2374,9 +2383,12 @@ fn test_boxed_raw_value() {
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());
#[cfg(feature = "std")]
{
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();
Expand All @@ -2395,12 +2407,15 @@ fn test_boxed_raw_value() {
assert_eq!(r#"{"foo": "bar"}"#, array_from_str[2].get());
assert_eq!("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!("42", array_from_reader[1].get());
assert_eq!(r#"{"foo": "bar"}"#, array_from_reader[2].get());
assert_eq!("null", array_from_reader[3].get());
#[cfg(feature = "std")]
{
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!("42", array_from_reader[1].get());
assert_eq!(r#"{"foo": "bar"}"#, array_from_reader[2].get());
assert_eq!("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);
Expand Down