Debian Codegraph @

src/repr/static_str.rs

raw
1 use core::{mem, ptr, slice, str};
2
3 use super::{Repr, MAX_SIZE, STATIC_STR_MASK};
4
5 pub(super) const DISCRIMINANT_SIZE: usize = MAX_SIZE - mem::size_of::<&'static str>();
6
7 /// A buffer stored on the stack whose size is equal to the stack size of `String`
8 /// The last byte is set to 0.
9 #[derive(Copy, Clone)]
10 #[repr(C)]
11 pub(crate) struct StaticStr {
12 ptr: ptr::NonNull<u8>,
13 len: usize,
14 #[allow(unused)]
15 discriminant: [u8; DISCRIMINANT_SIZE],
16 }
17 static_assertions::assert_eq_size!(StaticStr, Repr);
18 static_assertions::assert_eq_align!(StaticStr, Repr);
19 static_assertions::assert_eq_size!(&'static str, (*const u8, usize));
20
21 impl StaticStr {
22 #[inline]
23 pub(crate) const fn new(text: &'static str) -> Self {
24 let mut discriminant = [0; DISCRIMINANT_SIZE];
25 discriminant[DISCRIMINANT_SIZE - 1] = STATIC_STR_MASK;
26
27 Self {
28 // SAFETY: `&'static str` must have a non-null, properly aligned
29 // address
30 ptr: unsafe { ptr::NonNull::new_unchecked(text.as_ptr() as *mut _) },
31 len: text.len(),
32 discriminant,
33 }
34 }
35
36 pub(super) const fn get_text(&self) -> &'static str {
37 // SAFETY: `StaticStr` invariants requires it to be a valid str
38 unsafe { str::from_utf8_unchecked(slice::from_raw_parts(self.ptr.as_ptr(), self.len)) }
39 }
40
41 /// # Safety
42 /// * `len` bytes in the buffer must be valid UTF-8 and
43 /// * `len` must be <= `self.get_text().len()`
44 pub(super) unsafe fn set_len(&mut self, len: usize) {
45 *self = Self::new(&self.get_text()[..len]);
46 }
47 }