blob: d4bd71108e95ee84119f873d838cb8e09d120a4a [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;
12use core::ptr;
David Tolnay93637ca2020-09-24 15:58:20 -040013use core::slice;
David Tolnay4f7e6fa2020-04-24 11:52:44 -070014
David Tolnayb5d039c2020-12-12 23:21:17 -080015#[doc(inline)]
16pub use crate::Vector;
17
David Tolnay61a9fdf2020-04-24 16:19:42 -070018/// Binding to C++ `std::vector<T, std::allocator<T>>`.
Myron Ahneba35cf2020-02-05 19:41:51 +070019///
20/// # Invariants
21///
22/// As an invariant of this API and the static analysis of the cxx::bridge
David Tolnay5fe93632020-04-24 12:31:00 -070023/// macro, in Rust code we can never obtain a `CxxVector` by value. Instead in
24/// Rust code we will only ever look at a vector behind a reference or smart
25/// pointer, as in `&CxxVector<T>` or `UniquePtr<CxxVector<T>>`.
David Tolnay4f7e6fa2020-04-24 11:52:44 -070026#[repr(C, packed)]
David Tolnaye90be1d2020-04-24 11:45:57 -070027pub struct CxxVector<T> {
Myron Ahneba35cf2020-02-05 19:41:51 +070028 _private: [T; 0],
David Tolnay95dab1d2020-11-15 14:32:37 -080029 _pinned: PhantomData<PhantomPinned>,
Myron Ahneba35cf2020-02-05 19:41:51 +070030}
31
David Tolnay4074ad22020-04-24 18:20:11 -070032impl<T> CxxVector<T>
33where
34 T: VectorElement,
35{
David Tolnaycdc87962020-04-24 13:45:59 -070036 /// Returns the number of elements in the vector.
David Tolnaydd839192020-04-24 16:41:29 -070037 ///
38 /// Matches the behavior of C++ [std::vector\<T\>::size][size].
39 ///
40 /// [size]: https://en.cppreference.com/w/cpp/container/vector/size
David Tolnayc01d0a02020-04-24 13:30:44 -070041 pub fn len(&self) -> usize {
David Tolnay0e084662020-04-24 14:02:51 -070042 T::__vector_size(self)
Myron Ahneba35cf2020-02-05 19:41:51 +070043 }
44
David Tolnaycdc87962020-04-24 13:45:59 -070045 /// Returns true if the vector contains no elements.
David Tolnaydd839192020-04-24 16:41:29 -070046 ///
47 /// Matches the behavior of C++ [std::vector\<T\>::empty][empty].
48 ///
49 /// [empty]: https://en.cppreference.com/w/cpp/container/vector/empty
Myron Ahneba35cf2020-02-05 19:41:51 +070050 pub fn is_empty(&self) -> bool {
David Tolnayc01d0a02020-04-24 13:30:44 -070051 self.len() == 0
Myron Ahneba35cf2020-02-05 19:41:51 +070052 }
53
David Tolnaycdc87962020-04-24 13:45:59 -070054 /// Returns a reference to an element at the given position, or `None` if
55 /// out of bounds.
Myron Ahneba35cf2020-02-05 19:41:51 +070056 pub fn get(&self, pos: usize) -> Option<&T> {
David Tolnayc01d0a02020-04-24 13:30:44 -070057 if pos < self.len() {
David Tolnay93637ca2020-09-24 15:58:20 -040058 Some(unsafe { self.get_unchecked(pos) })
Myron Ahneba35cf2020-02-05 19:41:51 +070059 } else {
60 None
61 }
62 }
63
David Tolnay4944f2f2020-04-24 13:46:12 -070064 /// Returns a reference to an element without doing bounds checking.
65 ///
66 /// This is generally not recommended, use with caution! Calling this method
67 /// with an out-of-bounds index is undefined behavior even if the resulting
68 /// reference is not used.
David Tolnaydd839192020-04-24 16:41:29 -070069 ///
70 /// Matches the behavior of C++
71 /// [std::vector\<T\>::operator\[\]][operator_at].
72 ///
73 /// [operator_at]: https://en.cppreference.com/w/cpp/container/vector/operator_at
David Tolnay4944f2f2020-04-24 13:46:12 -070074 pub unsafe fn get_unchecked(&self, pos: usize) -> &T {
David Tolnay93637ca2020-09-24 15:58:20 -040075 &*T::__get_unchecked(self, pos)
76 }
77
78 /// Returns a slice to the underlying contiguous array of elements.
David Tolnay181ee912020-12-04 12:15:10 -080079 pub fn as_slice(&self) -> &[T]
80 where
81 T: ExternType<Kind = Trivial>,
82 {
David Tolnay93637ca2020-09-24 15:58:20 -040083 let len = self.len();
84 if len == 0 {
David Tolnaya5a14ce2020-09-24 16:02:40 -040085 // The slice::from_raw_parts in the other branch requires a nonnull
86 // and properly aligned data ptr. C++ standard does not guarantee
87 // that data() on a vector with size 0 would return a nonnull
88 // pointer or sufficiently aligned pointer, so using it would be
89 // undefined behavior. Create our own empty slice in Rust instead
90 // which upholds the invariants.
David Tolnayacc7fb02020-09-24 18:10:09 -040091 &[]
David Tolnay93637ca2020-09-24 15:58:20 -040092 } else {
93 let ptr = unsafe { T::__get_unchecked(self, 0) };
94 unsafe { slice::from_raw_parts(ptr, len) }
95 }
David Tolnay4944f2f2020-04-24 13:46:12 -070096 }
David Tolnay4f71cc52020-11-15 23:55:27 -080097
98 /// Returns an iterator over elements of type `&T`.
99 pub fn iter(&self) -> Iter<T> {
100 Iter { v: self, index: 0 }
101 }
Myron Ahneba35cf2020-02-05 19:41:51 +0700102}
103
David Tolnayb5d039c2020-12-12 23:21:17 -0800104/// Iterator over elements of a `CxxVector` by shared reference.
105///
106/// The iterator element type is `&'a T`.
David Tolnay3d88bdc2020-04-24 13:48:18 -0700107pub struct Iter<'a, T> {
David Tolnaye90be1d2020-04-24 11:45:57 -0700108 v: &'a CxxVector<T>,
Myron Ahneba35cf2020-02-05 19:41:51 +0700109 index: usize,
110}
111
David Tolnay4074ad22020-04-24 18:20:11 -0700112impl<'a, T> IntoIterator for &'a CxxVector<T>
113where
114 T: VectorElement,
115{
Myron Ahneba35cf2020-02-05 19:41:51 +0700116 type Item = &'a T;
David Tolnay3d88bdc2020-04-24 13:48:18 -0700117 type IntoIter = Iter<'a, T>;
Myron Ahneba35cf2020-02-05 19:41:51 +0700118
119 fn into_iter(self) -> Self::IntoIter {
David Tolnay4f71cc52020-11-15 23:55:27 -0800120 self.iter()
Myron Ahneba35cf2020-02-05 19:41:51 +0700121 }
122}
123
David Tolnay4074ad22020-04-24 18:20:11 -0700124impl<'a, T> Iterator for Iter<'a, T>
125where
126 T: VectorElement,
127{
Myron Ahneba35cf2020-02-05 19:41:51 +0700128 type Item = &'a T;
David Tolnay85db5a02020-04-25 13:17:27 -0700129
Myron Ahneba35cf2020-02-05 19:41:51 +0700130 fn next(&mut self) -> Option<Self::Item> {
David Tolnay39ee0ed2020-05-05 10:12:29 -0700131 let next = self.v.get(self.index);
David Tolnay724ac752020-12-13 16:00:48 -0800132 self.index += next.is_some() as usize;
David Tolnay39ee0ed2020-05-05 10:12:29 -0700133 next
Myron Ahneba35cf2020-02-05 19:41:51 +0700134 }
David Tolnay724ac752020-12-13 16:00:48 -0800135
136 fn size_hint(&self) -> (usize, Option<usize>) {
137 let len = self.len();
138 (len, Some(len))
139 }
140}
141
142impl<'a, T> ExactSizeIterator for Iter<'a, T>
143where
144 T: VectorElement,
145{
146 fn len(&self) -> usize {
147 self.v.len() - self.index
148 }
Myron Ahneba35cf2020-02-05 19:41:51 +0700149}
150
David Tolnay526faa22020-12-13 16:10:47 -0800151impl<'a, T> FusedIterator for Iter<'a, T> where T: VectorElement {}
152
David Tolnaya8100ed2020-12-04 12:41:24 -0800153impl<T> Debug for CxxVector<T>
154where
155 T: VectorElement + Debug,
156{
157 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
158 formatter.debug_list().entries(self).finish()
159 }
160}
161
David Tolnayb5d039c2020-12-12 23:21:17 -0800162pub(crate) struct TypeName<T> {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700163 element: PhantomData<T>,
164}
165
166impl<T> TypeName<T> {
167 pub const fn new() -> Self {
168 TypeName {
169 element: PhantomData,
170 }
171 }
172}
173
174impl<T> Display for TypeName<T>
175where
176 T: VectorElement,
177{
178 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
179 write!(formatter, "CxxVector<{}>", T::__NAME)
180 }
181}
182
David Tolnay5104c862020-04-24 13:26:01 -0700183// Methods are private; not intended to be implemented outside of cxxbridge
184// codebase.
David Tolnay1b341192020-04-24 13:04:04 -0700185#[doc(hidden)]
David Tolnayc3ed3a62020-04-24 13:34:50 -0700186pub unsafe trait VectorElement: Sized {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700187 const __NAME: &'static dyn Display;
David Tolnay0e084662020-04-24 14:02:51 -0700188 fn __vector_size(v: &CxxVector<Self>) -> usize;
David Tolnay93637ca2020-09-24 15:58:20 -0400189 unsafe fn __get_unchecked(v: &CxxVector<Self>, pos: usize) -> *const Self;
David Tolnay3b40b6f2020-04-24 17:58:24 -0700190 fn __unique_ptr_null() -> *mut c_void;
191 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void;
192 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self>;
193 unsafe fn __unique_ptr_release(repr: *mut c_void) -> *mut CxxVector<Self>;
194 unsafe fn __unique_ptr_drop(repr: *mut c_void);
David Tolnay1b341192020-04-24 13:04:04 -0700195}
196
David Tolnay47e239d2020-08-28 00:32:04 -0700197macro_rules! impl_vector_element {
198 ($segment:expr, $name:expr, $ty:ty) => {
David Tolnayf0446632020-04-25 11:29:26 -0700199 const_assert_eq!(1, mem::align_of::<CxxVector<$ty>>());
200
David Tolnaye4b6a622020-04-24 14:55:42 -0700201 unsafe impl VectorElement for $ty {
David Tolnay47e239d2020-08-28 00:32:04 -0700202 const __NAME: &'static dyn Display = &$name;
David Tolnaye4b6a622020-04-24 14:55:42 -0700203 fn __vector_size(v: &CxxVector<$ty>) -> usize {
204 extern "C" {
205 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800206 #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$size")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700207 fn __vector_size(_: &CxxVector<$ty>) -> usize;
208 }
209 }
210 unsafe { __vector_size(v) }
211 }
David Tolnay93637ca2020-09-24 15:58:20 -0400212 unsafe fn __get_unchecked(v: &CxxVector<$ty>, pos: usize) -> *const $ty {
David Tolnaye4b6a622020-04-24 14:55:42 -0700213 extern "C" {
214 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800215 #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$get_unchecked")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700216 fn __get_unchecked(_: &CxxVector<$ty>, _: usize) -> *const $ty;
217 }
218 }
David Tolnay93637ca2020-09-24 15:58:20 -0400219 __get_unchecked(v, pos)
David Tolnaye4b6a622020-04-24 14:55:42 -0700220 }
David Tolnay3b40b6f2020-04-24 17:58:24 -0700221 fn __unique_ptr_null() -> *mut c_void {
222 extern "C" {
223 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800224 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$null")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700225 fn __unique_ptr_null(this: *mut *mut c_void);
226 }
227 }
228 let mut repr = ptr::null_mut::<c_void>();
229 unsafe { __unique_ptr_null(&mut repr) }
230 repr
231 }
232 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void {
233 extern "C" {
234 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800235 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$raw")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700236 fn __unique_ptr_raw(this: *mut *mut c_void, raw: *mut CxxVector<$ty>);
237 }
238 }
239 let mut repr = ptr::null_mut::<c_void>();
240 __unique_ptr_raw(&mut repr, raw);
241 repr
242 }
243 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self> {
244 extern "C" {
245 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800246 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$get")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700247 fn __unique_ptr_get(this: *const *mut c_void) -> *const CxxVector<$ty>;
248 }
249 }
250 __unique_ptr_get(&repr)
251 }
252 unsafe fn __unique_ptr_release(mut repr: *mut c_void) -> *mut CxxVector<Self> {
253 extern "C" {
254 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800255 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$release")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700256 fn __unique_ptr_release(this: *mut *mut c_void) -> *mut CxxVector<$ty>;
257 }
258 }
259 __unique_ptr_release(&mut repr)
260 }
261 unsafe fn __unique_ptr_drop(mut repr: *mut c_void) {
262 extern "C" {
263 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800264 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$drop")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700265 fn __unique_ptr_drop(this: *mut *mut c_void);
266 }
267 }
268 __unique_ptr_drop(&mut repr);
269 }
David Tolnaye4b6a622020-04-24 14:55:42 -0700270 }
271 };
272}
273
David Tolnay47e239d2020-08-28 00:32:04 -0700274macro_rules! impl_vector_element_for_primitive {
275 ($ty:ident) => {
276 impl_vector_element!(stringify!($ty), stringify!($ty), $ty);
277 };
278}
279
David Tolnay4b91eaa2020-04-24 14:19:22 -0700280impl_vector_element_for_primitive!(u8);
281impl_vector_element_for_primitive!(u16);
282impl_vector_element_for_primitive!(u32);
283impl_vector_element_for_primitive!(u64);
284impl_vector_element_for_primitive!(usize);
285impl_vector_element_for_primitive!(i8);
286impl_vector_element_for_primitive!(i16);
287impl_vector_element_for_primitive!(i32);
288impl_vector_element_for_primitive!(i64);
289impl_vector_element_for_primitive!(isize);
290impl_vector_element_for_primitive!(f32);
291impl_vector_element_for_primitive!(f64);
David Tolnay47e239d2020-08-28 00:32:04 -0700292
293impl_vector_element!("string", "CxxString", CxxString);