• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! Less used details of `CxxVector` are exposed in this module. `CxxVector`
2 //! itself is exposed at the crate root.
3 
4 use crate::extern_type::ExternType;
5 use crate::kind::Trivial;
6 use crate::string::CxxString;
7 use core::ffi::c_void;
8 use core::fmt::{self, Debug};
9 use core::iter::FusedIterator;
10 use core::marker::{PhantomData, PhantomPinned};
11 use core::mem::{self, ManuallyDrop, MaybeUninit};
12 use core::pin::Pin;
13 use core::slice;
14 
15 /// Binding to C++ `std::vector<T, std::allocator<T>>`.
16 ///
17 /// # Invariants
18 ///
19 /// As an invariant of this API and the static analysis of the cxx::bridge
20 /// macro, in Rust code we can never obtain a `CxxVector` by value. Instead in
21 /// Rust code we will only ever look at a vector behind a reference or smart
22 /// pointer, as in `&CxxVector<T>` or `UniquePtr<CxxVector<T>>`.
23 #[repr(C, packed)]
24 pub struct CxxVector<T> {
25     // A thing, because repr(C) structs are not allowed to consist exclusively
26     // of PhantomData fields.
27     _void: [c_void; 0],
28     // The conceptual vector elements to ensure that autotraits are propagated
29     // correctly, e.g. CxxVector is UnwindSafe iff T is.
30     _elements: PhantomData<[T]>,
31     // Prevent unpin operation from Pin<&mut CxxVector<T>> to &mut CxxVector<T>.
32     _pinned: PhantomData<PhantomPinned>,
33 }
34 
35 impl<T> CxxVector<T>
36 where
37     T: VectorElement,
38 {
39     /// Returns the number of elements in the vector.
40     ///
41     /// Matches the behavior of C++ [std::vector\<T\>::size][size].
42     ///
43     /// [size]: https://en.cppreference.com/w/cpp/container/vector/size
len(&self) -> usize44     pub fn len(&self) -> usize {
45         T::__vector_size(self)
46     }
47 
48     /// Returns true if the vector contains no elements.
49     ///
50     /// Matches the behavior of C++ [std::vector\<T\>::empty][empty].
51     ///
52     /// [empty]: https://en.cppreference.com/w/cpp/container/vector/empty
is_empty(&self) -> bool53     pub fn is_empty(&self) -> bool {
54         self.len() == 0
55     }
56 
57     /// Returns a reference to an element at the given position, or `None` if
58     /// out of bounds.
get(&self, pos: usize) -> Option<&T>59     pub fn get(&self, pos: usize) -> Option<&T> {
60         if pos < self.len() {
61             Some(unsafe { self.get_unchecked(pos) })
62         } else {
63             None
64         }
65     }
66 
67     /// Returns a pinned mutable reference to an element at the given position,
68     /// or `None` if out of bounds.
index_mut(self: Pin<&mut Self>, pos: usize) -> Option<Pin<&mut T>>69     pub fn index_mut(self: Pin<&mut Self>, pos: usize) -> Option<Pin<&mut T>> {
70         if pos < self.len() {
71             Some(unsafe { self.index_unchecked_mut(pos) })
72         } else {
73             None
74         }
75     }
76 
77     /// Returns a reference to an element without doing bounds checking.
78     ///
79     /// This is generally not recommended, use with caution! Calling this method
80     /// with an out-of-bounds index is undefined behavior even if the resulting
81     /// reference is not used.
82     ///
83     /// Matches the behavior of C++
84     /// [std::vector\<T\>::operator\[\] const][operator_at].
85     ///
86     /// [operator_at]: https://en.cppreference.com/w/cpp/container/vector/operator_at
get_unchecked(&self, pos: usize) -> &T87     pub unsafe fn get_unchecked(&self, pos: usize) -> &T {
88         let this = self as *const CxxVector<T> as *mut CxxVector<T>;
89         unsafe {
90             let ptr = T::__get_unchecked(this, pos) as *const T;
91             &*ptr
92         }
93     }
94 
95     /// Returns a pinned mutable reference to an element without doing bounds
96     /// checking.
97     ///
98     /// This is generally not recommended, use with caution! Calling this method
99     /// with an out-of-bounds index is undefined behavior even if the resulting
100     /// reference is not used.
101     ///
102     /// Matches the behavior of C++
103     /// [std::vector\<T\>::operator\[\]][operator_at].
104     ///
105     /// [operator_at]: https://en.cppreference.com/w/cpp/container/vector/operator_at
index_unchecked_mut(self: Pin<&mut Self>, pos: usize) -> Pin<&mut T>106     pub unsafe fn index_unchecked_mut(self: Pin<&mut Self>, pos: usize) -> Pin<&mut T> {
107         unsafe {
108             let ptr = T::__get_unchecked(self.get_unchecked_mut(), pos);
109             Pin::new_unchecked(&mut *ptr)
110         }
111     }
112 
113     /// Returns a slice to the underlying contiguous array of elements.
as_slice(&self) -> &[T] where T: ExternType<Kind = Trivial>,114     pub fn as_slice(&self) -> &[T]
115     where
116         T: ExternType<Kind = Trivial>,
117     {
118         let len = self.len();
119         if len == 0 {
120             // The slice::from_raw_parts in the other branch requires a nonnull
121             // and properly aligned data ptr. C++ standard does not guarantee
122             // that data() on a vector with size 0 would return a nonnull
123             // pointer or sufficiently aligned pointer, so using it would be
124             // undefined behavior. Create our own empty slice in Rust instead
125             // which upholds the invariants.
126             &[]
127         } else {
128             let this = self as *const CxxVector<T> as *mut CxxVector<T>;
129             let ptr = unsafe { T::__get_unchecked(this, 0) };
130             unsafe { slice::from_raw_parts(ptr, len) }
131         }
132     }
133 
134     /// Returns a slice to the underlying contiguous array of elements by
135     /// mutable reference.
as_mut_slice(self: Pin<&mut Self>) -> &mut [T] where T: ExternType<Kind = Trivial>,136     pub fn as_mut_slice(self: Pin<&mut Self>) -> &mut [T]
137     where
138         T: ExternType<Kind = Trivial>,
139     {
140         let len = self.len();
141         if len == 0 {
142             &mut []
143         } else {
144             let ptr = unsafe { T::__get_unchecked(self.get_unchecked_mut(), 0) };
145             unsafe { slice::from_raw_parts_mut(ptr, len) }
146         }
147     }
148 
149     /// Returns an iterator over elements of type `&T`.
iter(&self) -> Iter<T>150     pub fn iter(&self) -> Iter<T> {
151         Iter { v: self, index: 0 }
152     }
153 
154     /// Returns an iterator over elements of type `Pin<&mut T>`.
iter_mut(self: Pin<&mut Self>) -> IterMut<T>155     pub fn iter_mut(self: Pin<&mut Self>) -> IterMut<T> {
156         IterMut { v: self, index: 0 }
157     }
158 
159     /// Appends an element to the back of the vector.
160     ///
161     /// Matches the behavior of C++ [std::vector\<T\>::push_back][push_back].
162     ///
163     /// [push_back]: https://en.cppreference.com/w/cpp/container/vector/push_back
push(self: Pin<&mut Self>, value: T) where T: ExternType<Kind = Trivial>,164     pub fn push(self: Pin<&mut Self>, value: T)
165     where
166         T: ExternType<Kind = Trivial>,
167     {
168         let mut value = ManuallyDrop::new(value);
169         unsafe {
170             // C++ calls move constructor followed by destructor on `value`.
171             T::__push_back(self, &mut value);
172         }
173     }
174 
175     /// Removes the last element from a vector and returns it, or `None` if the
176     /// vector is empty.
pop(self: Pin<&mut Self>) -> Option<T> where T: ExternType<Kind = Trivial>,177     pub fn pop(self: Pin<&mut Self>) -> Option<T>
178     where
179         T: ExternType<Kind = Trivial>,
180     {
181         if self.is_empty() {
182             None
183         } else {
184             let mut value = MaybeUninit::uninit();
185             Some(unsafe {
186                 T::__pop_back(self, &mut value);
187                 value.assume_init()
188             })
189         }
190     }
191 }
192 
193 /// Iterator over elements of a `CxxVector` by shared reference.
194 ///
195 /// The iterator element type is `&'a T`.
196 pub struct Iter<'a, T> {
197     v: &'a CxxVector<T>,
198     index: usize,
199 }
200 
201 impl<'a, T> IntoIterator for &'a CxxVector<T>
202 where
203     T: VectorElement,
204 {
205     type Item = &'a T;
206     type IntoIter = Iter<'a, T>;
207 
into_iter(self) -> Self::IntoIter208     fn into_iter(self) -> Self::IntoIter {
209         self.iter()
210     }
211 }
212 
213 impl<'a, T> Iterator for Iter<'a, T>
214 where
215     T: VectorElement,
216 {
217     type Item = &'a T;
218 
next(&mut self) -> Option<Self::Item>219     fn next(&mut self) -> Option<Self::Item> {
220         let next = self.v.get(self.index)?;
221         self.index += 1;
222         Some(next)
223     }
224 
size_hint(&self) -> (usize, Option<usize>)225     fn size_hint(&self) -> (usize, Option<usize>) {
226         let len = self.len();
227         (len, Some(len))
228     }
229 }
230 
231 impl<'a, T> ExactSizeIterator for Iter<'a, T>
232 where
233     T: VectorElement,
234 {
len(&self) -> usize235     fn len(&self) -> usize {
236         self.v.len() - self.index
237     }
238 }
239 
240 impl<'a, T> FusedIterator for Iter<'a, T> where T: VectorElement {}
241 
242 /// Iterator over elements of a `CxxVector` by pinned mutable reference.
243 ///
244 /// The iterator element type is `Pin<&'a mut T>`.
245 pub struct IterMut<'a, T> {
246     v: Pin<&'a mut CxxVector<T>>,
247     index: usize,
248 }
249 
250 impl<'a, T> IntoIterator for Pin<&'a mut CxxVector<T>>
251 where
252     T: VectorElement,
253 {
254     type Item = Pin<&'a mut T>;
255     type IntoIter = IterMut<'a, T>;
256 
into_iter(self) -> Self::IntoIter257     fn into_iter(self) -> Self::IntoIter {
258         self.iter_mut()
259     }
260 }
261 
262 impl<'a, T> Iterator for IterMut<'a, T>
263 where
264     T: VectorElement,
265 {
266     type Item = Pin<&'a mut T>;
267 
next(&mut self) -> Option<Self::Item>268     fn next(&mut self) -> Option<Self::Item> {
269         let next = self.v.as_mut().index_mut(self.index)?;
270         self.index += 1;
271         // Extend lifetime to allow simultaneous holding of nonoverlapping
272         // elements, analogous to slice::split_first_mut.
273         unsafe {
274             let ptr = Pin::into_inner_unchecked(next) as *mut T;
275             Some(Pin::new_unchecked(&mut *ptr))
276         }
277     }
278 
size_hint(&self) -> (usize, Option<usize>)279     fn size_hint(&self) -> (usize, Option<usize>) {
280         let len = self.len();
281         (len, Some(len))
282     }
283 }
284 
285 impl<'a, T> ExactSizeIterator for IterMut<'a, T>
286 where
287     T: VectorElement,
288 {
len(&self) -> usize289     fn len(&self) -> usize {
290         self.v.len() - self.index
291     }
292 }
293 
294 impl<'a, T> FusedIterator for IterMut<'a, T> where T: VectorElement {}
295 
296 impl<T> Debug for CxxVector<T>
297 where
298     T: VectorElement + Debug,
299 {
fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result300     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
301         formatter.debug_list().entries(self).finish()
302     }
303 }
304 
305 /// Trait bound for types which may be used as the `T` inside of a
306 /// `CxxVector<T>` in generic code.
307 ///
308 /// This trait has no publicly callable or implementable methods. Implementing
309 /// it outside of the CXX codebase is not supported.
310 ///
311 /// # Example
312 ///
313 /// A bound `T: VectorElement` may be necessary when manipulating [`CxxVector`]
314 /// in generic code.
315 ///
316 /// ```
317 /// use cxx::vector::{CxxVector, VectorElement};
318 /// use std::fmt::Display;
319 ///
320 /// pub fn take_generic_vector<T>(vector: &CxxVector<T>)
321 /// where
322 ///     T: VectorElement + Display,
323 /// {
324 ///     println!("the vector elements are:");
325 ///     for element in vector {
326 ///         println!("  • {}", element);
327 ///     }
328 /// }
329 /// ```
330 ///
331 /// Writing the same generic function without a `VectorElement` trait bound
332 /// would not compile.
333 pub unsafe trait VectorElement: Sized {
334     #[doc(hidden)]
__typename(f: &mut fmt::Formatter) -> fmt::Result335     fn __typename(f: &mut fmt::Formatter) -> fmt::Result;
336     #[doc(hidden)]
__vector_size(v: &CxxVector<Self>) -> usize337     fn __vector_size(v: &CxxVector<Self>) -> usize;
338     #[doc(hidden)]
__get_unchecked(v: *mut CxxVector<Self>, pos: usize) -> *mut Self339     unsafe fn __get_unchecked(v: *mut CxxVector<Self>, pos: usize) -> *mut Self;
340     #[doc(hidden)]
__push_back(v: Pin<&mut CxxVector<Self>>, value: &mut ManuallyDrop<Self>)341     unsafe fn __push_back(v: Pin<&mut CxxVector<Self>>, value: &mut ManuallyDrop<Self>) {
342         // Opaque C type vector elements do not get this method because they can
343         // never exist by value on the Rust side of the bridge.
344         let _ = v;
345         let _ = value;
346         unreachable!()
347     }
348     #[doc(hidden)]
__pop_back(v: Pin<&mut CxxVector<Self>>, out: &mut MaybeUninit<Self>)349     unsafe fn __pop_back(v: Pin<&mut CxxVector<Self>>, out: &mut MaybeUninit<Self>) {
350         // Opaque C type vector elements do not get this method because they can
351         // never exist by value on the Rust side of the bridge.
352         let _ = v;
353         let _ = out;
354         unreachable!()
355     }
356     #[doc(hidden)]
__unique_ptr_null() -> MaybeUninit<*mut c_void>357     fn __unique_ptr_null() -> MaybeUninit<*mut c_void>;
358     #[doc(hidden)]
__unique_ptr_raw(raw: *mut CxxVector<Self>) -> MaybeUninit<*mut c_void>359     unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> MaybeUninit<*mut c_void>;
360     #[doc(hidden)]
__unique_ptr_get(repr: MaybeUninit<*mut c_void>) -> *const CxxVector<Self>361     unsafe fn __unique_ptr_get(repr: MaybeUninit<*mut c_void>) -> *const CxxVector<Self>;
362     #[doc(hidden)]
__unique_ptr_release(repr: MaybeUninit<*mut c_void>) -> *mut CxxVector<Self>363     unsafe fn __unique_ptr_release(repr: MaybeUninit<*mut c_void>) -> *mut CxxVector<Self>;
364     #[doc(hidden)]
__unique_ptr_drop(repr: MaybeUninit<*mut c_void>)365     unsafe fn __unique_ptr_drop(repr: MaybeUninit<*mut c_void>);
366 }
367 
368 macro_rules! vector_element_by_value_methods {
369     (opaque, $segment:expr, $ty:ty) => {};
370     (trivial, $segment:expr, $ty:ty) => {
371         unsafe fn __push_back(v: Pin<&mut CxxVector<$ty>>, value: &mut ManuallyDrop<$ty>) {
372             extern "C" {
373                 attr! {
374                     #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$push_back")]
375                     fn __push_back(_: Pin<&mut CxxVector<$ty>>, _: &mut ManuallyDrop<$ty>);
376                 }
377             }
378             unsafe { __push_back(v, value) }
379         }
380         unsafe fn __pop_back(v: Pin<&mut CxxVector<$ty>>, out: &mut MaybeUninit<$ty>) {
381             extern "C" {
382                 attr! {
383                     #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$pop_back")]
384                     fn __pop_back(_: Pin<&mut CxxVector<$ty>>, _: &mut MaybeUninit<$ty>);
385                 }
386             }
387             unsafe { __pop_back(v, out) }
388         }
389     };
390 }
391 
392 macro_rules! impl_vector_element {
393     ($kind:ident, $segment:expr, $name:expr, $ty:ty) => {
394         const_assert_eq!(0, mem::size_of::<CxxVector<$ty>>());
395         const_assert_eq!(1, mem::align_of::<CxxVector<$ty>>());
396 
397         unsafe impl VectorElement for $ty {
398             fn __typename(f: &mut fmt::Formatter) -> fmt::Result {
399                 f.write_str($name)
400             }
401             fn __vector_size(v: &CxxVector<$ty>) -> usize {
402                 extern "C" {
403                     attr! {
404                         #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$size")]
405                         fn __vector_size(_: &CxxVector<$ty>) -> usize;
406                     }
407                 }
408                 unsafe { __vector_size(v) }
409             }
410             unsafe fn __get_unchecked(v: *mut CxxVector<$ty>, pos: usize) -> *mut $ty {
411                 extern "C" {
412                     attr! {
413                         #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$get_unchecked")]
414                         fn __get_unchecked(_: *mut CxxVector<$ty>, _: usize) -> *mut $ty;
415                     }
416                 }
417                 unsafe { __get_unchecked(v, pos) }
418             }
419             vector_element_by_value_methods!($kind, $segment, $ty);
420             fn __unique_ptr_null() -> MaybeUninit<*mut c_void> {
421                 extern "C" {
422                     attr! {
423                         #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$null")]
424                         fn __unique_ptr_null(this: *mut MaybeUninit<*mut c_void>);
425                     }
426                 }
427                 let mut repr = MaybeUninit::uninit();
428                 unsafe { __unique_ptr_null(&mut repr) }
429                 repr
430             }
431             unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> MaybeUninit<*mut c_void> {
432                 extern "C" {
433                     attr! {
434                         #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$raw")]
435                         fn __unique_ptr_raw(this: *mut MaybeUninit<*mut c_void>, raw: *mut CxxVector<$ty>);
436                     }
437                 }
438                 let mut repr = MaybeUninit::uninit();
439                 unsafe { __unique_ptr_raw(&mut repr, raw) }
440                 repr
441             }
442             unsafe fn __unique_ptr_get(repr: MaybeUninit<*mut c_void>) -> *const CxxVector<Self> {
443                 extern "C" {
444                     attr! {
445                         #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$get")]
446                         fn __unique_ptr_get(this: *const MaybeUninit<*mut c_void>) -> *const CxxVector<$ty>;
447                     }
448                 }
449                 unsafe { __unique_ptr_get(&repr) }
450             }
451             unsafe fn __unique_ptr_release(mut repr: MaybeUninit<*mut c_void>) -> *mut CxxVector<Self> {
452                 extern "C" {
453                     attr! {
454                         #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$release")]
455                         fn __unique_ptr_release(this: *mut MaybeUninit<*mut c_void>) -> *mut CxxVector<$ty>;
456                     }
457                 }
458                 unsafe { __unique_ptr_release(&mut repr) }
459             }
460             unsafe fn __unique_ptr_drop(mut repr: MaybeUninit<*mut c_void>) {
461                 extern "C" {
462                     attr! {
463                         #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$drop")]
464                         fn __unique_ptr_drop(this: *mut MaybeUninit<*mut c_void>);
465                     }
466                 }
467                 unsafe { __unique_ptr_drop(&mut repr) }
468             }
469         }
470     };
471 }
472 
473 macro_rules! impl_vector_element_for_primitive {
474     ($ty:ident) => {
475         impl_vector_element!(trivial, stringify!($ty), stringify!($ty), $ty);
476     };
477 }
478 
479 impl_vector_element_for_primitive!(u8);
480 impl_vector_element_for_primitive!(u16);
481 impl_vector_element_for_primitive!(u32);
482 impl_vector_element_for_primitive!(u64);
483 impl_vector_element_for_primitive!(usize);
484 impl_vector_element_for_primitive!(i8);
485 impl_vector_element_for_primitive!(i16);
486 impl_vector_element_for_primitive!(i32);
487 impl_vector_element_for_primitive!(i64);
488 impl_vector_element_for_primitive!(isize);
489 impl_vector_element_for_primitive!(f32);
490 impl_vector_element_for_primitive!(f64);
491 
492 impl_vector_element!(opaque, "string", "CxxString", CxxString);
493