small_fixed_array/
static.rs

1use core::ptr::NonNull;
2
3use crate::ValidLength;
4
5#[repr(packed)]
6#[derive(Clone, Copy)]
7pub(crate) struct StaticStr<LenT: ValidLength> {
8    ptr: NonNull<u8>,
9    len: LenT,
10}
11
12impl<LenT: ValidLength> StaticStr<LenT> {
13    /// # Panics
14    /// Panics if the string passed requires truncation.
15    pub fn from_static_str(src: &'static str) -> Self {
16        let ptr = NonNull::new(src.as_ptr().cast_mut()).expect("str::as_ptr should never be null");
17        let len = LenT::from_usize(src.len()).unwrap();
18
19        Self { ptr, len }
20    }
21
22    pub fn as_str(&self) -> &'static str {
23        unsafe {
24            let slice = core::slice::from_raw_parts(self.ptr.as_ptr(), self.len.to_usize());
25            core::str::from_utf8_unchecked(slice)
26        }
27    }
28
29    pub fn len(&self) -> LenT {
30        self.len
31    }
32}
33
34unsafe impl<LenT: ValidLength> Send for StaticStr<LenT> {}
35unsafe impl<LenT: ValidLength> Sync for StaticStr<LenT> {}
36
37#[cfg(feature = "typesize")]
38impl<LenT: ValidLength> typesize::TypeSize for StaticStr<LenT> {}