Skip to content

Commit 5a11b81

Browse files
committed
Add IpDisplayBuffer helper struct.
1 parent a39bdb1 commit 5a11b81

File tree

1 file changed

+48
-31
lines changed

1 file changed

+48
-31
lines changed

library/std/src/net/ip.rs

+48-31
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,44 @@
33
mod tests;
44

55
use crate::cmp::Ordering;
6-
use crate::fmt::{self, Write as FmtWrite};
7-
use crate::io::Write as IoWrite;
6+
use crate::fmt::{self, Write};
87
use crate::mem::transmute;
8+
use crate::str;
99
use crate::sys::net::netc as c;
1010
use crate::sys_common::{FromInner, IntoInner};
1111

12+
/// Used for slow path in `Display` implementations when alignment is required.
13+
struct IpDisplayBuffer<const SIZE: usize> {
14+
buf: [u8; SIZE],
15+
len: usize,
16+
}
17+
18+
impl<const SIZE: usize> IpDisplayBuffer<SIZE> {
19+
#[inline(always)]
20+
pub const fn new(_ip: &[u8; SIZE]) -> Self {
21+
Self { buf: [0; SIZE], len: 0 }
22+
}
23+
24+
#[inline(always)]
25+
pub fn as_str(&self) -> &str {
26+
// SAFETY: `buf` is only written to by the `fmt::Write::write_str` implementation
27+
// which writes a valid UTF-8 string to `buf` and correctly sets `len`.
28+
unsafe { str::from_utf8_unchecked(&self.buf[..self.len]) }
29+
}
30+
}
31+
32+
impl<const SIZE: usize> fmt::Write for IpDisplayBuffer<SIZE> {
33+
fn write_str(&mut self, s: &str) -> fmt::Result {
34+
if let Some(buf) = self.buf.get_mut(self.len..(self.len + s.len())) {
35+
buf.copy_from_slice(s.as_bytes());
36+
self.len += s.len();
37+
Ok(())
38+
} else {
39+
Err(fmt::Error)
40+
}
41+
}
42+
}
43+
1244
/// An IP address, either IPv4 or IPv6.
1345
///
1446
/// This enum can contain either an [`Ipv4Addr`] or an [`Ipv6Addr`], see their
@@ -991,21 +1023,17 @@ impl From<Ipv6Addr> for IpAddr {
9911023
impl fmt::Display for Ipv4Addr {
9921024
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
9931025
let octets = self.octets();
994-
// Fast Path: if there's no alignment stuff, write directly to the buffer
1026+
1027+
// If there are no alignment requirements, write the IP address directly to `f`.
1028+
// Otherwise, write it to a local buffer and then use `f.pad`.
9951029
if fmt.precision().is_none() && fmt.width().is_none() {
9961030
write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
9971031
} else {
998-
const IPV4_BUF_LEN: usize = 15; // Long enough for the longest possible IPv4 address
999-
let mut buf = [0u8; IPV4_BUF_LEN];
1000-
let mut buf_slice = &mut buf[..];
1001-
1002-
// Note: The call to write should never fail, hence the unwrap
1003-
write!(buf_slice, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
1004-
let len = IPV4_BUF_LEN - buf_slice.len();
1032+
let mut buf = IpDisplayBuffer::new(b"255.255.255.255");
1033+
// Buffer is long enough for the longest possible IPv4 address, so this should never fail.
1034+
write!(buf, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
10051035

1006-
// This unsafe is OK because we know what is being written to the buffer
1007-
let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
1008-
fmt.pad(buf)
1036+
fmt.pad(buf.as_str())
10091037
}
10101038
}
10111039
}
@@ -1708,8 +1736,8 @@ impl Ipv6Addr {
17081736
#[stable(feature = "rust1", since = "1.0.0")]
17091737
impl fmt::Display for Ipv6Addr {
17101738
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1711-
// If there are no alignment requirements, write out the IP address to
1712-
// f. Otherwise, write it to a local buffer, then use f.pad.
1739+
// If there are no alignment requirements, write the IP address directly to `f`.
1740+
// Otherwise, write it to a local buffer and then use `f.pad`.
17131741
if f.precision().is_none() && f.width().is_none() {
17141742
let segments = self.segments();
17151743

@@ -1780,22 +1808,11 @@ impl fmt::Display for Ipv6Addr {
17801808
}
17811809
}
17821810
} else {
1783-
// Slow path: write the address to a local buffer, then use f.pad.
1784-
// Defined recursively by using the fast path to write to the
1785-
// buffer.
1786-
1787-
// This is the largest possible size of an IPv6 address
1788-
const IPV6_BUF_LEN: usize = (4 * 8) + 7;
1789-
let mut buf = [0u8; IPV6_BUF_LEN];
1790-
let mut buf_slice = &mut buf[..];
1791-
1792-
// Note: This call to write should never fail, so unwrap is okay.
1793-
write!(buf_slice, "{}", self).unwrap();
1794-
let len = IPV6_BUF_LEN - buf_slice.len();
1795-
1796-
// This is safe because we know exactly what can be in this buffer
1797-
let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
1798-
f.pad(buf)
1811+
let mut buf = IpDisplayBuffer::new(b"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff");
1812+
// Buffer is long enough for the longest possible IPv6 address, so this should never fail.
1813+
write!(buf, "{}", self).unwrap();
1814+
1815+
f.pad(buf.as_str())
17991816
}
18001817
}
18011818
}

0 commit comments

Comments
 (0)