flexstr/storage/
heap.rs

1use core::fmt::{Debug, Formatter};
2use core::ops::Deref;
3use core::{fmt, mem};
4
5use crate::StorageType;
6
7// HEAP will likely align this just fine, but since we don't know the size, this is safest
8#[cfg_attr(target_pointer_width = "64", repr(align(8)))]
9#[cfg_attr(target_pointer_width = "32", repr(align(4)))]
10#[repr(C)]
11#[derive(Clone)]
12pub(crate) struct HeapStr<const PAD: usize, HEAP> {
13    pub heap: HEAP,
14    pad: [mem::MaybeUninit<u8>; PAD],
15    pub marker: StorageType,
16}
17
18impl<const PAD: usize, HEAP> HeapStr<PAD, HEAP> {
19    #[inline]
20    pub fn from_heap(t: HEAP) -> Self {
21        Self {
22            heap: t,
23            // SAFETY: Padding, never actually used
24            pad: unsafe { mem::MaybeUninit::uninit().assume_init() },
25            marker: StorageType::Heap,
26        }
27    }
28
29    #[inline]
30    pub fn from_ref(s: impl AsRef<str>) -> Self
31    where
32        HEAP: for<'a> From<&'a str>,
33    {
34        Self::from_heap(s.as_ref().into())
35    }
36}
37
38impl<const PAD: usize, HEAP> Debug for HeapStr<PAD, HEAP>
39where
40    HEAP: Deref<Target = str>,
41{
42    #[inline]
43    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
44        <str as Debug>::fmt(&self.heap, f)
45    }
46}