Skip to content

Commit

Permalink
Rollup merge of #72399 - Lucretiel:ipv4-display-fast, r=kennytm
Browse files Browse the repository at this point in the history
Add fast-path optimization for Ipv4Addr::fmt

Don't use an intermediary buffer when writing an IPv4 address without any specific alignment options
  • Loading branch information
RalfJung authored May 22, 2020
2 parents a116e7b + dc3de7c commit 37587af
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions src/libstd/net/ip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -856,16 +856,23 @@ impl From<Ipv6Addr> for IpAddr {
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for Ipv4Addr {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
const IPV4_BUF_LEN: usize = 15; // Long enough for the longest possible IPv4 address
let mut buf = [0u8; IPV4_BUF_LEN];
let mut buf_slice = &mut buf[..];
let octets = self.octets();
// Note: The call to write should never fail, hence the unwrap
write!(buf_slice, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
let len = IPV4_BUF_LEN - buf_slice.len();
// This unsafe is OK because we know what is being written to the buffer
let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
fmt.pad(buf)
// Fast Path: if there's no alignment stuff, write directly to the buffer
if fmt.precision().is_none() && fmt.width().is_none() {
write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
} else {
const IPV4_BUF_LEN: usize = 15; // Long enough for the longest possible IPv4 address
let mut buf = [0u8; IPV4_BUF_LEN];
let mut buf_slice = &mut buf[..];

// Note: The call to write should never fail, hence the unwrap
write!(buf_slice, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
let len = IPV4_BUF_LEN - buf_slice.len();

// This unsafe is OK because we know what is being written to the buffer
let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
fmt.pad(buf)
}
}
}

Expand Down

0 comments on commit 37587af

Please sign in to comment.