about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorNathan West <Lucretiel@gmail.com>2020-05-20 16:49:31 -0400
committerNathan West <Lucretiel@gmail.com>2020-05-20 16:49:31 -0400
commitdc3de7cb2ae9d886ddac91d71f2e9517ff123e90 (patch)
tree91df1129739cdefc1f0eb0229d5ddd41bae3ab09 /src
parent672b272077561ca7b5027a8aff9ea2957c7d4c21 (diff)
downloadrust-dc3de7cb2ae9d886ddac91d71f2e9517ff123e90.tar.gz
rust-dc3de7cb2ae9d886ddac91d71f2e9517ff123e90.zip
Add fast-path optimization for Ipv4Addr::fmt
Diffstat (limited to 'src')
-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)
+        }
     }
 }