Simplify `IpDisplayBuffer` API.

This commit is contained in:
Markus Reiter 2022-08-16 19:32:00 +02:00
parent 31540f5e15
commit 44d62425b9
No known key found for this signature in database
GPG Key ID: 245293B51702655B
2 changed files with 10 additions and 6 deletions

View File

@ -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();
@ -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();

View File

@ -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`.