| David Tolnay | 3384c14 | 2020-09-14 00:26:47 -0400 | [diff] [blame] | 1 | use core::mem; |
| 2 | use core::ptr::NonNull; | ||||
| David Tolnay | 3384c14 | 2020-09-14 00:26:47 -0400 | [diff] [blame] | 3 | use core::str; |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 4 | |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 5 | #[repr(C)] |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 6 | pub struct RustStr { |
| David Tolnay | 1202de5 | 2021-01-02 01:26:33 -0800 | [diff] [blame^] | 7 | repr: NonNull<str>, |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 8 | } |
| 9 | |||||
| 10 | impl RustStr { | ||||
| David Tolnay | 1202de5 | 2021-01-02 01:26:33 -0800 | [diff] [blame^] | 11 | pub fn from(repr: &str) -> Self { |
| 12 | let repr = NonNull::from(repr); | ||||
| 13 | RustStr { repr } | ||||
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 14 | } |
| 15 | |||||
| 16 | pub unsafe fn as_str<'a>(self) -> &'a str { | ||||
| David Tolnay | 1202de5 | 2021-01-02 01:26:33 -0800 | [diff] [blame^] | 17 | &*self.repr.as_ptr() |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 18 | } |
| 19 | } | ||||
| 20 | |||||
| David Tolnay | ad7186a | 2020-04-24 15:37:45 -0700 | [diff] [blame] | 21 | const_assert_eq!(mem::size_of::<Option<RustStr>>(), mem::size_of::<RustStr>()); |