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

Avoid some string allocations. #778

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 32 additions & 0 deletions serde/src/macros.rs
Expand Up @@ -188,3 +188,35 @@ macro_rules! forward_to_deserialize {
$(forward_to_deserialize_helper!{$func})*
};
}

/// Seralize the `$value` that implements Display as a string,
/// when that string is statically known to never have more than
/// a constant `$MAX_LEN` bytes.
///
/// Panics if the Display impl tries to write more than `$MAX_LEN` bytes.
#[cfg(feature = "std")]
// Not exported
macro_rules! serialize_display_bounded_length {
($value: expr, $MAX_LEN: expr, $serializer: expr) => {
{
use std::io::Write;
let mut buffer: [u8; $MAX_LEN] = unsafe { ::std::mem::uninitialized() };
let remaining_len;
{
let mut remaining = &mut buffer[..];
write!(remaining, "{}", $value).unwrap();
remaining_len = remaining.len()
}
let written_len = buffer.len() - remaining_len;
let written = &buffer[..written_len];

// write! only provides std::fmt::Formatter to Display implementations,
Copy link
Member

Choose a reason for hiding this comment

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

I would strongly prefer to implement this safely if possible. Would it be possible to implement fmt::Write and use that in the call to write!?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Implementing fmt::Write how?

It’s possible to remove unsafe completely, at some performance cost:

diff --git a/serde/src/macros.rs b/serde/src/macros.rs
index 126c7ec..cc8775b 100644
--- a/serde/src/macros.rs
+++ b/serde/src/macros.rs
@@ -200,7 +200,7 @@ macro_rules! serialize_display_bounded_length {
     ($value: expr, $MAX_LEN: expr, $serializer: expr) => {
         {
             use std::io::Write;
-            let mut buffer: [u8; $MAX_LEN] = unsafe { ::std::mem::uninitialized() };
+            let mut buffer = [0; $MAX_LEN];
             let remaining_len;
             {
                 let mut remaining = &mut buffer[..];
@@ -209,13 +209,7 @@ macro_rules! serialize_display_bounded_length {
             }
             let written_len = buffer.len() - remaining_len;
             let written = &buffer[..written_len];
-
-            // write! only provides std::fmt::Formatter to Display implementations,
-            // which has methods write_str and write_char but no method to write arbitrary bytes.
-            // Therefore, `written` is well-formed in UTF-8.
-            let written_str = unsafe {
-                ::std::str::from_utf8_unchecked(written)
-            };
+            let written_str = ::std::str::from_utf8(written).unwrap();
             $serializer.serialize_str(written_str)
         }
     }

Copy link
Member

Choose a reason for hiding this comment

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

You're right that doesn't help. Let's go with your way.

// which has methods write_str and write_char but no method to write arbitrary bytes.
// Therefore, `written` is well-formed in UTF-8.
let written_str = unsafe {
::std::str::from_utf8_unchecked(written)
};
$serializer.serialize_str(written_str)
}
}
}
21 changes: 16 additions & 5 deletions serde/src/ser/impls.rs
Expand Up @@ -623,7 +623,10 @@ impl Serialize for net::IpAddr {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
self.to_string().serialize(serializer)
match *self {
net::IpAddr::V4(ref a) => a.serialize(serializer),
net::IpAddr::V6(ref a) => a.serialize(serializer),
}
}
}

Expand All @@ -632,7 +635,9 @@ impl Serialize for net::Ipv4Addr {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
self.to_string().serialize(serializer)
/// "101.102.103.104".len()
const MAX_LEN: usize = 15;
serialize_display_bounded_length!(self, MAX_LEN, serializer)
}
}

Expand All @@ -641,7 +646,9 @@ impl Serialize for net::Ipv6Addr {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
self.to_string().serialize(serializer)
/// "1000:1002:1003:1004:1005:1006:1007:1008".len()
const MAX_LEN: usize = 39;
serialize_display_bounded_length!(self, MAX_LEN, serializer)
}
}

Expand All @@ -664,7 +671,9 @@ impl Serialize for net::SocketAddrV4 {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
self.to_string().serialize(serializer)
/// "101.102.103.104:65000".len()
const MAX_LEN: usize = 21;
serialize_display_bounded_length!(self, MAX_LEN, serializer)
}
}

Expand All @@ -673,7 +682,9 @@ impl Serialize for net::SocketAddrV6 {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
self.to_string().serialize(serializer)
/// "[1000:1002:1003:1004:1005:1006:1007:1008]:65000".len()
const MAX_LEN: usize = 47;
serialize_display_bounded_length!(self, MAX_LEN, serializer)
}
}

Expand Down