| David Tolnay | 792d022 | 2020-03-16 21:57:47 -0700 | [diff] [blame^] | 1 | use std::mem; |
| 2 | use std::ptr::NonNull; |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 3 | use std::slice; |
| 4 | use std::str; |
| 5 | |
| 6 | // Not necessarily ABI compatible with &str. Codegen performs the translation. |
| 7 | #[repr(C)] |
| 8 | #[derive(Copy, Clone)] |
| 9 | pub struct RustStr { |
| David Tolnay | 792d022 | 2020-03-16 21:57:47 -0700 | [diff] [blame^] | 10 | ptr: NonNull<u8>, |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 11 | len: usize, |
| 12 | } |
| 13 | |
| 14 | impl RustStr { |
| 15 | pub fn from(s: &str) -> Self { |
| 16 | RustStr { |
| David Tolnay | 792d022 | 2020-03-16 21:57:47 -0700 | [diff] [blame^] | 17 | ptr: NonNull::from(s).cast::<u8>(), |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 18 | len: s.len(), |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | pub unsafe fn as_str<'a>(self) -> &'a str { |
| David Tolnay | 792d022 | 2020-03-16 21:57:47 -0700 | [diff] [blame^] | 23 | let slice = slice::from_raw_parts(self.ptr.as_ptr(), self.len); |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 24 | str::from_utf8_unchecked(slice) |
| 25 | } |
| 26 | } |
| 27 | |
| David Tolnay | 8c73049 | 2020-03-13 01:29:06 -0700 | [diff] [blame] | 28 | #[export_name = "cxxbridge02$str$valid"] |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 29 | unsafe extern "C" fn str_valid(ptr: *const u8, len: usize) -> bool { |
| 30 | let slice = slice::from_raw_parts(ptr, len); |
| 31 | str::from_utf8(slice).is_ok() |
| 32 | } |
| David Tolnay | 792d022 | 2020-03-16 21:57:47 -0700 | [diff] [blame^] | 33 | |
| 34 | const_assert!(mem::size_of::<Option<RustStr>>() == mem::size_of::<RustStr>()); |