Skip to content

Commit b7b4f79

Browse files
authored
Rollup merge of #100625 - reitermarkus:ip-display-buffer, r=thomcc
Add `IpDisplayBuffer` helper struct. This removes the dependency on `std::io::Write` for implementing `Display`, allowing it to be moved to `core` as proposed in rust-lang/rfcs#2832.
2 parents e6d4792 + 44d6242 commit b7b4f79

File tree

3 files changed

+63
-30
lines changed

3 files changed

+63
-30
lines changed

library/std/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,8 @@
294294
#![feature(std_internals)]
295295
#![feature(str_internals)]
296296
#![feature(strict_provenance)]
297+
#![feature(maybe_uninit_uninit_array)]
298+
#![feature(const_maybe_uninit_uninit_array)]
297299
//
298300
// Library features (alloc):
299301
#![feature(alloc_layout_extra)]

library/std/src/net/ip.rs

+21-30
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,14 @@
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;
98
use crate::sys::net::netc as c;
109
use crate::sys_common::{FromInner, IntoInner};
1110

11+
mod display_buffer;
12+
use display_buffer::IpDisplayBuffer;
13+
1214
/// An IP address, either IPv4 or IPv6.
1315
///
1416
/// This enum can contain either an [`Ipv4Addr`] or an [`Ipv6Addr`], see their
@@ -991,21 +993,19 @@ impl From<Ipv6Addr> for IpAddr {
991993
impl fmt::Display for Ipv4Addr {
992994
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
993995
let octets = self.octets();
994-
// Fast Path: if there's no alignment stuff, write directly to the buffer
996+
997+
// If there are no alignment requirements, write the IP address directly to `f`.
998+
// Otherwise, write it to a local buffer and then use `f.pad`.
995999
if fmt.precision().is_none() && fmt.width().is_none() {
9961000
write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
9971001
} 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[..];
1002+
const LONGEST_IPV4_ADDR: &str = "255.255.255.255";
10011003

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();
1004+
let mut buf = IpDisplayBuffer::<{ LONGEST_IPV4_ADDR.len() }>::new();
1005+
// Buffer is long enough for the longest possible IPv4 address, so this should never fail.
1006+
write!(buf, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
10051007

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)
1008+
fmt.pad(buf.as_str())
10091009
}
10101010
}
10111011
}
@@ -1708,8 +1708,8 @@ impl Ipv6Addr {
17081708
#[stable(feature = "rust1", since = "1.0.0")]
17091709
impl fmt::Display for Ipv6Addr {
17101710
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.
1711+
// If there are no alignment requirements, write the IP address directly to `f`.
1712+
// Otherwise, write it to a local buffer and then use `f.pad`.
17131713
if f.precision().is_none() && f.width().is_none() {
17141714
let segments = self.segments();
17151715

@@ -1780,22 +1780,13 @@ impl fmt::Display for Ipv6Addr {
17801780
}
17811781
}
17821782
} 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)
1783+
const LONGEST_IPV6_ADDR: &str = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff";
1784+
1785+
let mut buf = IpDisplayBuffer::<{ LONGEST_IPV6_ADDR.len() }>::new();
1786+
// Buffer is long enough for the longest possible IPv6 address, so this should never fail.
1787+
write!(buf, "{}", self).unwrap();
1788+
1789+
f.pad(buf.as_str())
17991790
}
18001791
}
18011792
}
+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
use crate::fmt;
2+
use crate::mem::MaybeUninit;
3+
use crate::str;
4+
5+
/// Used for slow path in `Display` implementations when alignment is required.
6+
pub struct IpDisplayBuffer<const SIZE: usize> {
7+
buf: [MaybeUninit<u8>; SIZE],
8+
len: usize,
9+
}
10+
11+
impl<const SIZE: usize> IpDisplayBuffer<SIZE> {
12+
#[inline]
13+
pub const fn new() -> Self {
14+
Self { buf: MaybeUninit::uninit_array(), len: 0 }
15+
}
16+
17+
#[inline]
18+
pub fn as_str(&self) -> &str {
19+
// SAFETY: `buf` is only written to by the `fmt::Write::write_str` implementation
20+
// which writes a valid UTF-8 string to `buf` and correctly sets `len`.
21+
unsafe {
22+
let s = MaybeUninit::slice_assume_init_ref(&self.buf[..self.len]);
23+
str::from_utf8_unchecked(s)
24+
}
25+
}
26+
}
27+
28+
impl<const SIZE: usize> fmt::Write for IpDisplayBuffer<SIZE> {
29+
fn write_str(&mut self, s: &str) -> fmt::Result {
30+
let bytes = s.as_bytes();
31+
32+
if let Some(buf) = self.buf.get_mut(self.len..(self.len + bytes.len())) {
33+
MaybeUninit::write_slice(buf, bytes);
34+
self.len += bytes.len();
35+
Ok(())
36+
} else {
37+
Err(fmt::Error)
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)