blob: d78ee478ad7b4bd2149b43b772e061e5c472fdc0 [file] [log] [blame]
David Tolnayb5d039c2020-12-12 23:21:17 -08001//! Less used details of `CxxVector` are exposed in this module. `CxxVector`
2//! itself is exposed at the crate root.
3
David Tolnay181ee912020-12-04 12:15:10 -08004use crate::extern_type::ExternType;
5use crate::kind::Trivial;
David Tolnaybac25822020-12-12 23:13:51 -08006use crate::string::CxxString;
David Tolnay3384c142020-09-14 00:26:47 -04007use core::ffi::c_void;
David Tolnaya8100ed2020-12-04 12:41:24 -08008use core::fmt::{self, Debug, Display};
David Tolnay526faa22020-12-13 16:10:47 -08009use core::iter::FusedIterator;
David Tolnay95dab1d2020-11-15 14:32:37 -080010use core::marker::{PhantomData, PhantomPinned};
David Tolnay3384c142020-09-14 00:26:47 -040011use core::mem;
David Tolnay767e00d2020-12-21 17:12:27 -080012use core::pin::Pin;
David Tolnay3384c142020-09-14 00:26:47 -040013use core::ptr;
David Tolnay93637ca2020-09-24 15:58:20 -040014use core::slice;
David Tolnay4f7e6fa2020-04-24 11:52:44 -070015
David Tolnayb5d039c2020-12-12 23:21:17 -080016#[doc(inline)]
17pub use crate::Vector;
18
David Tolnay61a9fdf2020-04-24 16:19:42 -070019/// Binding to C++ `std::vector<T, std::allocator<T>>`.
Myron Ahneba35cf2020-02-05 19:41:51 +070020///
21/// # Invariants
22///
23/// As an invariant of this API and the static analysis of the cxx::bridge
David Tolnay5fe93632020-04-24 12:31:00 -070024/// macro, in Rust code we can never obtain a `CxxVector` by value. Instead in
25/// Rust code we will only ever look at a vector behind a reference or smart
26/// pointer, as in `&CxxVector<T>` or `UniquePtr<CxxVector<T>>`.
David Tolnay4f7e6fa2020-04-24 11:52:44 -070027#[repr(C, packed)]
David Tolnaye90be1d2020-04-24 11:45:57 -070028pub struct CxxVector<T> {
Myron Ahneba35cf2020-02-05 19:41:51 +070029 _private: [T; 0],
David Tolnay95dab1d2020-11-15 14:32:37 -080030 _pinned: PhantomData<PhantomPinned>,
Myron Ahneba35cf2020-02-05 19:41:51 +070031}
32
David Tolnay4074ad22020-04-24 18:20:11 -070033impl<T> CxxVector<T>
34where
35 T: VectorElement,
36{
David Tolnaycdc87962020-04-24 13:45:59 -070037 /// Returns the number of elements in the vector.
David Tolnaydd839192020-04-24 16:41:29 -070038 ///
39 /// Matches the behavior of C++ [std::vector\<T\>::size][size].
40 ///
41 /// [size]: https://en.cppreference.com/w/cpp/container/vector/size
David Tolnayc01d0a02020-04-24 13:30:44 -070042 pub fn len(&self) -> usize {
David Tolnay0e084662020-04-24 14:02:51 -070043 T::__vector_size(self)
Myron Ahneba35cf2020-02-05 19:41:51 +070044 }
45
David Tolnaycdc87962020-04-24 13:45:59 -070046 /// Returns true if the vector contains no elements.
David Tolnaydd839192020-04-24 16:41:29 -070047 ///
48 /// Matches the behavior of C++ [std::vector\<T\>::empty][empty].
49 ///
50 /// [empty]: https://en.cppreference.com/w/cpp/container/vector/empty
Myron Ahneba35cf2020-02-05 19:41:51 +070051 pub fn is_empty(&self) -> bool {
David Tolnayc01d0a02020-04-24 13:30:44 -070052 self.len() == 0
Myron Ahneba35cf2020-02-05 19:41:51 +070053 }
54
David Tolnaycdc87962020-04-24 13:45:59 -070055 /// Returns a reference to an element at the given position, or `None` if
56 /// out of bounds.
Myron Ahneba35cf2020-02-05 19:41:51 +070057 pub fn get(&self, pos: usize) -> Option<&T> {
David Tolnayc01d0a02020-04-24 13:30:44 -070058 if pos < self.len() {
David Tolnay93637ca2020-09-24 15:58:20 -040059 Some(unsafe { self.get_unchecked(pos) })
Myron Ahneba35cf2020-02-05 19:41:51 +070060 } else {
61 None
62 }
63 }
64
David Tolnay767e00d2020-12-21 17:12:27 -080065 /// Returns a pinned mutable reference to an element at the given position,
66 /// or `None` if out of bounds.
David Tolnay5b395b32020-12-31 10:44:26 -080067 pub fn index_mut(self: Pin<&mut Self>, pos: usize) -> Option<Pin<&mut T>> {
David Tolnay767e00d2020-12-21 17:12:27 -080068 if pos < self.len() {
David Tolnay5b395b32020-12-31 10:44:26 -080069 Some(unsafe { self.index_unchecked_mut(pos) })
David Tolnay767e00d2020-12-21 17:12:27 -080070 } else {
71 None
72 }
73 }
74
David Tolnay4944f2f2020-04-24 13:46:12 -070075 /// Returns a reference to an element without doing bounds checking.
76 ///
77 /// This is generally not recommended, use with caution! Calling this method
78 /// with an out-of-bounds index is undefined behavior even if the resulting
79 /// reference is not used.
David Tolnaydd839192020-04-24 16:41:29 -070080 ///
81 /// Matches the behavior of C++
David Tolnay767e00d2020-12-21 17:12:27 -080082 /// [std::vector\<T\>::operator\[\] const][operator_at].
83 ///
84 /// [operator_at]: https://en.cppreference.com/w/cpp/container/vector/operator_at
85 pub unsafe fn get_unchecked(&self, pos: usize) -> &T {
86 let this = self as *const CxxVector<T> as *mut CxxVector<T>;
87 let ptr = T::__get_unchecked(this, pos) as *const T;
88 &*ptr
89 }
90
91 /// Returns a pinned mutable reference to an element without doing bounds
92 /// checking.
93 ///
94 /// This is generally not recommended, use with caution! Calling this method
95 /// with an out-of-bounds index is undefined behavior even if the resulting
96 /// reference is not used.
97 ///
98 /// Matches the behavior of C++
David Tolnaydd839192020-04-24 16:41:29 -070099 /// [std::vector\<T\>::operator\[\]][operator_at].
100 ///
101 /// [operator_at]: https://en.cppreference.com/w/cpp/container/vector/operator_at
David Tolnay5b395b32020-12-31 10:44:26 -0800102 pub unsafe fn index_unchecked_mut(self: Pin<&mut Self>, pos: usize) -> Pin<&mut T> {
103 let ptr = T::__get_unchecked(self.get_unchecked_mut(), pos);
David Tolnay767e00d2020-12-21 17:12:27 -0800104 Pin::new_unchecked(&mut *ptr)
David Tolnay93637ca2020-09-24 15:58:20 -0400105 }
106
107 /// Returns a slice to the underlying contiguous array of elements.
David Tolnay181ee912020-12-04 12:15:10 -0800108 pub fn as_slice(&self) -> &[T]
109 where
110 T: ExternType<Kind = Trivial>,
111 {
David Tolnay93637ca2020-09-24 15:58:20 -0400112 let len = self.len();
113 if len == 0 {
David Tolnaya5a14ce2020-09-24 16:02:40 -0400114 // The slice::from_raw_parts in the other branch requires a nonnull
115 // and properly aligned data ptr. C++ standard does not guarantee
116 // that data() on a vector with size 0 would return a nonnull
117 // pointer or sufficiently aligned pointer, so using it would be
118 // undefined behavior. Create our own empty slice in Rust instead
119 // which upholds the invariants.
David Tolnayacc7fb02020-09-24 18:10:09 -0400120 &[]
David Tolnay93637ca2020-09-24 15:58:20 -0400121 } else {
David Tolnay767e00d2020-12-21 17:12:27 -0800122 let this = self as *const CxxVector<T> as *mut CxxVector<T>;
123 let ptr = unsafe { T::__get_unchecked(this, 0) };
David Tolnay93637ca2020-09-24 15:58:20 -0400124 unsafe { slice::from_raw_parts(ptr, len) }
125 }
David Tolnay4944f2f2020-04-24 13:46:12 -0700126 }
David Tolnay4f71cc52020-11-15 23:55:27 -0800127
David Tolnayab1ac882020-12-31 11:54:37 -0800128 /// Returns a slice to the underlying contiguous array of elements by
129 /// mutable reference.
130 pub fn as_mut_slice(self: Pin<&mut Self>) -> &mut [T]
131 where
132 T: ExternType<Kind = Trivial>,
133 {
134 let len = self.len();
135 if len == 0 {
136 &mut []
137 } else {
138 let ptr = unsafe { T::__get_unchecked(self.get_unchecked_mut(), 0) };
139 unsafe { slice::from_raw_parts_mut(ptr, len) }
140 }
141 }
142
David Tolnay4f71cc52020-11-15 23:55:27 -0800143 /// Returns an iterator over elements of type `&T`.
144 pub fn iter(&self) -> Iter<T> {
145 Iter { v: self, index: 0 }
146 }
David Tolnay26a52922020-12-21 17:29:04 -0800147
148 /// Returns an iterator over elements of type `Pin<&mut T>`.
David Tolnay30bea1c2020-12-31 10:41:42 -0800149 pub fn iter_mut(self: Pin<&mut Self>) -> IterMut<T> {
David Tolnay26a52922020-12-21 17:29:04 -0800150 IterMut { v: self, index: 0 }
151 }
Myron Ahneba35cf2020-02-05 19:41:51 +0700152}
153
David Tolnayb5d039c2020-12-12 23:21:17 -0800154/// Iterator over elements of a `CxxVector` by shared reference.
155///
156/// The iterator element type is `&'a T`.
David Tolnay3d88bdc2020-04-24 13:48:18 -0700157pub struct Iter<'a, T> {
David Tolnaye90be1d2020-04-24 11:45:57 -0700158 v: &'a CxxVector<T>,
Myron Ahneba35cf2020-02-05 19:41:51 +0700159 index: usize,
160}
161
David Tolnay4074ad22020-04-24 18:20:11 -0700162impl<'a, T> IntoIterator for &'a CxxVector<T>
163where
164 T: VectorElement,
165{
Myron Ahneba35cf2020-02-05 19:41:51 +0700166 type Item = &'a T;
David Tolnay3d88bdc2020-04-24 13:48:18 -0700167 type IntoIter = Iter<'a, T>;
Myron Ahneba35cf2020-02-05 19:41:51 +0700168
169 fn into_iter(self) -> Self::IntoIter {
David Tolnay4f71cc52020-11-15 23:55:27 -0800170 self.iter()
Myron Ahneba35cf2020-02-05 19:41:51 +0700171 }
172}
173
David Tolnay4074ad22020-04-24 18:20:11 -0700174impl<'a, T> Iterator for Iter<'a, T>
175where
176 T: VectorElement,
177{
Myron Ahneba35cf2020-02-05 19:41:51 +0700178 type Item = &'a T;
David Tolnay85db5a02020-04-25 13:17:27 -0700179
Myron Ahneba35cf2020-02-05 19:41:51 +0700180 fn next(&mut self) -> Option<Self::Item> {
David Tolnay0d527172020-12-21 17:35:24 -0800181 let next = self.v.get(self.index)?;
182 self.index += 1;
183 Some(next)
Myron Ahneba35cf2020-02-05 19:41:51 +0700184 }
David Tolnay724ac752020-12-13 16:00:48 -0800185
186 fn size_hint(&self) -> (usize, Option<usize>) {
187 let len = self.len();
188 (len, Some(len))
189 }
190}
191
192impl<'a, T> ExactSizeIterator for Iter<'a, T>
193where
194 T: VectorElement,
195{
196 fn len(&self) -> usize {
197 self.v.len() - self.index
198 }
Myron Ahneba35cf2020-02-05 19:41:51 +0700199}
200
David Tolnay526faa22020-12-13 16:10:47 -0800201impl<'a, T> FusedIterator for Iter<'a, T> where T: VectorElement {}
202
David Tolnay26a52922020-12-21 17:29:04 -0800203/// Iterator over elements of a `CxxVector` by pinned mutable reference.
204///
205/// The iterator element type is `Pin<&'a mut T>`.
206pub struct IterMut<'a, T> {
David Tolnay30bea1c2020-12-31 10:41:42 -0800207 v: Pin<&'a mut CxxVector<T>>,
David Tolnay26a52922020-12-21 17:29:04 -0800208 index: usize,
209}
210
David Tolnay30bea1c2020-12-31 10:41:42 -0800211impl<'a, T> IntoIterator for Pin<&'a mut CxxVector<T>>
David Tolnay26a52922020-12-21 17:29:04 -0800212where
213 T: VectorElement,
214{
215 type Item = Pin<&'a mut T>;
216 type IntoIter = IterMut<'a, T>;
217
218 fn into_iter(self) -> Self::IntoIter {
219 self.iter_mut()
220 }
221}
222
223impl<'a, T> Iterator for IterMut<'a, T>
224where
225 T: VectorElement,
226{
227 type Item = Pin<&'a mut T>;
228
229 fn next(&mut self) -> Option<Self::Item> {
David Tolnay5b395b32020-12-31 10:44:26 -0800230 let next = self.v.as_mut().index_mut(self.index)?;
David Tolnay26a52922020-12-21 17:29:04 -0800231 self.index += 1;
232 // Extend lifetime to allow simultaneous holding of nonoverlapping
233 // elements, analogous to slice::split_first_mut.
234 unsafe {
235 let ptr = Pin::into_inner_unchecked(next) as *mut T;
236 Some(Pin::new_unchecked(&mut *ptr))
237 }
238 }
239
240 fn size_hint(&self) -> (usize, Option<usize>) {
241 let len = self.len();
242 (len, Some(len))
243 }
244}
245
246impl<'a, T> ExactSizeIterator for IterMut<'a, T>
247where
248 T: VectorElement,
249{
250 fn len(&self) -> usize {
251 self.v.len() - self.index
252 }
253}
254
255impl<'a, T> FusedIterator for IterMut<'a, T> where T: VectorElement {}
256
David Tolnaya8100ed2020-12-04 12:41:24 -0800257impl<T> Debug for CxxVector<T>
258where
259 T: VectorElement + Debug,
260{
261 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
262 formatter.debug_list().entries(self).finish()
263 }
264}
265
David Tolnayb5d039c2020-12-12 23:21:17 -0800266pub(crate) struct TypeName<T> {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700267 element: PhantomData<T>,
268}
269
270impl<T> TypeName<T> {
271 pub const fn new() -> Self {
272 TypeName {
273 element: PhantomData,
274 }
275 }
276}
277
278impl<T> Display for TypeName<T>
279where
280 T: VectorElement,
281{
282 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
283 write!(formatter, "CxxVector<{}>", T::__NAME)
284 }
285}
286
David Tolnay5104c862020-04-24 13:26:01 -0700287// Methods are private; not intended to be implemented outside of cxxbridge
288// codebase.
David Tolnay1b341192020-04-24 13:04:04 -0700289#[doc(hidden)]
David Tolnayc3ed3a62020-04-24 13:34:50 -0700290pub unsafe trait VectorElement: Sized {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700291 const __NAME: &'static dyn Display;
David Tolnay0e084662020-04-24 14:02:51 -0700292 fn __vector_size(v: &CxxVector<Self>) -> usize;
David Tolnay767e00d2020-12-21 17:12:27 -0800293 unsafe fn __get_unchecked(v: *mut CxxVector<Self>, pos: usize) -> *mut Self;
David Tolnay3b40b6f2020-04-24 17:58:24 -0700294 fn __unique_ptr_null() -> *mut c_void;
295 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void;
296 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self>;
297 unsafe fn __unique_ptr_release(repr: *mut c_void) -> *mut CxxVector<Self>;
298 unsafe fn __unique_ptr_drop(repr: *mut c_void);
David Tolnay1b341192020-04-24 13:04:04 -0700299}
300
David Tolnay47e239d2020-08-28 00:32:04 -0700301macro_rules! impl_vector_element {
302 ($segment:expr, $name:expr, $ty:ty) => {
David Tolnayf0446632020-04-25 11:29:26 -0700303 const_assert_eq!(1, mem::align_of::<CxxVector<$ty>>());
304
David Tolnaye4b6a622020-04-24 14:55:42 -0700305 unsafe impl VectorElement for $ty {
David Tolnay47e239d2020-08-28 00:32:04 -0700306 const __NAME: &'static dyn Display = &$name;
David Tolnaye4b6a622020-04-24 14:55:42 -0700307 fn __vector_size(v: &CxxVector<$ty>) -> usize {
308 extern "C" {
309 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800310 #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$size")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700311 fn __vector_size(_: &CxxVector<$ty>) -> usize;
312 }
313 }
314 unsafe { __vector_size(v) }
315 }
David Tolnay767e00d2020-12-21 17:12:27 -0800316 unsafe fn __get_unchecked(v: *mut CxxVector<$ty>, pos: usize) -> *mut $ty {
David Tolnaye4b6a622020-04-24 14:55:42 -0700317 extern "C" {
318 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800319 #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$get_unchecked")]
David Tolnay767e00d2020-12-21 17:12:27 -0800320 fn __get_unchecked(_: *mut CxxVector<$ty>, _: usize) -> *mut $ty;
David Tolnaye4b6a622020-04-24 14:55:42 -0700321 }
322 }
David Tolnay93637ca2020-09-24 15:58:20 -0400323 __get_unchecked(v, pos)
David Tolnaye4b6a622020-04-24 14:55:42 -0700324 }
David Tolnay3b40b6f2020-04-24 17:58:24 -0700325 fn __unique_ptr_null() -> *mut c_void {
326 extern "C" {
327 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800328 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$null")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700329 fn __unique_ptr_null(this: *mut *mut c_void);
330 }
331 }
332 let mut repr = ptr::null_mut::<c_void>();
333 unsafe { __unique_ptr_null(&mut repr) }
334 repr
335 }
336 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void {
337 extern "C" {
338 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800339 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$raw")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700340 fn __unique_ptr_raw(this: *mut *mut c_void, raw: *mut CxxVector<$ty>);
341 }
342 }
343 let mut repr = ptr::null_mut::<c_void>();
344 __unique_ptr_raw(&mut repr, raw);
345 repr
346 }
347 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self> {
348 extern "C" {
349 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800350 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$get")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700351 fn __unique_ptr_get(this: *const *mut c_void) -> *const CxxVector<$ty>;
352 }
353 }
354 __unique_ptr_get(&repr)
355 }
356 unsafe fn __unique_ptr_release(mut repr: *mut c_void) -> *mut CxxVector<Self> {
357 extern "C" {
358 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800359 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$release")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700360 fn __unique_ptr_release(this: *mut *mut c_void) -> *mut CxxVector<$ty>;
361 }
362 }
363 __unique_ptr_release(&mut repr)
364 }
365 unsafe fn __unique_ptr_drop(mut repr: *mut c_void) {
366 extern "C" {
367 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800368 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$drop")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700369 fn __unique_ptr_drop(this: *mut *mut c_void);
370 }
371 }
372 __unique_ptr_drop(&mut repr);
373 }
David Tolnaye4b6a622020-04-24 14:55:42 -0700374 }
375 };
376}
377
David Tolnay47e239d2020-08-28 00:32:04 -0700378macro_rules! impl_vector_element_for_primitive {
379 ($ty:ident) => {
380 impl_vector_element!(stringify!($ty), stringify!($ty), $ty);
381 };
382}
383
David Tolnay4b91eaa2020-04-24 14:19:22 -0700384impl_vector_element_for_primitive!(u8);
385impl_vector_element_for_primitive!(u16);
386impl_vector_element_for_primitive!(u32);
387impl_vector_element_for_primitive!(u64);
388impl_vector_element_for_primitive!(usize);
389impl_vector_element_for_primitive!(i8);
390impl_vector_element_for_primitive!(i16);
391impl_vector_element_for_primitive!(i32);
392impl_vector_element_for_primitive!(i64);
393impl_vector_element_for_primitive!(isize);
394impl_vector_element_for_primitive!(f32);
395impl_vector_element_for_primitive!(f64);
David Tolnay47e239d2020-08-28 00:32:04 -0700396
397impl_vector_element!("string", "CxxString", CxxString);