blob: f1a7741592a4f5f1cfe59ee3b2db546a1f117aab [file] [log] [blame]
David Tolnay33f56ad2020-08-27 17:06:35 -07001use crate::rust_string::RustString;
David Tolnayc5a52f92020-09-14 00:43:29 -04002use alloc::string::String;
3use alloc::vec::Vec;
David Tolnay3384c142020-09-14 00:26:47 -04004use core::mem::ManuallyDrop;
David Tolnay33f56ad2020-08-27 17:06:35 -07005
Myron Ahneba35cf2020-02-05 19:41:51 +07006#[repr(C)]
David Tolnay3a8ae092020-04-24 11:55:46 -07007pub struct RustVec<T> {
David Tolnay9f6c0752020-09-07 22:26:46 -07008 pub(crate) repr: Vec<T>,
Myron Ahneba35cf2020-02-05 19:41:51 +07009}
10
David Tolnay3a8ae092020-04-24 11:55:46 -070011impl<T> RustVec<T> {
David Tolnayf97c2d52020-04-25 16:37:48 -070012 pub fn new() -> Self {
13 RustVec { repr: Vec::new() }
14 }
15
Myron Ahneba35cf2020-02-05 19:41:51 +070016 pub fn from(v: Vec<T>) -> Self {
17 RustVec { repr: v }
18 }
19
20 pub fn from_ref(v: &Vec<T>) -> &Self {
David Tolnayfac8b252020-04-24 11:37:39 -070021 unsafe { &*(v as *const Vec<T> as *const RustVec<T>) }
Myron Ahneba35cf2020-02-05 19:41:51 +070022 }
23
David Tolnayf1c7f322020-08-27 00:46:01 -070024 pub fn from_mut(v: &mut Vec<T>) -> &mut Self {
25 unsafe { &mut *(v as *mut Vec<T> as *mut RustVec<T>) }
26 }
27
Myron Ahneba35cf2020-02-05 19:41:51 +070028 pub fn into_vec(self) -> Vec<T> {
29 self.repr
30 }
31
32 pub fn as_vec(&self) -> &Vec<T> {
33 &self.repr
34 }
35
36 pub fn as_mut_vec(&mut self) -> &mut Vec<T> {
37 &mut self.repr
38 }
39
40 pub fn len(&self) -> usize {
41 self.repr.len()
42 }
David Tolnay219c0792020-04-24 20:31:37 -070043
44 pub fn as_ptr(&self) -> *const T {
45 self.repr.as_ptr()
46 }
Myron Ahneba35cf2020-02-05 19:41:51 +070047}
David Tolnay33f56ad2020-08-27 17:06:35 -070048
49impl RustVec<RustString> {
50 pub fn from_vec_string(v: Vec<String>) -> Self {
51 let mut v = ManuallyDrop::new(v);
52 let ptr = v.as_mut_ptr().cast::<RustString>();
53 let len = v.len();
54 let cap = v.capacity();
55 Self::from(unsafe { Vec::from_raw_parts(ptr, len, cap) })
56 }
57
58 pub fn from_ref_vec_string(v: &Vec<String>) -> &Self {
59 Self::from_ref(unsafe { &*(v as *const Vec<String> as *const Vec<RustString>) })
60 }
61
62 pub fn from_mut_vec_string(v: &mut Vec<String>) -> &mut Self {
63 Self::from_mut(unsafe { &mut *(v as *mut Vec<String> as *mut Vec<RustString>) })
64 }
65
66 pub fn into_vec_string(self) -> Vec<String> {
67 let mut v = ManuallyDrop::new(self.repr);
68 let ptr = v.as_mut_ptr().cast::<String>();
69 let len = v.len();
70 let cap = v.capacity();
71 unsafe { Vec::from_raw_parts(ptr, len, cap) }
72 }
73
74 pub fn as_vec_string(&self) -> &Vec<String> {
75 unsafe { &*(&self.repr as *const Vec<RustString> as *const Vec<String>) }
76 }
77
78 pub fn as_mut_vec_string(&mut self) -> &mut Vec<String> {
79 unsafe { &mut *(&mut self.repr as *mut Vec<RustString> as *mut Vec<String>) }
80 }
81}