1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use core::mem;
pub struct Buffer<T> {
inner: core::mem::MaybeUninit<T>,
offset: u8,
}
impl<S: Sized> Buffer<S> {
#[inline]
pub const fn new() -> Self {
Self {
inner: core::mem::MaybeUninit::uninit(),
offset: 0,
}
}
#[inline]
pub const fn as_ptr(&self) -> *const u8 {
&self.inner as *const _ as *const u8
}
#[inline]
pub const fn capacity() -> usize {
mem::size_of::<S>()
}
#[inline(always)]
pub fn as_str(&self) -> &str {
unsafe {
let slice = core::slice::from_raw_parts(self.as_ptr().offset(self.offset as isize), Self::capacity() - self.offset as usize);
core::str::from_utf8_unchecked(slice)
}
}
#[inline]
pub fn write<T: crate::ToStr>(&mut self, val: T) -> &str {
self.offset = (Self::capacity() - self.format(val).len()) as u8;
self.as_str()
}
#[inline(always)]
pub fn format<T: crate::ToStr>(&mut self, val: T) -> &str {
debug_assert!(Self::capacity() <= u8::max_value() as usize);
debug_assert!(T::TEXT_SIZE <= Self::capacity());
val.to_str(unsafe {
&mut *core::ptr::slice_from_raw_parts_mut(self.as_ptr() as *mut u8, Self::capacity())
})
}
#[inline(always)]
pub fn fmt<T: crate::ToStr>(val: T) -> Self {
let mut this = Self::new();
this.write(val);
this
}
}
impl<S: Sized> AsRef<str> for Buffer<S> {
#[inline(always)]
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl<S: Sized> core::fmt::Display for Buffer<S> {
#[inline(always)]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.write_str(self.as_str())
}
}
impl<S: Sized> core::fmt::Debug for Buffer<S> {
#[inline(always)]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.write_str(self.as_str())
}
}