blob: 82940445e5a10cf6d21e147027a7c21a15fee6aa [file] [log] [blame]
David Tolnay3b40b6f2020-04-24 17:58:24 -07001use std::ffi::c_void;
2use std::fmt::{self, Display};
3use std::marker::PhantomData;
David Tolnay4f7e6fa2020-04-24 11:52:44 -07004use std::mem;
David Tolnay3b40b6f2020-04-24 17:58:24 -07005use std::ptr;
David Tolnay4f7e6fa2020-04-24 11:52:44 -07006
David Tolnay61a9fdf2020-04-24 16:19:42 -07007/// Binding to C++ `std::vector<T, std::allocator<T>>`.
Myron Ahneba35cf2020-02-05 19:41:51 +07008///
9/// # Invariants
10///
11/// As an invariant of this API and the static analysis of the cxx::bridge
David Tolnay5fe93632020-04-24 12:31:00 -070012/// macro, in Rust code we can never obtain a `CxxVector` by value. Instead in
13/// Rust code we will only ever look at a vector behind a reference or smart
14/// pointer, as in `&CxxVector<T>` or `UniquePtr<CxxVector<T>>`.
David Tolnay4f7e6fa2020-04-24 11:52:44 -070015#[repr(C, packed)]
David Tolnaye90be1d2020-04-24 11:45:57 -070016pub struct CxxVector<T> {
Myron Ahneba35cf2020-02-05 19:41:51 +070017 _private: [T; 0],
18}
19
David Tolnay4074ad22020-04-24 18:20:11 -070020impl<T> CxxVector<T>
21where
22 T: VectorElement,
23{
David Tolnaycdc87962020-04-24 13:45:59 -070024 /// Returns the number of elements in the vector.
David Tolnaydd839192020-04-24 16:41:29 -070025 ///
26 /// Matches the behavior of C++ [std::vector\<T\>::size][size].
27 ///
28 /// [size]: https://en.cppreference.com/w/cpp/container/vector/size
David Tolnayc01d0a02020-04-24 13:30:44 -070029 pub fn len(&self) -> usize {
David Tolnay0e084662020-04-24 14:02:51 -070030 T::__vector_size(self)
Myron Ahneba35cf2020-02-05 19:41:51 +070031 }
32
David Tolnaycdc87962020-04-24 13:45:59 -070033 /// Returns true if the vector contains no elements.
David Tolnaydd839192020-04-24 16:41:29 -070034 ///
35 /// Matches the behavior of C++ [std::vector\<T\>::empty][empty].
36 ///
37 /// [empty]: https://en.cppreference.com/w/cpp/container/vector/empty
Myron Ahneba35cf2020-02-05 19:41:51 +070038 pub fn is_empty(&self) -> bool {
David Tolnayc01d0a02020-04-24 13:30:44 -070039 self.len() == 0
Myron Ahneba35cf2020-02-05 19:41:51 +070040 }
41
David Tolnaycdc87962020-04-24 13:45:59 -070042 /// Returns a reference to an element at the given position, or `None` if
43 /// out of bounds.
Myron Ahneba35cf2020-02-05 19:41:51 +070044 pub fn get(&self, pos: usize) -> Option<&T> {
David Tolnayc01d0a02020-04-24 13:30:44 -070045 if pos < self.len() {
David Tolnay31ad0be2020-04-24 13:29:51 -070046 Some(unsafe { T::__get_unchecked(self, pos) })
Myron Ahneba35cf2020-02-05 19:41:51 +070047 } else {
48 None
49 }
50 }
51
David Tolnay4944f2f2020-04-24 13:46:12 -070052 /// Returns a reference to an element without doing bounds checking.
53 ///
54 /// This is generally not recommended, use with caution! Calling this method
55 /// with an out-of-bounds index is undefined behavior even if the resulting
56 /// reference is not used.
David Tolnaydd839192020-04-24 16:41:29 -070057 ///
58 /// Matches the behavior of C++
59 /// [std::vector\<T\>::operator\[\]][operator_at].
60 ///
61 /// [operator_at]: https://en.cppreference.com/w/cpp/container/vector/operator_at
David Tolnay4944f2f2020-04-24 13:46:12 -070062 pub unsafe fn get_unchecked(&self, pos: usize) -> &T {
63 T::__get_unchecked(self, pos)
64 }
65
David Tolnaycdc87962020-04-24 13:45:59 -070066 /// Appends an element to the back of the vector.
Myron Ahneba35cf2020-02-05 19:41:51 +070067 pub fn push_back(&mut self, item: &T) {
David Tolnay0a63b4c2020-04-24 13:04:26 -070068 T::__push_back(self, item);
Myron Ahneba35cf2020-02-05 19:41:51 +070069 }
70}
71
David Tolnay3d88bdc2020-04-24 13:48:18 -070072pub struct Iter<'a, T> {
David Tolnaye90be1d2020-04-24 11:45:57 -070073 v: &'a CxxVector<T>,
Myron Ahneba35cf2020-02-05 19:41:51 +070074 index: usize,
75}
76
David Tolnay4074ad22020-04-24 18:20:11 -070077impl<'a, T> IntoIterator for &'a CxxVector<T>
78where
79 T: VectorElement,
80{
Myron Ahneba35cf2020-02-05 19:41:51 +070081 type Item = &'a T;
David Tolnay3d88bdc2020-04-24 13:48:18 -070082 type IntoIter = Iter<'a, T>;
Myron Ahneba35cf2020-02-05 19:41:51 +070083
84 fn into_iter(self) -> Self::IntoIter {
David Tolnay3d88bdc2020-04-24 13:48:18 -070085 Iter { v: self, index: 0 }
Myron Ahneba35cf2020-02-05 19:41:51 +070086 }
87}
88
David Tolnay4074ad22020-04-24 18:20:11 -070089impl<'a, T> Iterator for Iter<'a, T>
90where
91 T: VectorElement,
92{
Myron Ahneba35cf2020-02-05 19:41:51 +070093 type Item = &'a T;
David Tolnay85db5a02020-04-25 13:17:27 -070094
Myron Ahneba35cf2020-02-05 19:41:51 +070095 fn next(&mut self) -> Option<Self::Item> {
96 self.index = self.index + 1;
97 self.v.get(self.index - 1)
98 }
99}
100
David Tolnay3b40b6f2020-04-24 17:58:24 -0700101pub struct TypeName<T> {
102 element: PhantomData<T>,
103}
104
105impl<T> TypeName<T> {
106 pub const fn new() -> Self {
107 TypeName {
108 element: PhantomData,
109 }
110 }
111}
112
113impl<T> Display for TypeName<T>
114where
115 T: VectorElement,
116{
117 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
118 write!(formatter, "CxxVector<{}>", T::__NAME)
119 }
120}
121
David Tolnay5104c862020-04-24 13:26:01 -0700122// Methods are private; not intended to be implemented outside of cxxbridge
123// codebase.
David Tolnay1b341192020-04-24 13:04:04 -0700124#[doc(hidden)]
David Tolnayc3ed3a62020-04-24 13:34:50 -0700125pub unsafe trait VectorElement: Sized {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700126 const __NAME: &'static dyn Display;
David Tolnay0e084662020-04-24 14:02:51 -0700127 fn __vector_size(v: &CxxVector<Self>) -> usize;
David Tolnaycc75ad22020-04-24 14:45:16 -0700128 unsafe fn __get_unchecked(v: &CxxVector<Self>, pos: usize) -> &Self;
David Tolnayc3ed3a62020-04-24 13:34:50 -0700129 fn __push_back(v: &CxxVector<Self>, item: &Self);
David Tolnay3b40b6f2020-04-24 17:58:24 -0700130 fn __unique_ptr_null() -> *mut c_void;
131 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void;
132 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self>;
133 unsafe fn __unique_ptr_release(repr: *mut c_void) -> *mut CxxVector<Self>;
134 unsafe fn __unique_ptr_drop(repr: *mut c_void);
David Tolnay1b341192020-04-24 13:04:04 -0700135}
136
David Tolnaye4b6a622020-04-24 14:55:42 -0700137macro_rules! impl_vector_element_for_primitive {
138 ($ty:ident) => {
David Tolnayf0446632020-04-25 11:29:26 -0700139 const_assert_eq!(1, mem::align_of::<CxxVector<$ty>>());
140
David Tolnaye4b6a622020-04-24 14:55:42 -0700141 unsafe impl VectorElement for $ty {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700142 const __NAME: &'static dyn Display = &stringify!($ty);
David Tolnaye4b6a622020-04-24 14:55:42 -0700143 fn __vector_size(v: &CxxVector<$ty>) -> usize {
144 extern "C" {
145 attr! {
146 #[link_name = concat!("cxxbridge02$std$vector$", stringify!($ty), "$size")]
147 fn __vector_size(_: &CxxVector<$ty>) -> usize;
148 }
149 }
150 unsafe { __vector_size(v) }
151 }
152 unsafe fn __get_unchecked(v: &CxxVector<$ty>, pos: usize) -> &$ty {
153 extern "C" {
154 attr! {
155 #[link_name = concat!("cxxbridge02$std$vector$", stringify!($ty), "$get_unchecked")]
156 fn __get_unchecked(_: &CxxVector<$ty>, _: usize) -> *const $ty;
157 }
158 }
159 &*__get_unchecked(v, pos)
160 }
161 fn __push_back(v: &CxxVector<$ty>, item: &$ty) {
162 extern "C" {
163 attr! {
164 #[link_name = concat!("cxxbridge02$std$vector$", stringify!($ty), "$push_back")]
165 fn __push_back(_: &CxxVector<$ty>, _: &$ty);
166 }
167 }
168 unsafe { __push_back(v, item) }
169 }
David Tolnay3b40b6f2020-04-24 17:58:24 -0700170 fn __unique_ptr_null() -> *mut c_void {
171 extern "C" {
172 attr! {
173 #[link_name = concat!("cxxbridge02$unique_ptr$std$vector$", stringify!($ty), "$null")]
174 fn __unique_ptr_null(this: *mut *mut c_void);
175 }
176 }
177 let mut repr = ptr::null_mut::<c_void>();
178 unsafe { __unique_ptr_null(&mut repr) }
179 repr
180 }
181 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void {
182 extern "C" {
183 attr! {
184 #[link_name = concat!("cxxbridge02$unique_ptr$std$vector$", stringify!($ty), "$raw")]
185 fn __unique_ptr_raw(this: *mut *mut c_void, raw: *mut CxxVector<$ty>);
186 }
187 }
188 let mut repr = ptr::null_mut::<c_void>();
189 __unique_ptr_raw(&mut repr, raw);
190 repr
191 }
192 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self> {
193 extern "C" {
194 attr! {
195 #[link_name = concat!("cxxbridge02$unique_ptr$std$vector$", stringify!($ty), "$get")]
196 fn __unique_ptr_get(this: *const *mut c_void) -> *const CxxVector<$ty>;
197 }
198 }
199 __unique_ptr_get(&repr)
200 }
201 unsafe fn __unique_ptr_release(mut repr: *mut c_void) -> *mut CxxVector<Self> {
202 extern "C" {
203 attr! {
204 #[link_name = concat!("cxxbridge02$unique_ptr$std$vector$", stringify!($ty), "$release")]
205 fn __unique_ptr_release(this: *mut *mut c_void) -> *mut CxxVector<$ty>;
206 }
207 }
208 __unique_ptr_release(&mut repr)
209 }
210 unsafe fn __unique_ptr_drop(mut repr: *mut c_void) {
211 extern "C" {
212 attr! {
213 #[link_name = concat!("cxxbridge02$unique_ptr$std$vector$", stringify!($ty), "$drop")]
214 fn __unique_ptr_drop(this: *mut *mut c_void);
215 }
216 }
217 __unique_ptr_drop(&mut repr);
218 }
David Tolnaye4b6a622020-04-24 14:55:42 -0700219 }
220 };
221}
222
David Tolnay4b91eaa2020-04-24 14:19:22 -0700223impl_vector_element_for_primitive!(u8);
224impl_vector_element_for_primitive!(u16);
225impl_vector_element_for_primitive!(u32);
226impl_vector_element_for_primitive!(u64);
227impl_vector_element_for_primitive!(usize);
228impl_vector_element_for_primitive!(i8);
229impl_vector_element_for_primitive!(i16);
230impl_vector_element_for_primitive!(i32);
231impl_vector_element_for_primitive!(i64);
232impl_vector_element_for_primitive!(isize);
233impl_vector_element_for_primitive!(f32);
234impl_vector_element_for_primitive!(f64);