string_interner/backend/bucket/
interned_str.rs

1#![cfg(feature = "backends")]
2
3use core::ptr::NonNull;
4
5/// Reference to an interned string.
6///
7/// It is inherently `unsafe` to use instances of this type and should not be
8/// done outside of the `string-interner` crate itself.
9#[derive(Debug)]
10#[repr(transparent)]
11pub struct InternedStr {
12    ptr: NonNull<str>,
13}
14
15impl InternedStr {
16    /// Creates a new interned string from the given `str`.
17    #[inline]
18    pub fn new(val: &str) -> Self {
19        InternedStr {
20            ptr: NonNull::from(val),
21        }
22    }
23
24    /// Returns a shared reference to the underlying string.
25    ///
26    /// # Safety
27    ///
28    /// The user has to make sure that no lifetime guarantees are invalidated.
29    #[inline]
30    pub(super) fn as_str(&self) -> &str {
31        // SAFETY: This is safe since we only ever operate on interned `str`
32        //         that are never moved around in memory to avoid danling
33        //         references.
34        unsafe { self.ptr.as_ref() }
35    }
36}
37
38impl Eq for InternedStr {}
39
40impl PartialEq for InternedStr {
41    #[inline]
42    fn eq(&self, other: &Self) -> bool {
43        self.as_str() == other.as_str()
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    #[test]
52    fn size_of() {
53        use core::mem;
54        assert_eq!(mem::size_of::<InternedStr>(), mem::size_of::<&str>());
55    }
56}