Skip to content

Commit 44ca3da

Browse files
committed
Various minor improvements to Ipv6Addr::Display
- Defer to Ipv4Addr::fmt when printing an Ipv4 address - Fast path: write directly to f without an intermediary buffer when there are no alignment options - Simplify finding the inner zeroes-span
1 parent 672b272 commit 44ca3da

File tree

1 file changed

+78
-80
lines changed

1 file changed

+78
-80
lines changed

src/libstd/net/ip.rs

+78-80
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77
)]
88

99
use crate::cmp::Ordering;
10-
use crate::fmt;
10+
use crate::fmt::{self, Write as FmtWrite};
1111
use crate::hash;
12-
use crate::io::Write;
12+
use crate::io::Write as IoWrite;
1313
use crate::sys::net::netc as c;
1414
use crate::sys_common::{AsInner, FromInner};
1515

@@ -1525,102 +1525,100 @@ impl Ipv6Addr {
15251525
}
15261526
}
15271527

1528+
/// Write an Ipv6Addr, conforming to the canonical style described by
1529+
/// [RFC 5952](https://tools.ietf.org/html/rfc5952).
15281530
#[stable(feature = "rust1", since = "1.0.0")]
15291531
impl fmt::Display for Ipv6Addr {
1530-
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1531-
// Note: The calls to write should never fail, hence the unwraps in the function
1532-
// Long enough for the longest possible IPv6: 39
1533-
const IPV6_BUF_LEN: usize = 39;
1534-
let mut buf = [0u8; IPV6_BUF_LEN];
1535-
let mut buf_slice = &mut buf[..];
1532+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1533+
// If there are no alignment requirements, write out the IP address to
1534+
// f. Otherwise, write it to a local buffer, then use f.pad.
1535+
if f.precision().is_none() && f.width().is_none() {
1536+
let segments = self.segments();
1537+
1538+
// Special case for :: and ::1; otherwise they get written with the
1539+
// IPv4 formatter
1540+
if self.is_unspecified() {
1541+
f.write_str("::")
1542+
} else if self.is_loopback() {
1543+
f.write_str("::1")
1544+
} else if let Some(ipv4) = self.to_ipv4() {
1545+
match segments[5] {
1546+
// IPv4 Compatible address
1547+
0 => write!(f, "::{}", ipv4),
1548+
// IPv4 Mapped address
1549+
0xffff => write!(f, "::ffff:{}", ipv4),
1550+
_ => unreachable!(),
1551+
}
1552+
} else {
1553+
#[derive(Copy, Clone, Default)]
1554+
struct Span {
1555+
start: usize,
1556+
len: usize,
1557+
}
15361558

1537-
match self.segments() {
1538-
// We need special cases for :: and ::1, otherwise they're formatted
1539-
// as ::0.0.0.[01]
1540-
[0, 0, 0, 0, 0, 0, 0, 0] => write!(buf_slice, "::").unwrap(),
1541-
[0, 0, 0, 0, 0, 0, 0, 1] => write!(buf_slice, "::1").unwrap(),
1542-
// Ipv4 Compatible address
1543-
[0, 0, 0, 0, 0, 0, g, h] => {
1544-
write!(
1545-
buf_slice,
1546-
"::{}.{}.{}.{}",
1547-
(g >> 8) as u8,
1548-
g as u8,
1549-
(h >> 8) as u8,
1550-
h as u8
1551-
)
1552-
.unwrap();
1553-
}
1554-
// Ipv4-Mapped address
1555-
[0, 0, 0, 0, 0, 0xffff, g, h] => {
1556-
write!(
1557-
buf_slice,
1558-
"::ffff:{}.{}.{}.{}",
1559-
(g >> 8) as u8,
1560-
g as u8,
1561-
(h >> 8) as u8,
1562-
h as u8
1563-
)
1564-
.unwrap();
1565-
}
1566-
_ => {
1567-
fn find_zero_slice(segments: &[u16; 8]) -> (usize, usize) {
1568-
let mut longest_span_len = 0;
1569-
let mut longest_span_at = 0;
1570-
let mut cur_span_len = 0;
1571-
let mut cur_span_at = 0;
1572-
1573-
for i in 0..8 {
1574-
if segments[i] == 0 {
1575-
if cur_span_len == 0 {
1576-
cur_span_at = i;
1559+
// Find the inner 0 span
1560+
let zeroes = {
1561+
let mut longest = Span::default();
1562+
let mut current = Span::default();
1563+
1564+
for (i, &segment) in segments.iter().enumerate() {
1565+
if segment == 0 {
1566+
if current.len == 0 {
1567+
current.start = i;
15771568
}
15781569

1579-
cur_span_len += 1;
1570+
current.len += 1;
15801571

1581-
if cur_span_len > longest_span_len {
1582-
longest_span_len = cur_span_len;
1583-
longest_span_at = cur_span_at;
1572+
if current.len > longest.len {
1573+
longest = current;
15841574
}
15851575
} else {
1586-
cur_span_len = 0;
1587-
cur_span_at = 0;
1576+
current = Span::default();
15881577
}
15891578
}
15901579

1591-
(longest_span_at, longest_span_len)
1592-
}
1593-
1594-
let (zeros_at, zeros_len) = find_zero_slice(&self.segments());
1595-
1596-
if zeros_len > 1 {
1597-
fn fmt_subslice(segments: &[u16], buf: &mut &mut [u8]) {
1598-
if !segments.is_empty() {
1599-
write!(*buf, "{:x}", segments[0]).unwrap();
1600-
for &seg in &segments[1..] {
1601-
write!(*buf, ":{:x}", seg).unwrap();
1602-
}
1580+
longest
1581+
};
1582+
1583+
/// Write a colon-separated part of the address
1584+
#[inline]
1585+
fn fmt_subslice(f: &mut fmt::Formatter<'_>, chunk: &[u16]) -> fmt::Result {
1586+
if let Some(first) = chunk.first() {
1587+
fmt::LowerHex::fmt(first, f)?;
1588+
for segment in &chunk[1..] {
1589+
f.write_char(':')?;
1590+
fmt::LowerHex::fmt(segment, f)?;
16031591
}
16041592
}
1593+
Ok(())
1594+
}
16051595

1606-
fmt_subslice(&self.segments()[..zeros_at], &mut buf_slice);
1607-
write!(buf_slice, "::").unwrap();
1608-
fmt_subslice(&self.segments()[zeros_at + zeros_len..], &mut buf_slice);
1596+
if zeroes.len > 1 {
1597+
fmt_subslice(f, &segments[..zeroes.start])?;
1598+
f.write_str("::")?;
1599+
fmt_subslice(f, &segments[zeroes.start + zeroes.len..])
16091600
} else {
1610-
let &[a, b, c, d, e, f, g, h] = &self.segments();
1611-
write!(
1612-
buf_slice,
1613-
"{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}",
1614-
a, b, c, d, e, f, g, h
1615-
)
1616-
.unwrap();
1601+
fmt_subslice(f, &segments)
16171602
}
16181603
}
1604+
} else {
1605+
// Slow path: write the address to a local buffer, the use f.pad.
1606+
// Defined recursively by using the fast path to write to the
1607+
// buffer.
1608+
1609+
// This is the largest possible size of an IPv6 address
1610+
const IPV6_BUF_LEN: usize = (4 * 8) + 7;
1611+
let mut buf = [0u8; IPV6_BUF_LEN];
1612+
let mut buf_slice = &mut buf[..];
1613+
1614+
// Note: This call to write should never fail, so unwrap is okay.
1615+
write!(buf_slice, "{}", self).unwrap();
1616+
let len = IPV6_BUF_LEN - buf_slice.len();
1617+
1618+
// This is safe because we know exactly what can be in this buffer
1619+
let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
1620+
f.pad(buf)
16191621
}
1620-
let len = IPV6_BUF_LEN - buf_slice.len();
1621-
// This is safe because we know exactly what can be in this buffer
1622-
let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
1623-
fmt.pad(buf)
16241622
}
16251623
}
16261624

0 commit comments

Comments
 (0)