Rollup merge of #77426 - tamird:sockaddr-scope-id, r=dtolnay

Include scope id in SocketAddrV6::Display

r? @tmandry

I couldn't find any unit tests for these functions.

cc @ghanan94 @brunowonka
This commit is contained in:
Dylan DPC 2020-10-05 02:29:35 +02:00 committed by GitHub
commit f1afed541e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 3 deletions

View File

@ -623,19 +623,27 @@ impl fmt::Display for SocketAddrV6 {
// Fast path: if there's no alignment stuff, write to the output
// buffer directly
if f.precision().is_none() && f.width().is_none() {
write!(f, "[{}]:{}", self.ip(), self.port())
match self.scope_id() {
0 => write!(f, "[{}]:{}", self.ip(), self.port()),
scope_id => write!(f, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
}
} else {
const IPV6_SOCKET_BUF_LEN: usize = (4 * 8) // The address
+ 7 // The colon separators
+ 2 // The brackets
+ 1 + 10 // The scope id
+ 1 + 5; // The port
let mut buf = [0; IPV6_SOCKET_BUF_LEN];
let mut buf_slice = &mut buf[..];
match self.scope_id() {
0 => write!(buf_slice, "[{}]:{}", self.ip(), self.port()),
scope_id => write!(buf_slice, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
}
// Unwrap is fine because writing to a sufficiently-sized
// buffer is infallible
write!(buf_slice, "[{}]:{}", self.ip(), self.port()).unwrap();
.unwrap();
let len = IPV6_SOCKET_BUF_LEN - buf_slice.len();
// This unsafe is OK because we know what is being written to the buffer

View File

@ -178,13 +178,21 @@ fn socket_v4_to_str() {
#[test]
fn socket_v6_to_str() {
let socket: SocketAddrV6 = "[2a02:6b8:0:1::1]:53".parse().unwrap();
let mut socket = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53, 0, 0);
assert_eq!(format!("{}", socket), "[2a02:6b8:0:1::1]:53");
assert_eq!(format!("{:<24}", socket), "[2a02:6b8:0:1::1]:53 ");
assert_eq!(format!("{:>24}", socket), " [2a02:6b8:0:1::1]:53");
assert_eq!(format!("{:^24}", socket), " [2a02:6b8:0:1::1]:53 ");
assert_eq!(format!("{:.15}", socket), "[2a02:6b8:0:1::");
socket.set_scope_id(5);
assert_eq!(format!("{}", socket), "[2a02:6b8:0:1::1%5]:53");
assert_eq!(format!("{:<24}", socket), "[2a02:6b8:0:1::1%5]:53 ");
assert_eq!(format!("{:>24}", socket), " [2a02:6b8:0:1::1%5]:53");
assert_eq!(format!("{:^24}", socket), " [2a02:6b8:0:1::1%5]:53 ");
assert_eq!(format!("{:.18}", socket), "[2a02:6b8:0:1::1%5");
}
#[test]