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