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