Skip to content

Commit 37587af

Browse files
authored
Rollup merge of #72399 - Lucretiel:ipv4-display-fast, r=kennytm
Add fast-path optimization for Ipv4Addr::fmt Don't use an intermediary buffer when writing an IPv4 address without any specific alignment options
2 parents a116e7b + dc3de7c commit 37587af

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

src/libstd/net/ip.rs

+16-9
Original file line numberDiff line numberDiff line change
@@ -856,16 +856,23 @@ impl From<Ipv6Addr> for IpAddr {
856856
#[stable(feature = "rust1", since = "1.0.0")]
857857
impl fmt::Display for Ipv4Addr {
858858
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
859-
const IPV4_BUF_LEN: usize = 15; // Long enough for the longest possible IPv4 address
860-
let mut buf = [0u8; IPV4_BUF_LEN];
861-
let mut buf_slice = &mut buf[..];
862859
let octets = self.octets();
863-
// Note: The call to write should never fail, hence the unwrap
864-
write!(buf_slice, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
865-
let len = IPV4_BUF_LEN - buf_slice.len();
866-
// This unsafe is OK because we know what is being written to the buffer
867-
let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
868-
fmt.pad(buf)
860+
// Fast Path: if there's no alignment stuff, write directly to the buffer
861+
if fmt.precision().is_none() && fmt.width().is_none() {
862+
write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
863+
} else {
864+
const IPV4_BUF_LEN: usize = 15; // Long enough for the longest possible IPv4 address
865+
let mut buf = [0u8; IPV4_BUF_LEN];
866+
let mut buf_slice = &mut buf[..];
867+
868+
// Note: The call to write should never fail, hence the unwrap
869+
write!(buf_slice, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
870+
let len = IPV4_BUF_LEN - buf_slice.len();
871+
872+
// This unsafe is OK because we know what is being written to the buffer
873+
let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
874+
fmt.pad(buf)
875+
}
869876
}
870877
}
871878

0 commit comments

Comments
 (0)