blob: b8de942ec044bed8e3056108678fa2d3f35f11eb [file] [log] [blame]
David Tolnay47e239d2020-08-28 00:32:04 -07001use crate::cxx_string::CxxString;
David Tolnay181ee912020-12-04 12:15:10 -08002use crate::extern_type::ExternType;
3use crate::kind::Trivial;
David Tolnay3384c142020-09-14 00:26:47 -04004use core::ffi::c_void;
5use core::fmt::{self, Display};
David Tolnay95dab1d2020-11-15 14:32:37 -08006use core::marker::{PhantomData, PhantomPinned};
David Tolnay3384c142020-09-14 00:26:47 -04007use core::mem;
8use core::ptr;
David Tolnay93637ca2020-09-24 15:58:20 -04009use core::slice;
David Tolnay4f7e6fa2020-04-24 11:52:44 -070010
David Tolnay61a9fdf2020-04-24 16:19:42 -070011/// Binding to C++ `std::vector<T, std::allocator<T>>`.
Myron Ahneba35cf2020-02-05 19:41:51 +070012///
13/// # Invariants
14///
15/// As an invariant of this API and the static analysis of the cxx::bridge
David Tolnay5fe93632020-04-24 12:31:00 -070016/// macro, in Rust code we can never obtain a `CxxVector` by value. Instead in
17/// Rust code we will only ever look at a vector behind a reference or smart
18/// pointer, as in `&CxxVector<T>` or `UniquePtr<CxxVector<T>>`.
David Tolnay4f7e6fa2020-04-24 11:52:44 -070019#[repr(C, packed)]
David Tolnaye90be1d2020-04-24 11:45:57 -070020pub struct CxxVector<T> {
Myron Ahneba35cf2020-02-05 19:41:51 +070021 _private: [T; 0],
David Tolnay95dab1d2020-11-15 14:32:37 -080022 _pinned: PhantomData<PhantomPinned>,
Myron Ahneba35cf2020-02-05 19:41:51 +070023}
24
David Tolnay4074ad22020-04-24 18:20:11 -070025impl<T> CxxVector<T>
26where
27 T: VectorElement,
28{
David Tolnaycdc87962020-04-24 13:45:59 -070029 /// Returns the number of elements in the vector.
David Tolnaydd839192020-04-24 16:41:29 -070030 ///
31 /// Matches the behavior of C++ [std::vector\<T\>::size][size].
32 ///
33 /// [size]: https://en.cppreference.com/w/cpp/container/vector/size
David Tolnayc01d0a02020-04-24 13:30:44 -070034 pub fn len(&self) -> usize {
David Tolnay0e084662020-04-24 14:02:51 -070035 T::__vector_size(self)
Myron Ahneba35cf2020-02-05 19:41:51 +070036 }
37
David Tolnaycdc87962020-04-24 13:45:59 -070038 /// Returns true if the vector contains no elements.
David Tolnaydd839192020-04-24 16:41:29 -070039 ///
40 /// Matches the behavior of C++ [std::vector\<T\>::empty][empty].
41 ///
42 /// [empty]: https://en.cppreference.com/w/cpp/container/vector/empty
Myron Ahneba35cf2020-02-05 19:41:51 +070043 pub fn is_empty(&self) -> bool {
David Tolnayc01d0a02020-04-24 13:30:44 -070044 self.len() == 0
Myron Ahneba35cf2020-02-05 19:41:51 +070045 }
46
David Tolnaycdc87962020-04-24 13:45:59 -070047 /// Returns a reference to an element at the given position, or `None` if
48 /// out of bounds.
Myron Ahneba35cf2020-02-05 19:41:51 +070049 pub fn get(&self, pos: usize) -> Option<&T> {
David Tolnayc01d0a02020-04-24 13:30:44 -070050 if pos < self.len() {
David Tolnay93637ca2020-09-24 15:58:20 -040051 Some(unsafe { self.get_unchecked(pos) })
Myron Ahneba35cf2020-02-05 19:41:51 +070052 } else {
53 None
54 }
55 }
56
David Tolnay4944f2f2020-04-24 13:46:12 -070057 /// Returns a reference to an element without doing bounds checking.
58 ///
59 /// This is generally not recommended, use with caution! Calling this method
60 /// with an out-of-bounds index is undefined behavior even if the resulting
61 /// reference is not used.
David Tolnaydd839192020-04-24 16:41:29 -070062 ///
63 /// Matches the behavior of C++
64 /// [std::vector\<T\>::operator\[\]][operator_at].
65 ///
66 /// [operator_at]: https://en.cppreference.com/w/cpp/container/vector/operator_at
David Tolnay4944f2f2020-04-24 13:46:12 -070067 pub unsafe fn get_unchecked(&self, pos: usize) -> &T {
David Tolnay93637ca2020-09-24 15:58:20 -040068 &*T::__get_unchecked(self, pos)
69 }
70
71 /// Returns a slice to the underlying contiguous array of elements.
David Tolnay181ee912020-12-04 12:15:10 -080072 pub fn as_slice(&self) -> &[T]
73 where
74 T: ExternType<Kind = Trivial>,
75 {
David Tolnay93637ca2020-09-24 15:58:20 -040076 let len = self.len();
77 if len == 0 {
David Tolnaya5a14ce2020-09-24 16:02:40 -040078 // The slice::from_raw_parts in the other branch requires a nonnull
79 // and properly aligned data ptr. C++ standard does not guarantee
80 // that data() on a vector with size 0 would return a nonnull
81 // pointer or sufficiently aligned pointer, so using it would be
82 // undefined behavior. Create our own empty slice in Rust instead
83 // which upholds the invariants.
David Tolnayacc7fb02020-09-24 18:10:09 -040084 &[]
David Tolnay93637ca2020-09-24 15:58:20 -040085 } else {
86 let ptr = unsafe { T::__get_unchecked(self, 0) };
87 unsafe { slice::from_raw_parts(ptr, len) }
88 }
David Tolnay4944f2f2020-04-24 13:46:12 -070089 }
David Tolnay4f71cc52020-11-15 23:55:27 -080090
91 /// Returns an iterator over elements of type `&T`.
92 pub fn iter(&self) -> Iter<T> {
93 Iter { v: self, index: 0 }
94 }
Myron Ahneba35cf2020-02-05 19:41:51 +070095}
96
David Tolnay3d88bdc2020-04-24 13:48:18 -070097pub struct Iter<'a, T> {
David Tolnaye90be1d2020-04-24 11:45:57 -070098 v: &'a CxxVector<T>,
Myron Ahneba35cf2020-02-05 19:41:51 +070099 index: usize,
100}
101
David Tolnay4074ad22020-04-24 18:20:11 -0700102impl<'a, T> IntoIterator for &'a CxxVector<T>
103where
104 T: VectorElement,
105{
Myron Ahneba35cf2020-02-05 19:41:51 +0700106 type Item = &'a T;
David Tolnay3d88bdc2020-04-24 13:48:18 -0700107 type IntoIter = Iter<'a, T>;
Myron Ahneba35cf2020-02-05 19:41:51 +0700108
109 fn into_iter(self) -> Self::IntoIter {
David Tolnay4f71cc52020-11-15 23:55:27 -0800110 self.iter()
Myron Ahneba35cf2020-02-05 19:41:51 +0700111 }
112}
113
David Tolnay4074ad22020-04-24 18:20:11 -0700114impl<'a, T> Iterator for Iter<'a, T>
115where
116 T: VectorElement,
117{
Myron Ahneba35cf2020-02-05 19:41:51 +0700118 type Item = &'a T;
David Tolnay85db5a02020-04-25 13:17:27 -0700119
Myron Ahneba35cf2020-02-05 19:41:51 +0700120 fn next(&mut self) -> Option<Self::Item> {
David Tolnay39ee0ed2020-05-05 10:12:29 -0700121 let next = self.v.get(self.index);
122 self.index += 1;
123 next
Myron Ahneba35cf2020-02-05 19:41:51 +0700124 }
125}
126
David Tolnay3b40b6f2020-04-24 17:58:24 -0700127pub struct TypeName<T> {
128 element: PhantomData<T>,
129}
130
131impl<T> TypeName<T> {
132 pub const fn new() -> Self {
133 TypeName {
134 element: PhantomData,
135 }
136 }
137}
138
139impl<T> Display for TypeName<T>
140where
141 T: VectorElement,
142{
143 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
144 write!(formatter, "CxxVector<{}>", T::__NAME)
145 }
146}
147
David Tolnay5104c862020-04-24 13:26:01 -0700148// Methods are private; not intended to be implemented outside of cxxbridge
149// codebase.
David Tolnay1b341192020-04-24 13:04:04 -0700150#[doc(hidden)]
David Tolnayc3ed3a62020-04-24 13:34:50 -0700151pub unsafe trait VectorElement: Sized {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700152 const __NAME: &'static dyn Display;
David Tolnay0e084662020-04-24 14:02:51 -0700153 fn __vector_size(v: &CxxVector<Self>) -> usize;
David Tolnay93637ca2020-09-24 15:58:20 -0400154 unsafe fn __get_unchecked(v: &CxxVector<Self>, pos: usize) -> *const Self;
David Tolnay3b40b6f2020-04-24 17:58:24 -0700155 fn __unique_ptr_null() -> *mut c_void;
156 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void;
157 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self>;
158 unsafe fn __unique_ptr_release(repr: *mut c_void) -> *mut CxxVector<Self>;
159 unsafe fn __unique_ptr_drop(repr: *mut c_void);
David Tolnay1b341192020-04-24 13:04:04 -0700160}
161
David Tolnay47e239d2020-08-28 00:32:04 -0700162macro_rules! impl_vector_element {
163 ($segment:expr, $name:expr, $ty:ty) => {
David Tolnayf0446632020-04-25 11:29:26 -0700164 const_assert_eq!(1, mem::align_of::<CxxVector<$ty>>());
165
David Tolnaye4b6a622020-04-24 14:55:42 -0700166 unsafe impl VectorElement for $ty {
David Tolnay47e239d2020-08-28 00:32:04 -0700167 const __NAME: &'static dyn Display = &$name;
David Tolnaye4b6a622020-04-24 14:55:42 -0700168 fn __vector_size(v: &CxxVector<$ty>) -> usize {
169 extern "C" {
170 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800171 #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$size")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700172 fn __vector_size(_: &CxxVector<$ty>) -> usize;
173 }
174 }
175 unsafe { __vector_size(v) }
176 }
David Tolnay93637ca2020-09-24 15:58:20 -0400177 unsafe fn __get_unchecked(v: &CxxVector<$ty>, pos: usize) -> *const $ty {
David Tolnaye4b6a622020-04-24 14:55:42 -0700178 extern "C" {
179 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800180 #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$get_unchecked")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700181 fn __get_unchecked(_: &CxxVector<$ty>, _: usize) -> *const $ty;
182 }
183 }
David Tolnay93637ca2020-09-24 15:58:20 -0400184 __get_unchecked(v, pos)
David Tolnaye4b6a622020-04-24 14:55:42 -0700185 }
David Tolnay3b40b6f2020-04-24 17:58:24 -0700186 fn __unique_ptr_null() -> *mut c_void {
187 extern "C" {
188 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800189 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$null")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700190 fn __unique_ptr_null(this: *mut *mut c_void);
191 }
192 }
193 let mut repr = ptr::null_mut::<c_void>();
194 unsafe { __unique_ptr_null(&mut repr) }
195 repr
196 }
197 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void {
198 extern "C" {
199 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800200 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$raw")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700201 fn __unique_ptr_raw(this: *mut *mut c_void, raw: *mut CxxVector<$ty>);
202 }
203 }
204 let mut repr = ptr::null_mut::<c_void>();
205 __unique_ptr_raw(&mut repr, raw);
206 repr
207 }
208 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self> {
209 extern "C" {
210 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800211 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$get")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700212 fn __unique_ptr_get(this: *const *mut c_void) -> *const CxxVector<$ty>;
213 }
214 }
215 __unique_ptr_get(&repr)
216 }
217 unsafe fn __unique_ptr_release(mut repr: *mut c_void) -> *mut CxxVector<Self> {
218 extern "C" {
219 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800220 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$release")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700221 fn __unique_ptr_release(this: *mut *mut c_void) -> *mut CxxVector<$ty>;
222 }
223 }
224 __unique_ptr_release(&mut repr)
225 }
226 unsafe fn __unique_ptr_drop(mut repr: *mut c_void) {
227 extern "C" {
228 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800229 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$drop")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700230 fn __unique_ptr_drop(this: *mut *mut c_void);
231 }
232 }
233 __unique_ptr_drop(&mut repr);
234 }
David Tolnaye4b6a622020-04-24 14:55:42 -0700235 }
236 };
237}
238
David Tolnay47e239d2020-08-28 00:32:04 -0700239macro_rules! impl_vector_element_for_primitive {
240 ($ty:ident) => {
241 impl_vector_element!(stringify!($ty), stringify!($ty), $ty);
242 };
243}
244
David Tolnay4b91eaa2020-04-24 14:19:22 -0700245impl_vector_element_for_primitive!(u8);
246impl_vector_element_for_primitive!(u16);
247impl_vector_element_for_primitive!(u32);
248impl_vector_element_for_primitive!(u64);
249impl_vector_element_for_primitive!(usize);
250impl_vector_element_for_primitive!(i8);
251impl_vector_element_for_primitive!(i16);
252impl_vector_element_for_primitive!(i32);
253impl_vector_element_for_primitive!(i64);
254impl_vector_element_for_primitive!(isize);
255impl_vector_element_for_primitive!(f32);
256impl_vector_element_for_primitive!(f64);
David Tolnay47e239d2020-08-28 00:32:04 -0700257
258impl_vector_element!("string", "CxxString", CxxString);