blob: 3ab3193e03733e92a7497ba4f567fcbc49cb1c53 [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};
4use core::marker::PhantomData;
5use 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],
20}
21
David Tolnay4074ad22020-04-24 18:20:11 -070022impl<T> CxxVector<T>
23where
24 T: VectorElement,
25{
David Tolnaycdc87962020-04-24 13:45:59 -070026 /// Returns the number of elements in the vector.
David Tolnaydd839192020-04-24 16:41:29 -070027 ///
28 /// Matches the behavior of C++ [std::vector\<T\>::size][size].
29 ///
30 /// [size]: https://en.cppreference.com/w/cpp/container/vector/size
David Tolnayc01d0a02020-04-24 13:30:44 -070031 pub fn len(&self) -> usize {
David Tolnay0e084662020-04-24 14:02:51 -070032 T::__vector_size(self)
Myron Ahneba35cf2020-02-05 19:41:51 +070033 }
34
David Tolnaycdc87962020-04-24 13:45:59 -070035 /// Returns true if the vector contains no elements.
David Tolnaydd839192020-04-24 16:41:29 -070036 ///
37 /// Matches the behavior of C++ [std::vector\<T\>::empty][empty].
38 ///
39 /// [empty]: https://en.cppreference.com/w/cpp/container/vector/empty
Myron Ahneba35cf2020-02-05 19:41:51 +070040 pub fn is_empty(&self) -> bool {
David Tolnayc01d0a02020-04-24 13:30:44 -070041 self.len() == 0
Myron Ahneba35cf2020-02-05 19:41:51 +070042 }
43
David Tolnaycdc87962020-04-24 13:45:59 -070044 /// Returns a reference to an element at the given position, or `None` if
45 /// out of bounds.
Myron Ahneba35cf2020-02-05 19:41:51 +070046 pub fn get(&self, pos: usize) -> Option<&T> {
David Tolnayc01d0a02020-04-24 13:30:44 -070047 if pos < self.len() {
David Tolnay93637ca2020-09-24 15:58:20 -040048 Some(unsafe { self.get_unchecked(pos) })
Myron Ahneba35cf2020-02-05 19:41:51 +070049 } else {
50 None
51 }
52 }
53
David Tolnay4944f2f2020-04-24 13:46:12 -070054 /// Returns a reference to an element without doing bounds checking.
55 ///
56 /// This is generally not recommended, use with caution! Calling this method
57 /// with an out-of-bounds index is undefined behavior even if the resulting
58 /// reference is not used.
David Tolnaydd839192020-04-24 16:41:29 -070059 ///
60 /// Matches the behavior of C++
61 /// [std::vector\<T\>::operator\[\]][operator_at].
62 ///
63 /// [operator_at]: https://en.cppreference.com/w/cpp/container/vector/operator_at
David Tolnay4944f2f2020-04-24 13:46:12 -070064 pub unsafe fn get_unchecked(&self, pos: usize) -> &T {
David Tolnay93637ca2020-09-24 15:58:20 -040065 &*T::__get_unchecked(self, pos)
66 }
67
68 /// Returns a slice to the underlying contiguous array of elements.
69 pub fn as_slice(&self) -> &[T] {
70 let len = self.len();
71 if len == 0 {
72 <&[T]>::default()
73 } else {
74 let ptr = unsafe { T::__get_unchecked(self, 0) };
75 unsafe { slice::from_raw_parts(ptr, len) }
76 }
David Tolnay4944f2f2020-04-24 13:46:12 -070077 }
Myron Ahneba35cf2020-02-05 19:41:51 +070078}
79
David Tolnay3d88bdc2020-04-24 13:48:18 -070080pub struct Iter<'a, T> {
David Tolnaye90be1d2020-04-24 11:45:57 -070081 v: &'a CxxVector<T>,
Myron Ahneba35cf2020-02-05 19:41:51 +070082 index: usize,
83}
84
David Tolnay4074ad22020-04-24 18:20:11 -070085impl<'a, T> IntoIterator for &'a CxxVector<T>
86where
87 T: VectorElement,
88{
Myron Ahneba35cf2020-02-05 19:41:51 +070089 type Item = &'a T;
David Tolnay3d88bdc2020-04-24 13:48:18 -070090 type IntoIter = Iter<'a, T>;
Myron Ahneba35cf2020-02-05 19:41:51 +070091
92 fn into_iter(self) -> Self::IntoIter {
David Tolnay3d88bdc2020-04-24 13:48:18 -070093 Iter { v: self, index: 0 }
Myron Ahneba35cf2020-02-05 19:41:51 +070094 }
95}
96
David Tolnay4074ad22020-04-24 18:20:11 -070097impl<'a, T> Iterator for Iter<'a, T>
98where
99 T: VectorElement,
100{
Myron Ahneba35cf2020-02-05 19:41:51 +0700101 type Item = &'a T;
David Tolnay85db5a02020-04-25 13:17:27 -0700102
Myron Ahneba35cf2020-02-05 19:41:51 +0700103 fn next(&mut self) -> Option<Self::Item> {
David Tolnay39ee0ed2020-05-05 10:12:29 -0700104 let next = self.v.get(self.index);
105 self.index += 1;
106 next
Myron Ahneba35cf2020-02-05 19:41:51 +0700107 }
108}
109
David Tolnay3b40b6f2020-04-24 17:58:24 -0700110pub struct TypeName<T> {
111 element: PhantomData<T>,
112}
113
114impl<T> TypeName<T> {
115 pub const fn new() -> Self {
116 TypeName {
117 element: PhantomData,
118 }
119 }
120}
121
122impl<T> Display for TypeName<T>
123where
124 T: VectorElement,
125{
126 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
127 write!(formatter, "CxxVector<{}>", T::__NAME)
128 }
129}
130
David Tolnay5104c862020-04-24 13:26:01 -0700131// Methods are private; not intended to be implemented outside of cxxbridge
132// codebase.
David Tolnay1b341192020-04-24 13:04:04 -0700133#[doc(hidden)]
David Tolnayc3ed3a62020-04-24 13:34:50 -0700134pub unsafe trait VectorElement: Sized {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700135 const __NAME: &'static dyn Display;
David Tolnay0e084662020-04-24 14:02:51 -0700136 fn __vector_size(v: &CxxVector<Self>) -> usize;
David Tolnay93637ca2020-09-24 15:58:20 -0400137 unsafe fn __get_unchecked(v: &CxxVector<Self>, pos: usize) -> *const Self;
David Tolnay3b40b6f2020-04-24 17:58:24 -0700138 fn __unique_ptr_null() -> *mut c_void;
139 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void;
140 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self>;
141 unsafe fn __unique_ptr_release(repr: *mut c_void) -> *mut CxxVector<Self>;
142 unsafe fn __unique_ptr_drop(repr: *mut c_void);
David Tolnay1b341192020-04-24 13:04:04 -0700143}
144
David Tolnay47e239d2020-08-28 00:32:04 -0700145macro_rules! impl_vector_element {
146 ($segment:expr, $name:expr, $ty:ty) => {
David Tolnayf0446632020-04-25 11:29:26 -0700147 const_assert_eq!(1, mem::align_of::<CxxVector<$ty>>());
148
David Tolnaye4b6a622020-04-24 14:55:42 -0700149 unsafe impl VectorElement for $ty {
David Tolnay47e239d2020-08-28 00:32:04 -0700150 const __NAME: &'static dyn Display = &$name;
David Tolnaye4b6a622020-04-24 14:55:42 -0700151 fn __vector_size(v: &CxxVector<$ty>) -> usize {
152 extern "C" {
153 attr! {
David Tolnay591dcb62020-09-01 23:00:38 -0700154 #[link_name = concat!("cxxbridge04$std$vector$", $segment, "$size")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700155 fn __vector_size(_: &CxxVector<$ty>) -> usize;
156 }
157 }
158 unsafe { __vector_size(v) }
159 }
David Tolnay93637ca2020-09-24 15:58:20 -0400160 unsafe fn __get_unchecked(v: &CxxVector<$ty>, pos: usize) -> *const $ty {
David Tolnaye4b6a622020-04-24 14:55:42 -0700161 extern "C" {
162 attr! {
David Tolnay591dcb62020-09-01 23:00:38 -0700163 #[link_name = concat!("cxxbridge04$std$vector$", $segment, "$get_unchecked")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700164 fn __get_unchecked(_: &CxxVector<$ty>, _: usize) -> *const $ty;
165 }
166 }
David Tolnay93637ca2020-09-24 15:58:20 -0400167 __get_unchecked(v, pos)
David Tolnaye4b6a622020-04-24 14:55:42 -0700168 }
David Tolnay3b40b6f2020-04-24 17:58:24 -0700169 fn __unique_ptr_null() -> *mut c_void {
170 extern "C" {
171 attr! {
David Tolnay591dcb62020-09-01 23:00:38 -0700172 #[link_name = concat!("cxxbridge04$unique_ptr$std$vector$", $segment, "$null")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700173 fn __unique_ptr_null(this: *mut *mut c_void);
174 }
175 }
176 let mut repr = ptr::null_mut::<c_void>();
177 unsafe { __unique_ptr_null(&mut repr) }
178 repr
179 }
180 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void {
181 extern "C" {
182 attr! {
David Tolnay591dcb62020-09-01 23:00:38 -0700183 #[link_name = concat!("cxxbridge04$unique_ptr$std$vector$", $segment, "$raw")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700184 fn __unique_ptr_raw(this: *mut *mut c_void, raw: *mut CxxVector<$ty>);
185 }
186 }
187 let mut repr = ptr::null_mut::<c_void>();
188 __unique_ptr_raw(&mut repr, raw);
189 repr
190 }
191 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self> {
192 extern "C" {
193 attr! {
David Tolnay591dcb62020-09-01 23:00:38 -0700194 #[link_name = concat!("cxxbridge04$unique_ptr$std$vector$", $segment, "$get")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700195 fn __unique_ptr_get(this: *const *mut c_void) -> *const CxxVector<$ty>;
196 }
197 }
198 __unique_ptr_get(&repr)
199 }
200 unsafe fn __unique_ptr_release(mut repr: *mut c_void) -> *mut CxxVector<Self> {
201 extern "C" {
202 attr! {
David Tolnay591dcb62020-09-01 23:00:38 -0700203 #[link_name = concat!("cxxbridge04$unique_ptr$std$vector$", $segment, "$release")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700204 fn __unique_ptr_release(this: *mut *mut c_void) -> *mut CxxVector<$ty>;
205 }
206 }
207 __unique_ptr_release(&mut repr)
208 }
209 unsafe fn __unique_ptr_drop(mut repr: *mut c_void) {
210 extern "C" {
211 attr! {
David Tolnay591dcb62020-09-01 23:00:38 -0700212 #[link_name = concat!("cxxbridge04$unique_ptr$std$vector$", $segment, "$drop")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700213 fn __unique_ptr_drop(this: *mut *mut c_void);
214 }
215 }
216 __unique_ptr_drop(&mut repr);
217 }
David Tolnaye4b6a622020-04-24 14:55:42 -0700218 }
219 };
220}
221
David Tolnay47e239d2020-08-28 00:32:04 -0700222macro_rules! impl_vector_element_for_primitive {
223 ($ty:ident) => {
224 impl_vector_element!(stringify!($ty), stringify!($ty), $ty);
225 };
226}
227
David Tolnay4b91eaa2020-04-24 14:19:22 -0700228impl_vector_element_for_primitive!(u8);
229impl_vector_element_for_primitive!(u16);
230impl_vector_element_for_primitive!(u32);
231impl_vector_element_for_primitive!(u64);
232impl_vector_element_for_primitive!(usize);
233impl_vector_element_for_primitive!(i8);
234impl_vector_element_for_primitive!(i16);
235impl_vector_element_for_primitive!(i32);
236impl_vector_element_for_primitive!(i64);
237impl_vector_element_for_primitive!(isize);
238impl_vector_element_for_primitive!(f32);
239impl_vector_element_for_primitive!(f64);
David Tolnay47e239d2020-08-28 00:32:04 -0700240
241impl_vector_element!("string", "CxxString", CxxString);