@@ -2,7 +2,7 @@ use crate::cmp::Ordering;
22use crate :: convert:: TryInto ;
33use crate :: fmt;
44use crate :: hash;
5- use crate :: io;
5+ use crate :: io:: { self , Write } ;
66use crate :: iter;
77use crate :: mem;
88use crate :: net:: { htons, ntohs, IpAddr , Ipv4Addr , Ipv6Addr } ;
@@ -600,7 +600,17 @@ impl fmt::Display for SocketAddr {
600600#[ stable( feature = "rust1" , since = "1.0.0" ) ]
601601impl fmt:: Display for SocketAddrV4 {
602602 fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
603- write ! ( f, "{}:{}" , self . ip( ) , self . port( ) )
603+ const IPV4_SOCKET_BUF_LEN : usize = 21 ;
604+ let mut buf = [ 0 ; IPV4_SOCKET_BUF_LEN ] ;
605+ let mut buf_slice = & mut buf[ ..] ;
606+
607+ // Unwrap is fine because writing to a buffer is infallible
608+ write ! ( buf_slice, "{}:{}" , self . ip( ) , self . port( ) ) . unwrap ( ) ;
609+ let len = IPV4_SOCKET_BUF_LEN - buf_slice. len ( ) ;
610+
611+ // This unsafe is OK because we know what is being written to the buffer
612+ let buf = unsafe { crate :: str:: from_utf8_unchecked ( & buf[ ..len] ) } ;
613+ f. pad ( buf)
604614 }
605615}
606616
@@ -614,7 +624,21 @@ impl fmt::Debug for SocketAddrV4 {
614624#[ stable( feature = "rust1" , since = "1.0.0" ) ]
615625impl fmt:: Display for SocketAddrV6 {
616626 fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
617- write ! ( f, "[{}]:{}" , self . ip( ) , self . port( ) )
627+ const IPV6_SOCKET_BUF_LEN : usize = ( 4 * 8 ) // The address
628+ + 7 // The colon separators
629+ + 2 // The brackets
630+ + 1 + 5 ; // The port
631+
632+ let mut buf = [ 0 ; IPV6_SOCKET_BUF_LEN ] ;
633+ let mut buf_slice = & mut buf[ ..] ;
634+
635+ // Unwrap is fine because writing to a buffer is infallible
636+ write ! ( buf_slice, "[{}]:{}" , self . ip( ) , self . port( ) ) . unwrap ( ) ;
637+ let len = IPV6_SOCKET_BUF_LEN - buf_slice. len ( ) ;
638+
639+ // This unsafe is OK because we know what is being written to the buffer
640+ let buf = unsafe { crate :: str:: from_utf8_unchecked ( & buf[ ..len] ) } ;
641+ f. pad ( buf)
618642 }
619643}
620644
0 commit comments