Skip to content

Commit 813ce7a

Browse files
committed
SocketAddr(V4|V6)?::Display now correctly pads its content
IpAddr and friends pad when displaying; SocketAddr now does this as well
1 parent 255c033 commit 813ce7a

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

src/libstd/net/addr.rs

+27-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use crate::cmp::Ordering;
22
use crate::convert::TryInto;
33
use crate::fmt;
44
use crate::hash;
5-
use crate::io;
5+
use crate::io::{self, Write};
66
use crate::iter;
77
use crate::mem;
88
use crate::net::{htons, ntohs, IpAddr, Ipv4Addr, Ipv6Addr};
@@ -600,7 +600,17 @@ impl fmt::Display for SocketAddr {
600600
#[stable(feature = "rust1", since = "1.0.0")]
601601
impl 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")]
615625
impl 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

Comments
 (0)