blob: 59a7784371ee153a5ede6bcb1507a2a7cda1b6b4 [file] [log] [blame]
David Tolnay7db73692019-10-20 14:51:12 -04001use std::slice;
2use std::str;
3
4// Not necessarily ABI compatible with &str. Codegen performs the translation.
5#[repr(C)]
6#[derive(Copy, Clone)]
7pub struct RustStr {
8 ptr: *const u8,
9 len: usize,
10}
11
12impl 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 Tolnaye43b7372020-01-08 08:46:20 -080026#[export_name = "cxxbridge01$rust_str$valid"]
David Tolnay7db73692019-10-20 14:51:12 -040027unsafe 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}