blob: df29616a0c6bc051ff87f0b8068d3dc1fec5cbf8 [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);
131 self.index += 1;
132 next
Myron Ahneba35cf2020-02-05 19:41:51 +0700133 }
134}
135
David Tolnaya8100ed2020-12-04 12:41:24 -0800136impl<T> Debug for CxxVector<T>
137where
138 T: VectorElement + Debug,
139{
140 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
141 formatter.debug_list().entries(self).finish()
142 }
143}
144
David Tolnayb5d039c2020-12-12 23:21:17 -0800145pub(crate) struct TypeName<T> {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700146 element: PhantomData<T>,
147}
148
149impl<T> TypeName<T> {
150 pub const fn new() -> Self {
151 TypeName {
152 element: PhantomData,
153 }
154 }
155}
156
157impl<T> Display for TypeName<T>
158where
159 T: VectorElement,
160{
161 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
162 write!(formatter, "CxxVector<{}>", T::__NAME)
163 }
164}
165
David Tolnay5104c862020-04-24 13:26:01 -0700166// Methods are private; not intended to be implemented outside of cxxbridge
167// codebase.
David Tolnay1b341192020-04-24 13:04:04 -0700168#[doc(hidden)]
David Tolnayc3ed3a62020-04-24 13:34:50 -0700169pub unsafe trait VectorElement: Sized {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700170 const __NAME: &'static dyn Display;
David Tolnay0e084662020-04-24 14:02:51 -0700171 fn __vector_size(v: &CxxVector<Self>) -> usize;
David Tolnay93637ca2020-09-24 15:58:20 -0400172 unsafe fn __get_unchecked(v: &CxxVector<Self>, pos: usize) -> *const Self;
David Tolnay3b40b6f2020-04-24 17:58:24 -0700173 fn __unique_ptr_null() -> *mut c_void;
174 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void;
175 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self>;
176 unsafe fn __unique_ptr_release(repr: *mut c_void) -> *mut CxxVector<Self>;
177 unsafe fn __unique_ptr_drop(repr: *mut c_void);
David Tolnay1b341192020-04-24 13:04:04 -0700178}
179
David Tolnay47e239d2020-08-28 00:32:04 -0700180macro_rules! impl_vector_element {
181 ($segment:expr, $name:expr, $ty:ty) => {
David Tolnayf0446632020-04-25 11:29:26 -0700182 const_assert_eq!(1, mem::align_of::<CxxVector<$ty>>());
183
David Tolnaye4b6a622020-04-24 14:55:42 -0700184 unsafe impl VectorElement for $ty {
David Tolnay47e239d2020-08-28 00:32:04 -0700185 const __NAME: &'static dyn Display = &$name;
David Tolnaye4b6a622020-04-24 14:55:42 -0700186 fn __vector_size(v: &CxxVector<$ty>) -> usize {
187 extern "C" {
188 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800189 #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$size")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700190 fn __vector_size(_: &CxxVector<$ty>) -> usize;
191 }
192 }
193 unsafe { __vector_size(v) }
194 }
David Tolnay93637ca2020-09-24 15:58:20 -0400195 unsafe fn __get_unchecked(v: &CxxVector<$ty>, pos: usize) -> *const $ty {
David Tolnaye4b6a622020-04-24 14:55:42 -0700196 extern "C" {
197 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800198 #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$get_unchecked")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700199 fn __get_unchecked(_: &CxxVector<$ty>, _: usize) -> *const $ty;
200 }
201 }
David Tolnay93637ca2020-09-24 15:58:20 -0400202 __get_unchecked(v, pos)
David Tolnaye4b6a622020-04-24 14:55:42 -0700203 }
David Tolnay3b40b6f2020-04-24 17:58:24 -0700204 fn __unique_ptr_null() -> *mut c_void {
205 extern "C" {
206 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800207 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$null")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700208 fn __unique_ptr_null(this: *mut *mut c_void);
209 }
210 }
211 let mut repr = ptr::null_mut::<c_void>();
212 unsafe { __unique_ptr_null(&mut repr) }
213 repr
214 }
215 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void {
216 extern "C" {
217 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800218 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$raw")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700219 fn __unique_ptr_raw(this: *mut *mut c_void, raw: *mut CxxVector<$ty>);
220 }
221 }
222 let mut repr = ptr::null_mut::<c_void>();
223 __unique_ptr_raw(&mut repr, raw);
224 repr
225 }
226 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self> {
227 extern "C" {
228 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800229 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$get")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700230 fn __unique_ptr_get(this: *const *mut c_void) -> *const CxxVector<$ty>;
231 }
232 }
233 __unique_ptr_get(&repr)
234 }
235 unsafe fn __unique_ptr_release(mut repr: *mut c_void) -> *mut CxxVector<Self> {
236 extern "C" {
237 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800238 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$release")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700239 fn __unique_ptr_release(this: *mut *mut c_void) -> *mut CxxVector<$ty>;
240 }
241 }
242 __unique_ptr_release(&mut repr)
243 }
244 unsafe fn __unique_ptr_drop(mut repr: *mut c_void) {
245 extern "C" {
246 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800247 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$drop")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700248 fn __unique_ptr_drop(this: *mut *mut c_void);
249 }
250 }
251 __unique_ptr_drop(&mut repr);
252 }
David Tolnaye4b6a622020-04-24 14:55:42 -0700253 }
254 };
255}
256
David Tolnay47e239d2020-08-28 00:32:04 -0700257macro_rules! impl_vector_element_for_primitive {
258 ($ty:ident) => {
259 impl_vector_element!(stringify!($ty), stringify!($ty), $ty);
260 };
261}
262
David Tolnay4b91eaa2020-04-24 14:19:22 -0700263impl_vector_element_for_primitive!(u8);
264impl_vector_element_for_primitive!(u16);
265impl_vector_element_for_primitive!(u32);
266impl_vector_element_for_primitive!(u64);
267impl_vector_element_for_primitive!(usize);
268impl_vector_element_for_primitive!(i8);
269impl_vector_element_for_primitive!(i16);
270impl_vector_element_for_primitive!(i32);
271impl_vector_element_for_primitive!(i64);
272impl_vector_element_for_primitive!(isize);
273impl_vector_element_for_primitive!(f32);
274impl_vector_element_for_primitive!(f64);
David Tolnay47e239d2020-08-28 00:32:04 -0700275
276impl_vector_element!("string", "CxxString", CxxString);