From fb7964fde70c603d91005aa18f87905e5df894c0 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 13 Apr 2017 16:36:24 -0700 Subject: [PATCH] Clean up serialize_display_bounded_length --- serde/src/ser/impls.rs | 46 ++++++++++++++++++------------------------ 1 file changed, 20 insertions(+), 26 deletions(-) diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs index 0fb48c11..291c6670 100644 --- a/serde/src/ser/impls.rs +++ b/serde/src/ser/impls.rs @@ -369,34 +369,30 @@ impl Serialize for Duration { //////////////////////////////////////////////////////////////////////////////// -/// 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. +/// Serialize a 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. +/// Panics if the `Display` impl tries to write more than `MAX_LEN` bytes. #[cfg(feature = "std")] macro_rules! serialize_display_bounded_length { - ($value: expr, $MAX_LEN: expr, $serializer: expr) => { - { - let mut buffer: [u8; $MAX_LEN] = unsafe { 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]; + ($value:expr, $max:expr, $serializer:expr) => {{ + let mut buffer: [u8; $max] = unsafe { mem::uninitialized() }; + let remaining_len = { + let mut remaining = &mut buffer[..]; + write!(remaining, "{}", $value).unwrap(); + remaining.len() + }; + let written_len = buffer.len() - remaining_len; + let written = &buffer[..written_len]; - // write! only provides 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 { - str::from_utf8_unchecked(written) - }; - $serializer.serialize_str(written_str) - } - } + // write! only provides fmt::Formatter to Display implementations, which + // has methods write_str and write_char but no method to write arbitrary + // bytes. Therefore `written` must be valid UTF-8. + let written_str = unsafe { + str::from_utf8_unchecked(written) + }; + $serializer.serialize_str(written_str) + }} } #[cfg(feature = "std")] @@ -436,8 +432,6 @@ impl Serialize for net::Ipv6Addr { } } -//////////////////////////////////////////////////////////////////////////////// - #[cfg(feature = "std")] impl Serialize for net::SocketAddr { fn serialize(&self, serializer: S) -> Result