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

Document behavior of to_pretty_string when passing Value #804

Open
marcospb19 opened this issue Sep 16, 2021 · 1 comment
Open

Document behavior of to_pretty_string when passing Value #804

marcospb19 opened this issue Sep 16, 2021 · 1 comment
Labels

Comments

@marcospb19
Copy link

marcospb19 commented Sep 16, 2021

From https://docs.rs/serde_json/1.0.68/serde_json/fn.to_string_pretty.html:

image

I assume that if I call

use serde_json::*;
to_string_pretty<Value>(...);

I can .unwrap() this result safely, is it right? Or Value's implementation of Serialize might decide to fail?

If it's the former, can I make a PR adding this piece of info to this doc page?

@dtolnay dtolnay added the docs label Jan 22, 2022
@kangalio
Copy link

Looking at the source code, it seems Value's Serialize impl indeed cannot fail:

json/src/value/ser.rs

Lines 13 to 36 in 931ee23

impl Serialize for Value {
#[inline]
fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
where
S: ::serde::Serializer,
{
match self {
Value::Null => serializer.serialize_unit(),
Value::Bool(b) => serializer.serialize_bool(*b),
Value::Number(n) => n.serialize(serializer),
Value::String(s) => serializer.serialize_str(s),
Value::Array(v) => v.serialize(serializer),
#[cfg(any(feature = "std", feature = "alloc"))]
Value::Object(m) => {
use serde::ser::SerializeMap;
let mut map = tri!(serializer.serialize_map(Some(m.len())));
for (k, v) in m {
tri!(map.serialize_entry(k, v));
}
map.end()
}
}
}
}

I think a PR to state this in the docs is a good idea, although the docs should be added to Value, not to_string_pretty.

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

No branches or pull requests

3 participants