Skip to content

Commit

Permalink
Simplify IpDisplayBuffer API.
Browse files Browse the repository at this point in the history
  • Loading branch information
reitermarkus committed Aug 16, 2022
1 parent 31540f5 commit 44d6242
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
8 changes: 6 additions & 2 deletions library/std/src/net/ip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -999,7 +999,9 @@ impl fmt::Display for Ipv4Addr {
if fmt.precision().is_none() && fmt.width().is_none() {
write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
} else {
let mut buf = IpDisplayBuffer::new(b"255.255.255.255");
const LONGEST_IPV4_ADDR: &str = "255.255.255.255";

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

Expand Down Expand Up @@ -1778,7 +1780,9 @@ impl fmt::Display for Ipv6Addr {
}
}
} else {
let mut buf = IpDisplayBuffer::new(b"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff");
const LONGEST_IPV6_ADDR: &str = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff";

let mut buf = IpDisplayBuffer::<{ LONGEST_IPV6_ADDR.len() }>::new();
// Buffer is long enough for the longest possible IPv6 address, so this should never fail.
write!(buf, "{}", self).unwrap();

Expand Down
8 changes: 4 additions & 4 deletions library/std/src/net/ip/display_buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ pub struct IpDisplayBuffer<const SIZE: usize> {
}

impl<const SIZE: usize> IpDisplayBuffer<SIZE> {
#[inline(always)]
pub const fn new(_ip: &[u8; SIZE]) -> Self {
Self { buf: MaybeUninit::uninit_array::<SIZE>(), len: 0 }
#[inline]
pub const fn new() -> Self {
Self { buf: MaybeUninit::uninit_array(), len: 0 }
}

#[inline(always)]
#[inline]
pub fn as_str(&self) -> &str {
// SAFETY: `buf` is only written to by the `fmt::Write::write_str` implementation
// which writes a valid UTF-8 string to `buf` and correctly sets `len`.
Expand Down

0 comments on commit 44d6242

Please sign in to comment.