Skip to content

Commit

Permalink
Use MaybeUninit<u8> for IpDisplayBuffer.
Browse files Browse the repository at this point in the history
  • Loading branch information
reitermarkus committed Aug 16, 2022
1 parent 033e9d6 commit 31540f5
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
2 changes: 2 additions & 0 deletions library/std/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,8 @@
#![feature(std_internals)]
#![feature(str_internals)]
#![feature(strict_provenance)]
#![feature(maybe_uninit_uninit_array)]
#![feature(const_maybe_uninit_uninit_array)]
//
// Library features (alloc):
#![feature(alloc_layout_extra)]
Expand Down
18 changes: 12 additions & 6 deletions library/std/src/net/ip/display_buffer.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,37 @@
use crate::fmt;
use crate::mem::MaybeUninit;
use crate::str;

/// Used for slow path in `Display` implementations when alignment is required.
pub struct IpDisplayBuffer<const SIZE: usize> {
buf: [u8; SIZE],
buf: [MaybeUninit<u8>; SIZE],
len: usize,
}

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

#[inline(always)]
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`.
unsafe { str::from_utf8_unchecked(&self.buf[..self.len]) }
unsafe {
let s = MaybeUninit::slice_assume_init_ref(&self.buf[..self.len]);
str::from_utf8_unchecked(s)
}
}
}

impl<const SIZE: usize> fmt::Write for IpDisplayBuffer<SIZE> {
fn write_str(&mut self, s: &str) -> fmt::Result {
if let Some(buf) = self.buf.get_mut(self.len..(self.len + s.len())) {
buf.copy_from_slice(s.as_bytes());
self.len += s.len();
let bytes = s.as_bytes();

if let Some(buf) = self.buf.get_mut(self.len..(self.len + bytes.len())) {
MaybeUninit::write_slice(buf, bytes);
self.len += bytes.len();
Ok(())
} else {
Err(fmt::Error)
Expand Down

0 comments on commit 31540f5

Please sign in to comment.