blob: 38e5cabf2ae131461ab562205edbc3b8e9b49740 [file] [log] [blame]
David Tolnay3384c142020-09-14 00:26:47 -04001use core::mem;
2use core::ptr::NonNull;
3use core::slice;
4use core::str;
David Tolnay7db73692019-10-20 14:51:12 -04005
6// Not necessarily ABI compatible with &str. Codegen performs the translation.
7#[repr(C)]
8#[derive(Copy, Clone)]
9pub struct RustStr {
David Tolnayebef4a22020-03-17 15:33:47 -070010 pub(crate) ptr: NonNull<u8>,
11 pub(crate) len: usize,
David Tolnay7db73692019-10-20 14:51:12 -040012}
13
14impl RustStr {
15 pub fn from(s: &str) -> Self {
16 RustStr {
David Tolnay792d0222020-03-16 21:57:47 -070017 ptr: NonNull::from(s).cast::<u8>(),
David Tolnay7db73692019-10-20 14:51:12 -040018 len: s.len(),
19 }
20 }
21
22 pub unsafe fn as_str<'a>(self) -> &'a str {
David Tolnay792d0222020-03-16 21:57:47 -070023 let slice = slice::from_raw_parts(self.ptr.as_ptr(), self.len);
David Tolnay7db73692019-10-20 14:51:12 -040024 str::from_utf8_unchecked(slice)
25 }
26}
27
David Tolnayad7186a2020-04-24 15:37:45 -070028const_assert_eq!(mem::size_of::<Option<RustStr>>(), mem::size_of::<RustStr>());