2 use crate::mem::MaybeUninit;
5 /// Used for slow path in `Display` implementations when alignment is required.
6 pub struct DisplayBuffer<const SIZE: usize> {
7 buf: [MaybeUninit<u8>; SIZE],
11 impl<const SIZE: usize> DisplayBuffer<SIZE> {
13 pub const fn new() -> Self {
14 Self { buf: MaybeUninit::uninit_array(), len: 0 }
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`.
22 let s = MaybeUninit::slice_assume_init_ref(&self.buf[..self.len]);
23 str::from_utf8_unchecked(s)
28 impl<const SIZE: usize> fmt::Write for DisplayBuffer<SIZE> {
29 fn write_str(&mut self, s: &str) -> fmt::Result {
30 let bytes = s.as_bytes();
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();