Skip to content

Commit f1afed5

Browse files
authored
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
2 parents fffeaa7 + 4585c22 commit f1afed5

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

library/std/src/net/addr.rs

+10-2
Original file line numberDiff line numberDiff line change
@@ -623,19 +623,27 @@ impl fmt::Display for SocketAddrV6 {
623623
// Fast path: if there's no alignment stuff, write to the output
624624
// buffer directly
625625
if f.precision().is_none() && f.width().is_none() {
626-
write!(f, "[{}]:{}", self.ip(), self.port())
626+
match self.scope_id() {
627+
0 => write!(f, "[{}]:{}", self.ip(), self.port()),
628+
scope_id => write!(f, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
629+
}
627630
} else {
628631
const IPV6_SOCKET_BUF_LEN: usize = (4 * 8) // The address
629632
+ 7 // The colon separators
630633
+ 2 // The brackets
634+
+ 1 + 10 // The scope id
631635
+ 1 + 5; // The port
632636

633637
let mut buf = [0; IPV6_SOCKET_BUF_LEN];
634638
let mut buf_slice = &mut buf[..];
635639

640+
match self.scope_id() {
641+
0 => write!(buf_slice, "[{}]:{}", self.ip(), self.port()),
642+
scope_id => write!(buf_slice, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
643+
}
636644
// Unwrap is fine because writing to a sufficiently-sized
637645
// buffer is infallible
638-
write!(buf_slice, "[{}]:{}", self.ip(), self.port()).unwrap();
646+
.unwrap();
639647
let len = IPV6_SOCKET_BUF_LEN - buf_slice.len();
640648

641649
// This unsafe is OK because we know what is being written to the buffer

library/std/src/net/addr/tests.rs

+9-1
Original file line numberDiff line numberDiff line change
@@ -178,13 +178,21 @@ fn socket_v4_to_str() {
178178

179179
#[test]
180180
fn socket_v6_to_str() {
181-
let socket: SocketAddrV6 = "[2a02:6b8:0:1::1]:53".parse().unwrap();
181+
let mut socket = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53, 0, 0);
182182

183183
assert_eq!(format!("{}", socket), "[2a02:6b8:0:1::1]:53");
184184
assert_eq!(format!("{:<24}", socket), "[2a02:6b8:0:1::1]:53 ");
185185
assert_eq!(format!("{:>24}", socket), " [2a02:6b8:0:1::1]:53");
186186
assert_eq!(format!("{:^24}", socket), " [2a02:6b8:0:1::1]:53 ");
187187
assert_eq!(format!("{:.15}", socket), "[2a02:6b8:0:1::");
188+
189+
socket.set_scope_id(5);
190+
191+
assert_eq!(format!("{}", socket), "[2a02:6b8:0:1::1%5]:53");
192+
assert_eq!(format!("{:<24}", socket), "[2a02:6b8:0:1::1%5]:53 ");
193+
assert_eq!(format!("{:>24}", socket), " [2a02:6b8:0:1::1%5]:53");
194+
assert_eq!(format!("{:^24}", socket), " [2a02:6b8:0:1::1%5]:53 ");
195+
assert_eq!(format!("{:.18}", socket), "[2a02:6b8:0:1::1%5");
188196
}
189197

190198
#[test]

0 commit comments

Comments
 (0)