blob: 31dc11c8e57ae45fc099df5a801e05b66ffadbd9 [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 Tolnay95dab1d2020-11-15 14:32:37 -08009use core::marker::{PhantomData, PhantomPinned};
David Tolnay3384c142020-09-14 00:26:47 -040010use core::mem;
11use core::ptr;
David Tolnay93637ca2020-09-24 15:58:20 -040012use core::slice;
David Tolnay4f7e6fa2020-04-24 11:52:44 -070013
David Tolnayb5d039c2020-12-12 23:21:17 -080014#[doc(inline)]
15pub use crate::Vector;
16
David Tolnay61a9fdf2020-04-24 16:19:42 -070017/// Binding to C++ `std::vector<T, std::allocator<T>>`.
Myron Ahneba35cf2020-02-05 19:41:51 +070018///
19/// # Invariants
20///
21/// As an invariant of this API and the static analysis of the cxx::bridge
David Tolnay5fe93632020-04-24 12:31:00 -070022/// macro, in Rust code we can never obtain a `CxxVector` by value. Instead in
23/// Rust code we will only ever look at a vector behind a reference or smart
24/// pointer, as in `&CxxVector<T>` or `UniquePtr<CxxVector<T>>`.
David Tolnay4f7e6fa2020-04-24 11:52:44 -070025#[repr(C, packed)]
David Tolnaye90be1d2020-04-24 11:45:57 -070026pub struct CxxVector<T> {
Myron Ahneba35cf2020-02-05 19:41:51 +070027 _private: [T; 0],
David Tolnay95dab1d2020-11-15 14:32:37 -080028 _pinned: PhantomData<PhantomPinned>,
Myron Ahneba35cf2020-02-05 19:41:51 +070029}
30
David Tolnay4074ad22020-04-24 18:20:11 -070031impl<T> CxxVector<T>
32where
33 T: VectorElement,
34{
David Tolnaycdc87962020-04-24 13:45:59 -070035 /// Returns the number of elements in the vector.
David Tolnaydd839192020-04-24 16:41:29 -070036 ///
37 /// Matches the behavior of C++ [std::vector\<T\>::size][size].
38 ///
39 /// [size]: https://en.cppreference.com/w/cpp/container/vector/size
David Tolnayc01d0a02020-04-24 13:30:44 -070040 pub fn len(&self) -> usize {
David Tolnay0e084662020-04-24 14:02:51 -070041 T::__vector_size(self)
Myron Ahneba35cf2020-02-05 19:41:51 +070042 }
43
David Tolnaycdc87962020-04-24 13:45:59 -070044 /// Returns true if the vector contains no elements.
David Tolnaydd839192020-04-24 16:41:29 -070045 ///
46 /// Matches the behavior of C++ [std::vector\<T\>::empty][empty].
47 ///
48 /// [empty]: https://en.cppreference.com/w/cpp/container/vector/empty
Myron Ahneba35cf2020-02-05 19:41:51 +070049 pub fn is_empty(&self) -> bool {
David Tolnayc01d0a02020-04-24 13:30:44 -070050 self.len() == 0
Myron Ahneba35cf2020-02-05 19:41:51 +070051 }
52
David Tolnaycdc87962020-04-24 13:45:59 -070053 /// Returns a reference to an element at the given position, or `None` if
54 /// out of bounds.
Myron Ahneba35cf2020-02-05 19:41:51 +070055 pub fn get(&self, pos: usize) -> Option<&T> {
David Tolnayc01d0a02020-04-24 13:30:44 -070056 if pos < self.len() {
David Tolnay93637ca2020-09-24 15:58:20 -040057 Some(unsafe { self.get_unchecked(pos) })
Myron Ahneba35cf2020-02-05 19:41:51 +070058 } else {
59 None
60 }
61 }
62
David Tolnay4944f2f2020-04-24 13:46:12 -070063 /// Returns a reference to an element without doing bounds checking.
64 ///
65 /// This is generally not recommended, use with caution! Calling this method
66 /// with an out-of-bounds index is undefined behavior even if the resulting
67 /// reference is not used.
David Tolnaydd839192020-04-24 16:41:29 -070068 ///
69 /// Matches the behavior of C++
70 /// [std::vector\<T\>::operator\[\]][operator_at].
71 ///
72 /// [operator_at]: https://en.cppreference.com/w/cpp/container/vector/operator_at
David Tolnay4944f2f2020-04-24 13:46:12 -070073 pub unsafe fn get_unchecked(&self, pos: usize) -> &T {
David Tolnay93637ca2020-09-24 15:58:20 -040074 &*T::__get_unchecked(self, pos)
75 }
76
77 /// Returns a slice to the underlying contiguous array of elements.
David Tolnay181ee912020-12-04 12:15:10 -080078 pub fn as_slice(&self) -> &[T]
79 where
80 T: ExternType<Kind = Trivial>,
81 {
David Tolnay93637ca2020-09-24 15:58:20 -040082 let len = self.len();
83 if len == 0 {
David Tolnaya5a14ce2020-09-24 16:02:40 -040084 // The slice::from_raw_parts in the other branch requires a nonnull
85 // and properly aligned data ptr. C++ standard does not guarantee
86 // that data() on a vector with size 0 would return a nonnull
87 // pointer or sufficiently aligned pointer, so using it would be
88 // undefined behavior. Create our own empty slice in Rust instead
89 // which upholds the invariants.
David Tolnayacc7fb02020-09-24 18:10:09 -040090 &[]
David Tolnay93637ca2020-09-24 15:58:20 -040091 } else {
92 let ptr = unsafe { T::__get_unchecked(self, 0) };
93 unsafe { slice::from_raw_parts(ptr, len) }
94 }
David Tolnay4944f2f2020-04-24 13:46:12 -070095 }
David Tolnay4f71cc52020-11-15 23:55:27 -080096
97 /// Returns an iterator over elements of type `&T`.
98 pub fn iter(&self) -> Iter<T> {
99 Iter { v: self, index: 0 }
100 }
Myron Ahneba35cf2020-02-05 19:41:51 +0700101}
102
David Tolnayb5d039c2020-12-12 23:21:17 -0800103/// Iterator over elements of a `CxxVector` by shared reference.
104///
105/// The iterator element type is `&'a T`.
David Tolnay3d88bdc2020-04-24 13:48:18 -0700106pub struct Iter<'a, T> {
David Tolnaye90be1d2020-04-24 11:45:57 -0700107 v: &'a CxxVector<T>,
Myron Ahneba35cf2020-02-05 19:41:51 +0700108 index: usize,
109}
110
David Tolnay4074ad22020-04-24 18:20:11 -0700111impl<'a, T> IntoIterator for &'a CxxVector<T>
112where
113 T: VectorElement,
114{
Myron Ahneba35cf2020-02-05 19:41:51 +0700115 type Item = &'a T;
David Tolnay3d88bdc2020-04-24 13:48:18 -0700116 type IntoIter = Iter<'a, T>;
Myron Ahneba35cf2020-02-05 19:41:51 +0700117
118 fn into_iter(self) -> Self::IntoIter {
David Tolnay4f71cc52020-11-15 23:55:27 -0800119 self.iter()
Myron Ahneba35cf2020-02-05 19:41:51 +0700120 }
121}
122
David Tolnay4074ad22020-04-24 18:20:11 -0700123impl<'a, T> Iterator for Iter<'a, T>
124where
125 T: VectorElement,
126{
Myron Ahneba35cf2020-02-05 19:41:51 +0700127 type Item = &'a T;
David Tolnay85db5a02020-04-25 13:17:27 -0700128
Myron Ahneba35cf2020-02-05 19:41:51 +0700129 fn next(&mut self) -> Option<Self::Item> {
David Tolnay39ee0ed2020-05-05 10:12:29 -0700130 let next = self.v.get(self.index);
David Tolnay724ac752020-12-13 16:00:48 -0800131 self.index += next.is_some() as usize;
David Tolnay39ee0ed2020-05-05 10:12:29 -0700132 next
Myron Ahneba35cf2020-02-05 19:41:51 +0700133 }
David Tolnay724ac752020-12-13 16:00:48 -0800134
135 fn size_hint(&self) -> (usize, Option<usize>) {
136 let len = self.len();
137 (len, Some(len))
138 }
139}
140
141impl<'a, T> ExactSizeIterator for Iter<'a, T>
142where
143 T: VectorElement,
144{
145 fn len(&self) -> usize {
146 self.v.len() - self.index
147 }
Myron Ahneba35cf2020-02-05 19:41:51 +0700148}
149
David Tolnaya8100ed2020-12-04 12:41:24 -0800150impl<T> Debug for CxxVector<T>
151where
152 T: VectorElement + Debug,
153{
154 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
155 formatter.debug_list().entries(self).finish()
156 }
157}
158
David Tolnayb5d039c2020-12-12 23:21:17 -0800159pub(crate) struct TypeName<T> {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700160 element: PhantomData<T>,
161}
162
163impl<T> TypeName<T> {
164 pub const fn new() -> Self {
165 TypeName {
166 element: PhantomData,
167 }
168 }
169}
170
171impl<T> Display for TypeName<T>
172where
173 T: VectorElement,
174{
175 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
176 write!(formatter, "CxxVector<{}>", T::__NAME)
177 }
178}
179
David Tolnay5104c862020-04-24 13:26:01 -0700180// Methods are private; not intended to be implemented outside of cxxbridge
181// codebase.
David Tolnay1b341192020-04-24 13:04:04 -0700182#[doc(hidden)]
David Tolnayc3ed3a62020-04-24 13:34:50 -0700183pub unsafe trait VectorElement: Sized {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700184 const __NAME: &'static dyn Display;
David Tolnay0e084662020-04-24 14:02:51 -0700185 fn __vector_size(v: &CxxVector<Self>) -> usize;
David Tolnay93637ca2020-09-24 15:58:20 -0400186 unsafe fn __get_unchecked(v: &CxxVector<Self>, pos: usize) -> *const Self;
David Tolnay3b40b6f2020-04-24 17:58:24 -0700187 fn __unique_ptr_null() -> *mut c_void;
188 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void;
189 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self>;
190 unsafe fn __unique_ptr_release(repr: *mut c_void) -> *mut CxxVector<Self>;
191 unsafe fn __unique_ptr_drop(repr: *mut c_void);
David Tolnay1b341192020-04-24 13:04:04 -0700192}
193
David Tolnay47e239d2020-08-28 00:32:04 -0700194macro_rules! impl_vector_element {
195 ($segment:expr, $name:expr, $ty:ty) => {
David Tolnayf0446632020-04-25 11:29:26 -0700196 const_assert_eq!(1, mem::align_of::<CxxVector<$ty>>());
197
David Tolnaye4b6a622020-04-24 14:55:42 -0700198 unsafe impl VectorElement for $ty {
David Tolnay47e239d2020-08-28 00:32:04 -0700199 const __NAME: &'static dyn Display = &$name;
David Tolnaye4b6a622020-04-24 14:55:42 -0700200 fn __vector_size(v: &CxxVector<$ty>) -> usize {
201 extern "C" {
202 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800203 #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$size")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700204 fn __vector_size(_: &CxxVector<$ty>) -> usize;
205 }
206 }
207 unsafe { __vector_size(v) }
208 }
David Tolnay93637ca2020-09-24 15:58:20 -0400209 unsafe fn __get_unchecked(v: &CxxVector<$ty>, pos: usize) -> *const $ty {
David Tolnaye4b6a622020-04-24 14:55:42 -0700210 extern "C" {
211 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800212 #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$get_unchecked")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700213 fn __get_unchecked(_: &CxxVector<$ty>, _: usize) -> *const $ty;
214 }
215 }
David Tolnay93637ca2020-09-24 15:58:20 -0400216 __get_unchecked(v, pos)
David Tolnaye4b6a622020-04-24 14:55:42 -0700217 }
David Tolnay3b40b6f2020-04-24 17:58:24 -0700218 fn __unique_ptr_null() -> *mut c_void {
219 extern "C" {
220 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800221 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$null")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700222 fn __unique_ptr_null(this: *mut *mut c_void);
223 }
224 }
225 let mut repr = ptr::null_mut::<c_void>();
226 unsafe { __unique_ptr_null(&mut repr) }
227 repr
228 }
229 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void {
230 extern "C" {
231 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800232 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$raw")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700233 fn __unique_ptr_raw(this: *mut *mut c_void, raw: *mut CxxVector<$ty>);
234 }
235 }
236 let mut repr = ptr::null_mut::<c_void>();
237 __unique_ptr_raw(&mut repr, raw);
238 repr
239 }
240 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self> {
241 extern "C" {
242 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800243 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$get")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700244 fn __unique_ptr_get(this: *const *mut c_void) -> *const CxxVector<$ty>;
245 }
246 }
247 __unique_ptr_get(&repr)
248 }
249 unsafe fn __unique_ptr_release(mut repr: *mut c_void) -> *mut CxxVector<Self> {
250 extern "C" {
251 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800252 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$release")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700253 fn __unique_ptr_release(this: *mut *mut c_void) -> *mut CxxVector<$ty>;
254 }
255 }
256 __unique_ptr_release(&mut repr)
257 }
258 unsafe fn __unique_ptr_drop(mut repr: *mut c_void) {
259 extern "C" {
260 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800261 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$drop")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700262 fn __unique_ptr_drop(this: *mut *mut c_void);
263 }
264 }
265 __unique_ptr_drop(&mut repr);
266 }
David Tolnaye4b6a622020-04-24 14:55:42 -0700267 }
268 };
269}
270
David Tolnay47e239d2020-08-28 00:32:04 -0700271macro_rules! impl_vector_element_for_primitive {
272 ($ty:ident) => {
273 impl_vector_element!(stringify!($ty), stringify!($ty), $ty);
274 };
275}
276
David Tolnay4b91eaa2020-04-24 14:19:22 -0700277impl_vector_element_for_primitive!(u8);
278impl_vector_element_for_primitive!(u16);
279impl_vector_element_for_primitive!(u32);
280impl_vector_element_for_primitive!(u64);
281impl_vector_element_for_primitive!(usize);
282impl_vector_element_for_primitive!(i8);
283impl_vector_element_for_primitive!(i16);
284impl_vector_element_for_primitive!(i32);
285impl_vector_element_for_primitive!(i64);
286impl_vector_element_for_primitive!(isize);
287impl_vector_element_for_primitive!(f32);
288impl_vector_element_for_primitive!(f64);
David Tolnay47e239d2020-08-28 00:32:04 -0700289
290impl_vector_element!("string", "CxxString", CxxString);