summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorRalf Jung <post@ralfj.de>2020-05-22 16:58:36 +0200
committerGitHub <noreply@github.com>2020-05-22 16:58:36 +0200
commit37587af8d53b516b5f74a0ff667c83bccd308b8d (patch)
treeb89df02ec644a31fffd773a1f9259b96d2998454 /src/libstd
parenta116e7b02fa407e06303e5118da9bf7ae1caf493 (diff)
parentdc3de7cb2ae9d886ddac91d71f2e9517ff123e90 (diff)
downloadrust-37587af8d53b516b5f74a0ff667c83bccd308b8d.tar.gz
rust-37587af8d53b516b5f74a0ff667c83bccd308b8d.zip
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
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/net/ip.rs25
1 files changed, 16 insertions, 9 deletions
diff --git a/src/libstd/net/ip.rs b/src/libstd/net/ip.rs
index edc28033c9b..6e2478b8308 100644
--- a/src/libstd/net/ip.rs
+++ b/src/libstd/net/ip.rs
@@ -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)
+        }
     }
 }