@@ -856,16 +856,23 @@ impl From<Ipv6Addr> for IpAddr {
856
856
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
857
857
impl fmt:: Display for Ipv4Addr {
858
858
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[ ..] ;
862
859
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
+ }
869
876
}
870
877
}
871
878
0 commit comments