blob: 191b643d2183a58959d6345fbae6a55f5a55d0dc [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.
67 pub fn get_mut(&mut self, pos: usize) -> Option<Pin<&mut T>> {
68 if pos < self.len() {
69 Some(unsafe { self.get_unchecked_mut(pos) })
70 } 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 Tolnay767e00d2020-12-21 17:12:27 -0800102 pub unsafe fn get_unchecked_mut(&mut self, pos: usize) -> Pin<&mut T> {
103 let ptr = T::__get_unchecked(self, pos);
104 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
128 /// Returns an iterator over elements of type `&T`.
129 pub fn iter(&self) -> Iter<T> {
130 Iter { v: self, index: 0 }
131 }
Myron Ahneba35cf2020-02-05 19:41:51 +0700132}
133
David Tolnayb5d039c2020-12-12 23:21:17 -0800134/// Iterator over elements of a `CxxVector` by shared reference.
135///
136/// The iterator element type is `&'a T`.
David Tolnay3d88bdc2020-04-24 13:48:18 -0700137pub struct Iter<'a, T> {
David Tolnaye90be1d2020-04-24 11:45:57 -0700138 v: &'a CxxVector<T>,
Myron Ahneba35cf2020-02-05 19:41:51 +0700139 index: usize,
140}
141
David Tolnay4074ad22020-04-24 18:20:11 -0700142impl<'a, T> IntoIterator for &'a CxxVector<T>
143where
144 T: VectorElement,
145{
Myron Ahneba35cf2020-02-05 19:41:51 +0700146 type Item = &'a T;
David Tolnay3d88bdc2020-04-24 13:48:18 -0700147 type IntoIter = Iter<'a, T>;
Myron Ahneba35cf2020-02-05 19:41:51 +0700148
149 fn into_iter(self) -> Self::IntoIter {
David Tolnay4f71cc52020-11-15 23:55:27 -0800150 self.iter()
Myron Ahneba35cf2020-02-05 19:41:51 +0700151 }
152}
153
David Tolnay4074ad22020-04-24 18:20:11 -0700154impl<'a, T> Iterator for Iter<'a, T>
155where
156 T: VectorElement,
157{
Myron Ahneba35cf2020-02-05 19:41:51 +0700158 type Item = &'a T;
David Tolnay85db5a02020-04-25 13:17:27 -0700159
Myron Ahneba35cf2020-02-05 19:41:51 +0700160 fn next(&mut self) -> Option<Self::Item> {
David Tolnay0d527172020-12-21 17:35:24 -0800161 let next = self.v.get(self.index)?;
162 self.index += 1;
163 Some(next)
Myron Ahneba35cf2020-02-05 19:41:51 +0700164 }
David Tolnay724ac752020-12-13 16:00:48 -0800165
166 fn size_hint(&self) -> (usize, Option<usize>) {
167 let len = self.len();
168 (len, Some(len))
169 }
170}
171
172impl<'a, T> ExactSizeIterator for Iter<'a, T>
173where
174 T: VectorElement,
175{
176 fn len(&self) -> usize {
177 self.v.len() - self.index
178 }
Myron Ahneba35cf2020-02-05 19:41:51 +0700179}
180
David Tolnay526faa22020-12-13 16:10:47 -0800181impl<'a, T> FusedIterator for Iter<'a, T> where T: VectorElement {}
182
David Tolnaya8100ed2020-12-04 12:41:24 -0800183impl<T> Debug for CxxVector<T>
184where
185 T: VectorElement + Debug,
186{
187 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
188 formatter.debug_list().entries(self).finish()
189 }
190}
191
David Tolnayb5d039c2020-12-12 23:21:17 -0800192pub(crate) struct TypeName<T> {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700193 element: PhantomData<T>,
194}
195
196impl<T> TypeName<T> {
197 pub const fn new() -> Self {
198 TypeName {
199 element: PhantomData,
200 }
201 }
202}
203
204impl<T> Display for TypeName<T>
205where
206 T: VectorElement,
207{
208 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
209 write!(formatter, "CxxVector<{}>", T::__NAME)
210 }
211}
212
David Tolnay5104c862020-04-24 13:26:01 -0700213// Methods are private; not intended to be implemented outside of cxxbridge
214// codebase.
David Tolnay1b341192020-04-24 13:04:04 -0700215#[doc(hidden)]
David Tolnayc3ed3a62020-04-24 13:34:50 -0700216pub unsafe trait VectorElement: Sized {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700217 const __NAME: &'static dyn Display;
David Tolnay0e084662020-04-24 14:02:51 -0700218 fn __vector_size(v: &CxxVector<Self>) -> usize;
David Tolnay767e00d2020-12-21 17:12:27 -0800219 unsafe fn __get_unchecked(v: *mut CxxVector<Self>, pos: usize) -> *mut Self;
David Tolnay3b40b6f2020-04-24 17:58:24 -0700220 fn __unique_ptr_null() -> *mut c_void;
221 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void;
222 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self>;
223 unsafe fn __unique_ptr_release(repr: *mut c_void) -> *mut CxxVector<Self>;
224 unsafe fn __unique_ptr_drop(repr: *mut c_void);
David Tolnay1b341192020-04-24 13:04:04 -0700225}
226
David Tolnay47e239d2020-08-28 00:32:04 -0700227macro_rules! impl_vector_element {
228 ($segment:expr, $name:expr, $ty:ty) => {
David Tolnayf0446632020-04-25 11:29:26 -0700229 const_assert_eq!(1, mem::align_of::<CxxVector<$ty>>());
230
David Tolnaye4b6a622020-04-24 14:55:42 -0700231 unsafe impl VectorElement for $ty {
David Tolnay47e239d2020-08-28 00:32:04 -0700232 const __NAME: &'static dyn Display = &$name;
David Tolnaye4b6a622020-04-24 14:55:42 -0700233 fn __vector_size(v: &CxxVector<$ty>) -> usize {
234 extern "C" {
235 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800236 #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$size")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700237 fn __vector_size(_: &CxxVector<$ty>) -> usize;
238 }
239 }
240 unsafe { __vector_size(v) }
241 }
David Tolnay767e00d2020-12-21 17:12:27 -0800242 unsafe fn __get_unchecked(v: *mut CxxVector<$ty>, pos: usize) -> *mut $ty {
David Tolnaye4b6a622020-04-24 14:55:42 -0700243 extern "C" {
244 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800245 #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$get_unchecked")]
David Tolnay767e00d2020-12-21 17:12:27 -0800246 fn __get_unchecked(_: *mut CxxVector<$ty>, _: usize) -> *mut $ty;
David Tolnaye4b6a622020-04-24 14:55:42 -0700247 }
248 }
David Tolnay93637ca2020-09-24 15:58:20 -0400249 __get_unchecked(v, pos)
David Tolnaye4b6a622020-04-24 14:55:42 -0700250 }
David Tolnay3b40b6f2020-04-24 17:58:24 -0700251 fn __unique_ptr_null() -> *mut c_void {
252 extern "C" {
253 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800254 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$null")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700255 fn __unique_ptr_null(this: *mut *mut c_void);
256 }
257 }
258 let mut repr = ptr::null_mut::<c_void>();
259 unsafe { __unique_ptr_null(&mut repr) }
260 repr
261 }
262 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void {
263 extern "C" {
264 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800265 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$raw")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700266 fn __unique_ptr_raw(this: *mut *mut c_void, raw: *mut CxxVector<$ty>);
267 }
268 }
269 let mut repr = ptr::null_mut::<c_void>();
270 __unique_ptr_raw(&mut repr, raw);
271 repr
272 }
273 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self> {
274 extern "C" {
275 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800276 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$get")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700277 fn __unique_ptr_get(this: *const *mut c_void) -> *const CxxVector<$ty>;
278 }
279 }
280 __unique_ptr_get(&repr)
281 }
282 unsafe fn __unique_ptr_release(mut repr: *mut c_void) -> *mut CxxVector<Self> {
283 extern "C" {
284 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800285 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$release")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700286 fn __unique_ptr_release(this: *mut *mut c_void) -> *mut CxxVector<$ty>;
287 }
288 }
289 __unique_ptr_release(&mut repr)
290 }
291 unsafe fn __unique_ptr_drop(mut repr: *mut c_void) {
292 extern "C" {
293 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800294 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$drop")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700295 fn __unique_ptr_drop(this: *mut *mut c_void);
296 }
297 }
298 __unique_ptr_drop(&mut repr);
299 }
David Tolnaye4b6a622020-04-24 14:55:42 -0700300 }
301 };
302}
303
David Tolnay47e239d2020-08-28 00:32:04 -0700304macro_rules! impl_vector_element_for_primitive {
305 ($ty:ident) => {
306 impl_vector_element!(stringify!($ty), stringify!($ty), $ty);
307 };
308}
309
David Tolnay4b91eaa2020-04-24 14:19:22 -0700310impl_vector_element_for_primitive!(u8);
311impl_vector_element_for_primitive!(u16);
312impl_vector_element_for_primitive!(u32);
313impl_vector_element_for_primitive!(u64);
314impl_vector_element_for_primitive!(usize);
315impl_vector_element_for_primitive!(i8);
316impl_vector_element_for_primitive!(i16);
317impl_vector_element_for_primitive!(i32);
318impl_vector_element_for_primitive!(i64);
319impl_vector_element_for_primitive!(isize);
320impl_vector_element_for_primitive!(f32);
321impl_vector_element_for_primitive!(f64);
David Tolnay47e239d2020-08-28 00:32:04 -0700322
323impl_vector_element!("string", "CxxString", CxxString);