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

Conversation

JohnScience
Copy link

@JohnScience JohnScience commented Aug 9, 2024

/// 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 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)
}

@JohnScience
Copy link
Author

Ready for the review!

@@ -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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants