blob: d25ea91f383d9821288b684e8c4a78edf608fa9d [file] [log] [blame]
David Tolnay47e239d2020-08-28 00:32:04 -07001use crate::cxx_string::CxxString;
David Tolnay3384c142020-09-14 00:26:47 -04002use core::ffi::c_void;
3use core::fmt::{self, Display};
David Tolnay95dab1d2020-11-15 14:32:37 -08004use core::marker::{PhantomData, PhantomPinned};
David Tolnay3384c142020-09-14 00:26:47 -04005use core::mem;
6use core::ptr;
David Tolnay93637ca2020-09-24 15:58:20 -04007use core::slice;
David Tolnay4f7e6fa2020-04-24 11:52:44 -07008
David Tolnay61a9fdf2020-04-24 16:19:42 -07009/// Binding to C++ `std::vector<T, std::allocator<T>>`.
Myron Ahneba35cf2020-02-05 19:41:51 +070010///
11/// # Invariants
12///
13/// As an invariant of this API and the static analysis of the cxx::bridge
David Tolnay5fe93632020-04-24 12:31:00 -070014/// macro, in Rust code we can never obtain a `CxxVector` by value. Instead in
15/// Rust code we will only ever look at a vector behind a reference or smart
16/// pointer, as in `&CxxVector<T>` or `UniquePtr<CxxVector<T>>`.
David Tolnay4f7e6fa2020-04-24 11:52:44 -070017#[repr(C, packed)]
David Tolnaye90be1d2020-04-24 11:45:57 -070018pub struct CxxVector<T> {
Myron Ahneba35cf2020-02-05 19:41:51 +070019 _private: [T; 0],
David Tolnay95dab1d2020-11-15 14:32:37 -080020 _pinned: PhantomData<PhantomPinned>,
Myron Ahneba35cf2020-02-05 19:41:51 +070021}
22
David Tolnay4074ad22020-04-24 18:20:11 -070023impl<T> CxxVector<T>
24where
25 T: VectorElement,
26{
David Tolnaycdc87962020-04-24 13:45:59 -070027 /// Returns the number of elements in the vector.
David Tolnaydd839192020-04-24 16:41:29 -070028 ///
29 /// Matches the behavior of C++ [std::vector\<T\>::size][size].
30 ///
31 /// [size]: https://en.cppreference.com/w/cpp/container/vector/size
David Tolnayc01d0a02020-04-24 13:30:44 -070032 pub fn len(&self) -> usize {
David Tolnay0e084662020-04-24 14:02:51 -070033 T::__vector_size(self)
Myron Ahneba35cf2020-02-05 19:41:51 +070034 }
35
David Tolnaycdc87962020-04-24 13:45:59 -070036 /// Returns true if the vector contains no elements.
David Tolnaydd839192020-04-24 16:41:29 -070037 ///
38 /// Matches the behavior of C++ [std::vector\<T\>::empty][empty].
39 ///
40 /// [empty]: https://en.cppreference.com/w/cpp/container/vector/empty
Myron Ahneba35cf2020-02-05 19:41:51 +070041 pub fn is_empty(&self) -> bool {
David Tolnayc01d0a02020-04-24 13:30:44 -070042 self.len() == 0
Myron Ahneba35cf2020-02-05 19:41:51 +070043 }
44
David Tolnaycdc87962020-04-24 13:45:59 -070045 /// Returns a reference to an element at the given position, or `None` if
46 /// out of bounds.
Myron Ahneba35cf2020-02-05 19:41:51 +070047 pub fn get(&self, pos: usize) -> Option<&T> {
David Tolnayc01d0a02020-04-24 13:30:44 -070048 if pos < self.len() {
David Tolnay93637ca2020-09-24 15:58:20 -040049 Some(unsafe { self.get_unchecked(pos) })
Myron Ahneba35cf2020-02-05 19:41:51 +070050 } else {
51 None
52 }
53 }
54
David Tolnay4944f2f2020-04-24 13:46:12 -070055 /// Returns a reference to an element without doing bounds checking.
56 ///
57 /// This is generally not recommended, use with caution! Calling this method
58 /// with an out-of-bounds index is undefined behavior even if the resulting
59 /// reference is not used.
David Tolnaydd839192020-04-24 16:41:29 -070060 ///
61 /// Matches the behavior of C++
62 /// [std::vector\<T\>::operator\[\]][operator_at].
63 ///
64 /// [operator_at]: https://en.cppreference.com/w/cpp/container/vector/operator_at
David Tolnay4944f2f2020-04-24 13:46:12 -070065 pub unsafe fn get_unchecked(&self, pos: usize) -> &T {
David Tolnay93637ca2020-09-24 15:58:20 -040066 &*T::__get_unchecked(self, pos)
67 }
68
69 /// Returns a slice to the underlying contiguous array of elements.
70 pub fn as_slice(&self) -> &[T] {
71 let len = self.len();
72 if len == 0 {
David Tolnaya5a14ce2020-09-24 16:02:40 -040073 // The slice::from_raw_parts in the other branch requires a nonnull
74 // and properly aligned data ptr. C++ standard does not guarantee
75 // that data() on a vector with size 0 would return a nonnull
76 // pointer or sufficiently aligned pointer, so using it would be
77 // undefined behavior. Create our own empty slice in Rust instead
78 // which upholds the invariants.
David Tolnayacc7fb02020-09-24 18:10:09 -040079 &[]
David Tolnay93637ca2020-09-24 15:58:20 -040080 } else {
81 let ptr = unsafe { T::__get_unchecked(self, 0) };
82 unsafe { slice::from_raw_parts(ptr, len) }
83 }
David Tolnay4944f2f2020-04-24 13:46:12 -070084 }
Myron Ahneba35cf2020-02-05 19:41:51 +070085}
86
David Tolnay3d88bdc2020-04-24 13:48:18 -070087pub struct Iter<'a, T> {
David Tolnaye90be1d2020-04-24 11:45:57 -070088 v: &'a CxxVector<T>,
Myron Ahneba35cf2020-02-05 19:41:51 +070089 index: usize,
90}
91
David Tolnay4074ad22020-04-24 18:20:11 -070092impl<'a, T> IntoIterator for &'a CxxVector<T>
93where
94 T: VectorElement,
95{
Myron Ahneba35cf2020-02-05 19:41:51 +070096 type Item = &'a T;
David Tolnay3d88bdc2020-04-24 13:48:18 -070097 type IntoIter = Iter<'a, T>;
Myron Ahneba35cf2020-02-05 19:41:51 +070098
99 fn into_iter(self) -> Self::IntoIter {
David Tolnay3d88bdc2020-04-24 13:48:18 -0700100 Iter { v: self, index: 0 }
Myron Ahneba35cf2020-02-05 19:41:51 +0700101 }
102}
103
David Tolnay4074ad22020-04-24 18:20:11 -0700104impl<'a, T> Iterator for Iter<'a, T>
105where
106 T: VectorElement,
107{
Myron Ahneba35cf2020-02-05 19:41:51 +0700108 type Item = &'a T;
David Tolnay85db5a02020-04-25 13:17:27 -0700109
Myron Ahneba35cf2020-02-05 19:41:51 +0700110 fn next(&mut self) -> Option<Self::Item> {
David Tolnay39ee0ed2020-05-05 10:12:29 -0700111 let next = self.v.get(self.index);
112 self.index += 1;
113 next
Myron Ahneba35cf2020-02-05 19:41:51 +0700114 }
115}
116
David Tolnay3b40b6f2020-04-24 17:58:24 -0700117pub struct TypeName<T> {
118 element: PhantomData<T>,
119}
120
121impl<T> TypeName<T> {
122 pub const fn new() -> Self {
123 TypeName {
124 element: PhantomData,
125 }
126 }
127}
128
129impl<T> Display for TypeName<T>
130where
131 T: VectorElement,
132{
133 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
134 write!(formatter, "CxxVector<{}>", T::__NAME)
135 }
136}
137
David Tolnay5104c862020-04-24 13:26:01 -0700138// Methods are private; not intended to be implemented outside of cxxbridge
139// codebase.
David Tolnay1b341192020-04-24 13:04:04 -0700140#[doc(hidden)]
David Tolnayc3ed3a62020-04-24 13:34:50 -0700141pub unsafe trait VectorElement: Sized {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700142 const __NAME: &'static dyn Display;
David Tolnay0e084662020-04-24 14:02:51 -0700143 fn __vector_size(v: &CxxVector<Self>) -> usize;
David Tolnay93637ca2020-09-24 15:58:20 -0400144 unsafe fn __get_unchecked(v: &CxxVector<Self>, pos: usize) -> *const Self;
David Tolnay3b40b6f2020-04-24 17:58:24 -0700145 fn __unique_ptr_null() -> *mut c_void;
146 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void;
147 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self>;
148 unsafe fn __unique_ptr_release(repr: *mut c_void) -> *mut CxxVector<Self>;
149 unsafe fn __unique_ptr_drop(repr: *mut c_void);
David Tolnay1b341192020-04-24 13:04:04 -0700150}
151
David Tolnay47e239d2020-08-28 00:32:04 -0700152macro_rules! impl_vector_element {
153 ($segment:expr, $name:expr, $ty:ty) => {
David Tolnayf0446632020-04-25 11:29:26 -0700154 const_assert_eq!(1, mem::align_of::<CxxVector<$ty>>());
155
David Tolnaye4b6a622020-04-24 14:55:42 -0700156 unsafe impl VectorElement for $ty {
David Tolnay47e239d2020-08-28 00:32:04 -0700157 const __NAME: &'static dyn Display = &$name;
David Tolnaye4b6a622020-04-24 14:55:42 -0700158 fn __vector_size(v: &CxxVector<$ty>) -> usize {
159 extern "C" {
160 attr! {
David Tolnay8f16ae72020-10-08 18:21:13 -0700161 #[link_name = concat!("cxxbridge05$std$vector$", $segment, "$size")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700162 fn __vector_size(_: &CxxVector<$ty>) -> usize;
163 }
164 }
165 unsafe { __vector_size(v) }
166 }
David Tolnay93637ca2020-09-24 15:58:20 -0400167 unsafe fn __get_unchecked(v: &CxxVector<$ty>, pos: usize) -> *const $ty {
David Tolnaye4b6a622020-04-24 14:55:42 -0700168 extern "C" {
169 attr! {
David Tolnay8f16ae72020-10-08 18:21:13 -0700170 #[link_name = concat!("cxxbridge05$std$vector$", $segment, "$get_unchecked")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700171 fn __get_unchecked(_: &CxxVector<$ty>, _: usize) -> *const $ty;
172 }
173 }
David Tolnay93637ca2020-09-24 15:58:20 -0400174 __get_unchecked(v, pos)
David Tolnaye4b6a622020-04-24 14:55:42 -0700175 }
David Tolnay3b40b6f2020-04-24 17:58:24 -0700176 fn __unique_ptr_null() -> *mut c_void {
177 extern "C" {
178 attr! {
David Tolnay8f16ae72020-10-08 18:21:13 -0700179 #[link_name = concat!("cxxbridge05$unique_ptr$std$vector$", $segment, "$null")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700180 fn __unique_ptr_null(this: *mut *mut c_void);
181 }
182 }
183 let mut repr = ptr::null_mut::<c_void>();
184 unsafe { __unique_ptr_null(&mut repr) }
185 repr
186 }
187 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void {
188 extern "C" {
189 attr! {
David Tolnay8f16ae72020-10-08 18:21:13 -0700190 #[link_name = concat!("cxxbridge05$unique_ptr$std$vector$", $segment, "$raw")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700191 fn __unique_ptr_raw(this: *mut *mut c_void, raw: *mut CxxVector<$ty>);
192 }
193 }
194 let mut repr = ptr::null_mut::<c_void>();
195 __unique_ptr_raw(&mut repr, raw);
196 repr
197 }
198 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self> {
199 extern "C" {
200 attr! {
David Tolnay8f16ae72020-10-08 18:21:13 -0700201 #[link_name = concat!("cxxbridge05$unique_ptr$std$vector$", $segment, "$get")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700202 fn __unique_ptr_get(this: *const *mut c_void) -> *const CxxVector<$ty>;
203 }
204 }
205 __unique_ptr_get(&repr)
206 }
207 unsafe fn __unique_ptr_release(mut repr: *mut c_void) -> *mut CxxVector<Self> {
208 extern "C" {
209 attr! {
David Tolnay8f16ae72020-10-08 18:21:13 -0700210 #[link_name = concat!("cxxbridge05$unique_ptr$std$vector$", $segment, "$release")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700211 fn __unique_ptr_release(this: *mut *mut c_void) -> *mut CxxVector<$ty>;
212 }
213 }
214 __unique_ptr_release(&mut repr)
215 }
216 unsafe fn __unique_ptr_drop(mut repr: *mut c_void) {
217 extern "C" {
218 attr! {
David Tolnay8f16ae72020-10-08 18:21:13 -0700219 #[link_name = concat!("cxxbridge05$unique_ptr$std$vector$", $segment, "$drop")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700220 fn __unique_ptr_drop(this: *mut *mut c_void);
221 }
222 }
223 __unique_ptr_drop(&mut repr);
224 }
David Tolnaye4b6a622020-04-24 14:55:42 -0700225 }
226 };
227}
228
David Tolnay47e239d2020-08-28 00:32:04 -0700229macro_rules! impl_vector_element_for_primitive {
230 ($ty:ident) => {
231 impl_vector_element!(stringify!($ty), stringify!($ty), $ty);
232 };
233}
234
David Tolnay4b91eaa2020-04-24 14:19:22 -0700235impl_vector_element_for_primitive!(u8);
236impl_vector_element_for_primitive!(u16);
237impl_vector_element_for_primitive!(u32);
238impl_vector_element_for_primitive!(u64);
239impl_vector_element_for_primitive!(usize);
240impl_vector_element_for_primitive!(i8);
241impl_vector_element_for_primitive!(i16);
242impl_vector_element_for_primitive!(i32);
243impl_vector_element_for_primitive!(i64);
244impl_vector_element_for_primitive!(isize);
245impl_vector_element_for_primitive!(f32);
246impl_vector_element_for_primitive!(f64);
David Tolnay47e239d2020-08-28 00:32:04 -0700247
248impl_vector_element!("string", "CxxString", CxxString);