blob: d1611dbd4807122546039b00b35c500568ac3f12 [file] [log] [blame]
David Tolnay47e239d2020-08-28 00:32:04 -07001use crate::cxx_string::CxxString;
David Tolnay3384c142020-09-14 00:26:47 -04002use core::ffi::c_void;
3use core::fmt::{self, Display};
David Tolnay95dab1d2020-11-15 14:32:37 -08004use core::marker::{PhantomData, PhantomPinned};
David Tolnay3384c142020-09-14 00:26:47 -04005use core::mem;
6use core::ptr;
David Tolnay93637ca2020-09-24 15:58:20 -04007use core::slice;
David Tolnay4f7e6fa2020-04-24 11:52:44 -07008
David Tolnay61a9fdf2020-04-24 16:19:42 -07009/// Binding to C++ `std::vector<T, std::allocator<T>>`.
Myron Ahneba35cf2020-02-05 19:41:51 +070010///
11/// # Invariants
12///
13/// As an invariant of this API and the static analysis of the cxx::bridge
David Tolnay5fe93632020-04-24 12:31:00 -070014/// macro, in Rust code we can never obtain a `CxxVector` by value. Instead in
15/// Rust code we will only ever look at a vector behind a reference or smart
16/// pointer, as in `&CxxVector<T>` or `UniquePtr<CxxVector<T>>`.
David Tolnay4f7e6fa2020-04-24 11:52:44 -070017#[repr(C, packed)]
David Tolnaye90be1d2020-04-24 11:45:57 -070018pub struct CxxVector<T> {
Myron Ahneba35cf2020-02-05 19:41:51 +070019 _private: [T; 0],
David Tolnay95dab1d2020-11-15 14:32:37 -080020 _pinned: PhantomData<PhantomPinned>,
Myron Ahneba35cf2020-02-05 19:41:51 +070021}
22
David Tolnay4074ad22020-04-24 18:20:11 -070023impl<T> CxxVector<T>
24where
25 T: VectorElement,
26{
David Tolnaycdc87962020-04-24 13:45:59 -070027 /// Returns the number of elements in the vector.
David Tolnaydd839192020-04-24 16:41:29 -070028 ///
29 /// Matches the behavior of C++ [std::vector\<T\>::size][size].
30 ///
31 /// [size]: https://en.cppreference.com/w/cpp/container/vector/size
David Tolnayc01d0a02020-04-24 13:30:44 -070032 pub fn len(&self) -> usize {
David Tolnay0e084662020-04-24 14:02:51 -070033 T::__vector_size(self)
Myron Ahneba35cf2020-02-05 19:41:51 +070034 }
35
David Tolnaycdc87962020-04-24 13:45:59 -070036 /// Returns true if the vector contains no elements.
David Tolnaydd839192020-04-24 16:41:29 -070037 ///
38 /// Matches the behavior of C++ [std::vector\<T\>::empty][empty].
39 ///
40 /// [empty]: https://en.cppreference.com/w/cpp/container/vector/empty
Myron Ahneba35cf2020-02-05 19:41:51 +070041 pub fn is_empty(&self) -> bool {
David Tolnayc01d0a02020-04-24 13:30:44 -070042 self.len() == 0
Myron Ahneba35cf2020-02-05 19:41:51 +070043 }
44
David Tolnaycdc87962020-04-24 13:45:59 -070045 /// Returns a reference to an element at the given position, or `None` if
46 /// out of bounds.
Myron Ahneba35cf2020-02-05 19:41:51 +070047 pub fn get(&self, pos: usize) -> Option<&T> {
David Tolnayc01d0a02020-04-24 13:30:44 -070048 if pos < self.len() {
David Tolnay93637ca2020-09-24 15:58:20 -040049 Some(unsafe { self.get_unchecked(pos) })
Myron Ahneba35cf2020-02-05 19:41:51 +070050 } else {
51 None
52 }
53 }
54
David Tolnay4944f2f2020-04-24 13:46:12 -070055 /// Returns a reference to an element without doing bounds checking.
56 ///
57 /// This is generally not recommended, use with caution! Calling this method
58 /// with an out-of-bounds index is undefined behavior even if the resulting
59 /// reference is not used.
David Tolnaydd839192020-04-24 16:41:29 -070060 ///
61 /// Matches the behavior of C++
62 /// [std::vector\<T\>::operator\[\]][operator_at].
63 ///
64 /// [operator_at]: https://en.cppreference.com/w/cpp/container/vector/operator_at
David Tolnay4944f2f2020-04-24 13:46:12 -070065 pub unsafe fn get_unchecked(&self, pos: usize) -> &T {
David Tolnay93637ca2020-09-24 15:58:20 -040066 &*T::__get_unchecked(self, pos)
67 }
68
69 /// Returns a slice to the underlying contiguous array of elements.
70 pub fn as_slice(&self) -> &[T] {
71 let len = self.len();
72 if len == 0 {
David Tolnaya5a14ce2020-09-24 16:02:40 -040073 // The slice::from_raw_parts in the other branch requires a nonnull
74 // and properly aligned data ptr. C++ standard does not guarantee
75 // that data() on a vector with size 0 would return a nonnull
76 // pointer or sufficiently aligned pointer, so using it would be
77 // undefined behavior. Create our own empty slice in Rust instead
78 // which upholds the invariants.
David Tolnayacc7fb02020-09-24 18:10:09 -040079 &[]
David Tolnay93637ca2020-09-24 15:58:20 -040080 } else {
81 let ptr = unsafe { T::__get_unchecked(self, 0) };
82 unsafe { slice::from_raw_parts(ptr, len) }
83 }
David Tolnay4944f2f2020-04-24 13:46:12 -070084 }
David Tolnay4f71cc52020-11-15 23:55:27 -080085
86 /// Returns an iterator over elements of type `&T`.
87 pub fn iter(&self) -> Iter<T> {
88 Iter { v: self, index: 0 }
89 }
Myron Ahneba35cf2020-02-05 19:41:51 +070090}
91
David Tolnay3d88bdc2020-04-24 13:48:18 -070092pub struct Iter<'a, T> {
David Tolnaye90be1d2020-04-24 11:45:57 -070093 v: &'a CxxVector<T>,
Myron Ahneba35cf2020-02-05 19:41:51 +070094 index: usize,
95}
96
David Tolnay4074ad22020-04-24 18:20:11 -070097impl<'a, T> IntoIterator for &'a CxxVector<T>
98where
99 T: VectorElement,
100{
Myron Ahneba35cf2020-02-05 19:41:51 +0700101 type Item = &'a T;
David Tolnay3d88bdc2020-04-24 13:48:18 -0700102 type IntoIter = Iter<'a, T>;
Myron Ahneba35cf2020-02-05 19:41:51 +0700103
104 fn into_iter(self) -> Self::IntoIter {
David Tolnay4f71cc52020-11-15 23:55:27 -0800105 self.iter()
Myron Ahneba35cf2020-02-05 19:41:51 +0700106 }
107}
108
David Tolnay4074ad22020-04-24 18:20:11 -0700109impl<'a, T> Iterator for Iter<'a, T>
110where
111 T: VectorElement,
112{
Myron Ahneba35cf2020-02-05 19:41:51 +0700113 type Item = &'a T;
David Tolnay85db5a02020-04-25 13:17:27 -0700114
Myron Ahneba35cf2020-02-05 19:41:51 +0700115 fn next(&mut self) -> Option<Self::Item> {
David Tolnay39ee0ed2020-05-05 10:12:29 -0700116 let next = self.v.get(self.index);
117 self.index += 1;
118 next
Myron Ahneba35cf2020-02-05 19:41:51 +0700119 }
120}
121
David Tolnay3b40b6f2020-04-24 17:58:24 -0700122pub struct TypeName<T> {
123 element: PhantomData<T>,
124}
125
126impl<T> TypeName<T> {
127 pub const fn new() -> Self {
128 TypeName {
129 element: PhantomData,
130 }
131 }
132}
133
134impl<T> Display for TypeName<T>
135where
136 T: VectorElement,
137{
138 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
139 write!(formatter, "CxxVector<{}>", T::__NAME)
140 }
141}
142
David Tolnay5104c862020-04-24 13:26:01 -0700143// Methods are private; not intended to be implemented outside of cxxbridge
144// codebase.
David Tolnay1b341192020-04-24 13:04:04 -0700145#[doc(hidden)]
David Tolnayc3ed3a62020-04-24 13:34:50 -0700146pub unsafe trait VectorElement: Sized {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700147 const __NAME: &'static dyn Display;
David Tolnay0e084662020-04-24 14:02:51 -0700148 fn __vector_size(v: &CxxVector<Self>) -> usize;
David Tolnay93637ca2020-09-24 15:58:20 -0400149 unsafe fn __get_unchecked(v: &CxxVector<Self>, pos: usize) -> *const Self;
David Tolnay3b40b6f2020-04-24 17:58:24 -0700150 fn __unique_ptr_null() -> *mut c_void;
151 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void;
152 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self>;
153 unsafe fn __unique_ptr_release(repr: *mut c_void) -> *mut CxxVector<Self>;
154 unsafe fn __unique_ptr_drop(repr: *mut c_void);
David Tolnay1b341192020-04-24 13:04:04 -0700155}
156
David Tolnay47e239d2020-08-28 00:32:04 -0700157macro_rules! impl_vector_element {
158 ($segment:expr, $name:expr, $ty:ty) => {
David Tolnayf0446632020-04-25 11:29:26 -0700159 const_assert_eq!(1, mem::align_of::<CxxVector<$ty>>());
160
David Tolnaye4b6a622020-04-24 14:55:42 -0700161 unsafe impl VectorElement for $ty {
David Tolnay47e239d2020-08-28 00:32:04 -0700162 const __NAME: &'static dyn Display = &$name;
David Tolnaye4b6a622020-04-24 14:55:42 -0700163 fn __vector_size(v: &CxxVector<$ty>) -> usize {
164 extern "C" {
165 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800166 #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$size")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700167 fn __vector_size(_: &CxxVector<$ty>) -> usize;
168 }
169 }
170 unsafe { __vector_size(v) }
171 }
David Tolnay93637ca2020-09-24 15:58:20 -0400172 unsafe fn __get_unchecked(v: &CxxVector<$ty>, pos: usize) -> *const $ty {
David Tolnaye4b6a622020-04-24 14:55:42 -0700173 extern "C" {
174 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800175 #[link_name = concat!("cxxbridge1$std$vector$", $segment, "$get_unchecked")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700176 fn __get_unchecked(_: &CxxVector<$ty>, _: usize) -> *const $ty;
177 }
178 }
David Tolnay93637ca2020-09-24 15:58:20 -0400179 __get_unchecked(v, pos)
David Tolnaye4b6a622020-04-24 14:55:42 -0700180 }
David Tolnay3b40b6f2020-04-24 17:58:24 -0700181 fn __unique_ptr_null() -> *mut c_void {
182 extern "C" {
183 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800184 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$null")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700185 fn __unique_ptr_null(this: *mut *mut c_void);
186 }
187 }
188 let mut repr = ptr::null_mut::<c_void>();
189 unsafe { __unique_ptr_null(&mut repr) }
190 repr
191 }
192 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void {
193 extern "C" {
194 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800195 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$raw")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700196 fn __unique_ptr_raw(this: *mut *mut c_void, raw: *mut CxxVector<$ty>);
197 }
198 }
199 let mut repr = ptr::null_mut::<c_void>();
200 __unique_ptr_raw(&mut repr, raw);
201 repr
202 }
203 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self> {
204 extern "C" {
205 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800206 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$get")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700207 fn __unique_ptr_get(this: *const *mut c_void) -> *const CxxVector<$ty>;
208 }
209 }
210 __unique_ptr_get(&repr)
211 }
212 unsafe fn __unique_ptr_release(mut repr: *mut c_void) -> *mut CxxVector<Self> {
213 extern "C" {
214 attr! {
David Tolnay0f0162f2020-11-16 23:43:37 -0800215 #[link_name = concat!("cxxbridge1$unique_ptr$std$vector$", $segment, "$release")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700216 fn __unique_ptr_release(this: *mut *mut c_void) -> *mut CxxVector<$ty>;
217 }
218 }
219 __unique_ptr_release(&mut repr)
220 }
221 unsafe fn __unique_ptr_drop(mut repr: *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, "$drop")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700225 fn __unique_ptr_drop(this: *mut *mut c_void);
226 }
227 }
228 __unique_ptr_drop(&mut repr);
229 }
David Tolnaye4b6a622020-04-24 14:55:42 -0700230 }
231 };
232}
233
David Tolnay47e239d2020-08-28 00:32:04 -0700234macro_rules! impl_vector_element_for_primitive {
235 ($ty:ident) => {
236 impl_vector_element!(stringify!($ty), stringify!($ty), $ty);
237 };
238}
239
David Tolnay4b91eaa2020-04-24 14:19:22 -0700240impl_vector_element_for_primitive!(u8);
241impl_vector_element_for_primitive!(u16);
242impl_vector_element_for_primitive!(u32);
243impl_vector_element_for_primitive!(u64);
244impl_vector_element_for_primitive!(usize);
245impl_vector_element_for_primitive!(i8);
246impl_vector_element_for_primitive!(i16);
247impl_vector_element_for_primitive!(i32);
248impl_vector_element_for_primitive!(i64);
249impl_vector_element_for_primitive!(isize);
250impl_vector_element_for_primitive!(f32);
251impl_vector_element_for_primitive!(f64);
David Tolnay47e239d2020-08-28 00:32:04 -0700252
253impl_vector_element!("string", "CxxString", CxxString);