Skip to content

Commit

Permalink
Rollup merge of #77426 - tamird:sockaddr-scope-id, r=dtolnay
Browse files Browse the repository at this point in the history
Include scope id in SocketAddrV6::Display

r? @tmandry

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

cc @ghanan94 @brunowonka
  • Loading branch information
Dylan-DPC committed Oct 5, 2020
2 parents fffeaa7 + 4585c22 commit f1afed5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
12 changes: 10 additions & 2 deletions library/std/src/net/addr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 9 additions & 1 deletion library/std/src/net/addr/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down

0 comments on commit f1afed5

Please sign in to comment.