mirror of
https://github.com/rust-lang/rust.git
synced 2025-04-28 02:57:37 +00:00
Use MaybeUninit<u8>
for IpDisplayBuffer
.
This commit is contained in:
parent
033e9d66ff
commit
31540f5e15
@ -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)]
|
||||
|
@ -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)
|
||||
|
Loading…
Reference in New Issue
Block a user