| David Tolnay | c5a52f9 | 2020-09-14 00:43:29 -0400 | [diff] [blame^] | 1 | use alloc::string::String; |
| David Tolnay | 3384c14 | 2020-09-14 00:26:47 -0400 | [diff] [blame] | 2 | use core::mem; |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 3 | |
| 4 | #[repr(C)] |
| 5 | pub struct RustString { |
| 6 | repr: String, |
| 7 | } |
| 8 | |
| 9 | impl RustString { |
| 10 | pub fn from(s: String) -> Self { |
| 11 | RustString { repr: s } |
| 12 | } |
| 13 | |
| 14 | pub fn from_ref(s: &String) -> &Self { |
| David Tolnay | db96ed9 | 2020-03-18 17:20:39 -0700 | [diff] [blame] | 15 | unsafe { &*(s as *const String as *const RustString) } |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 16 | } |
| 17 | |
| David Tolnay | f1c7f32 | 2020-08-27 00:46:01 -0700 | [diff] [blame] | 18 | pub fn from_mut(s: &mut String) -> &mut Self { |
| 19 | unsafe { &mut *(s as *mut String as *mut RustString) } |
| 20 | } |
| 21 | |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 22 | pub fn into_string(self) -> String { |
| 23 | self.repr |
| 24 | } |
| 25 | |
| 26 | pub fn as_string(&self) -> &String { |
| 27 | &self.repr |
| 28 | } |
| David Tolnay | 40226ab | 2020-03-03 00:05:35 -0800 | [diff] [blame] | 29 | |
| 30 | pub fn as_mut_string(&mut self) -> &mut String { |
| 31 | &mut self.repr |
| 32 | } |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 33 | } |
| 34 | |
| David Tolnay | aa77e82 | 2020-04-24 15:43:05 -0700 | [diff] [blame] | 35 | const_assert_eq!(mem::size_of::<[usize; 3]>(), mem::size_of::<String>()); |
| 36 | const_assert_eq!(mem::align_of::<usize>(), mem::align_of::<String>()); |