blob: a5fa3f496498478da323ce43e907d66927170072 [file] [log] [blame]
David Tolnayc5a52f92020-09-14 00:43:29 -04001use alloc::string::String;
David Tolnay3384c142020-09-14 00:26:47 -04002use core::mem;
David Tolnay7db73692019-10-20 14:51:12 -04003
4#[repr(C)]
5pub struct RustString {
6 repr: String,
7}
8
9impl RustString {
10 pub fn from(s: String) -> Self {
11 RustString { repr: s }
12 }
13
14 pub fn from_ref(s: &String) -> &Self {
David Tolnaydb96ed92020-03-18 17:20:39 -070015 unsafe { &*(s as *const String as *const RustString) }
David Tolnay7db73692019-10-20 14:51:12 -040016 }
17
David Tolnayf1c7f322020-08-27 00:46:01 -070018 pub fn from_mut(s: &mut String) -> &mut Self {
19 unsafe { &mut *(s as *mut String as *mut RustString) }
20 }
21
David Tolnay7db73692019-10-20 14:51:12 -040022 pub fn into_string(self) -> String {
23 self.repr
24 }
25
26 pub fn as_string(&self) -> &String {
27 &self.repr
28 }
David Tolnay40226ab2020-03-03 00:05:35 -080029
30 pub fn as_mut_string(&mut self) -> &mut String {
31 &mut self.repr
32 }
David Tolnay7db73692019-10-20 14:51:12 -040033}
34
David Tolnayaa77e822020-04-24 15:43:05 -070035const_assert_eq!(mem::size_of::<[usize; 3]>(), mem::size_of::<String>());
36const_assert_eq!(mem::align_of::<usize>(), mem::align_of::<String>());