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

Improve IpAddr/SocketAddr serialization by avoiding Display #2001

Merged
merged 4 commits into from Mar 22, 2021
Merged
Changes from 2 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
50 changes: 49 additions & 1 deletion serde/src/ser/impls.rs
Expand Up @@ -674,6 +674,46 @@ impl Serialize for net::IpAddr {
}
}

const DEC_DIGITS_LUT: &'static [u8] = b"\
0001020304050607080910111213141516171819\
2021222324252627282930313233343536373839\
4041424344454647484950515253545556575859\
6061626364656667686970717273747576777879\
8081828384858687888990919293949596979899";

#[inline]
fn format_u8(mut n: u8, out: &mut [u8]) -> usize {
assert!(out.len() >= 3);
if n >= 100 {
let d1 = ((n % 100) << 1) as usize;
n /= 100;
out[0] = b'0' + n;
out[1] = DEC_DIGITS_LUT[d1];
out[2] = DEC_DIGITS_LUT[d1 + 1];
3
} else if n >= 10 {
let d1 = (n << 1) as usize;
out[0] = DEC_DIGITS_LUT[d1];
out[1] = DEC_DIGITS_LUT[d1 + 1];
2
} else {
out[0] = b'0' + n;
1
}
}

#[cfg(test)]
mod format_u8_tests {
#[test]
fn all() {
for i in 0..(u8::MAX as u16) {
let mut buf = [0u8; 3];
let written = super::format_u8(i as u8, &mut buf);
assert_eq!(i.to_string().as_bytes(), &buf[..written]);
}
}
}

#[cfg(feature = "std")]
impl Serialize for net::Ipv4Addr {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
Expand All @@ -683,7 +723,15 @@ impl Serialize for net::Ipv4Addr {
if serializer.is_human_readable() {
const MAX_LEN: usize = 15;
debug_assert_eq!(MAX_LEN, "101.102.103.104".len());
serialize_display_bounded_length!(self, MAX_LEN, serializer)
let mut buf = [0u8; MAX_LEN];
let mut written = 0;
written += format_u8(self.octets()[0], &mut buf);
for oct in &self.octets()[1..] {
buf[written] = b'.';
written += 1;
written += format_u8(*oct, &mut buf[written..]);
}
serializer.serialize_str(str::from_utf8(&buf[..written]).unwrap())
} else {
self.octets().serialize(serializer)
}
Expand Down