blob: d9e8892f10300457058106b6d32ee5d7ed7666f1 [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) => {
139 unsafe impl VectorElement for $ty {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700140 const __NAME: &'static dyn Display = &stringify!($ty);
David Tolnaye4b6a622020-04-24 14:55:42 -0700141 fn __vector_size(v: &CxxVector<$ty>) -> usize {
142 extern "C" {
143 attr! {
144 #[link_name = concat!("cxxbridge02$std$vector$", stringify!($ty), "$size")]
145 fn __vector_size(_: &CxxVector<$ty>) -> usize;
146 }
147 }
148 unsafe { __vector_size(v) }
149 }
150 unsafe fn __get_unchecked(v: &CxxVector<$ty>, pos: usize) -> &$ty {
151 extern "C" {
152 attr! {
153 #[link_name = concat!("cxxbridge02$std$vector$", stringify!($ty), "$get_unchecked")]
154 fn __get_unchecked(_: &CxxVector<$ty>, _: usize) -> *const $ty;
155 }
156 }
157 &*__get_unchecked(v, pos)
158 }
159 fn __push_back(v: &CxxVector<$ty>, item: &$ty) {
160 extern "C" {
161 attr! {
162 #[link_name = concat!("cxxbridge02$std$vector$", stringify!($ty), "$push_back")]
163 fn __push_back(_: &CxxVector<$ty>, _: &$ty);
164 }
165 }
166 unsafe { __push_back(v, item) }
167 }
David Tolnay3b40b6f2020-04-24 17:58:24 -0700168 fn __unique_ptr_null() -> *mut c_void {
169 extern "C" {
170 attr! {
171 #[link_name = concat!("cxxbridge02$unique_ptr$std$vector$", stringify!($ty), "$null")]
172 fn __unique_ptr_null(this: *mut *mut c_void);
173 }
174 }
175 let mut repr = ptr::null_mut::<c_void>();
176 unsafe { __unique_ptr_null(&mut repr) }
177 repr
178 }
179 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void {
180 extern "C" {
181 attr! {
182 #[link_name = concat!("cxxbridge02$unique_ptr$std$vector$", stringify!($ty), "$raw")]
183 fn __unique_ptr_raw(this: *mut *mut c_void, raw: *mut CxxVector<$ty>);
184 }
185 }
186 let mut repr = ptr::null_mut::<c_void>();
187 __unique_ptr_raw(&mut repr, raw);
188 repr
189 }
190 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self> {
191 extern "C" {
192 attr! {
193 #[link_name = concat!("cxxbridge02$unique_ptr$std$vector$", stringify!($ty), "$get")]
194 fn __unique_ptr_get(this: *const *mut c_void) -> *const CxxVector<$ty>;
195 }
196 }
197 __unique_ptr_get(&repr)
198 }
199 unsafe fn __unique_ptr_release(mut repr: *mut c_void) -> *mut CxxVector<Self> {
200 extern "C" {
201 attr! {
202 #[link_name = concat!("cxxbridge02$unique_ptr$std$vector$", stringify!($ty), "$release")]
203 fn __unique_ptr_release(this: *mut *mut c_void) -> *mut CxxVector<$ty>;
204 }
205 }
206 __unique_ptr_release(&mut repr)
207 }
208 unsafe fn __unique_ptr_drop(mut repr: *mut c_void) {
209 extern "C" {
210 attr! {
211 #[link_name = concat!("cxxbridge02$unique_ptr$std$vector$", stringify!($ty), "$drop")]
212 fn __unique_ptr_drop(this: *mut *mut c_void);
213 }
214 }
215 __unique_ptr_drop(&mut repr);
216 }
David Tolnaye4b6a622020-04-24 14:55:42 -0700217 }
218 };
219}
220
David Tolnay4b91eaa2020-04-24 14:19:22 -0700221impl_vector_element_for_primitive!(u8);
222impl_vector_element_for_primitive!(u16);
223impl_vector_element_for_primitive!(u32);
224impl_vector_element_for_primitive!(u64);
225impl_vector_element_for_primitive!(usize);
226impl_vector_element_for_primitive!(i8);
227impl_vector_element_for_primitive!(i16);
228impl_vector_element_for_primitive!(i32);
229impl_vector_element_for_primitive!(i64);
230impl_vector_element_for_primitive!(isize);
231impl_vector_element_for_primitive!(f32);
232impl_vector_element_for_primitive!(f64);
David Tolnay4f7e6fa2020-04-24 11:52:44 -0700233
234const_assert_eq!(1, mem::align_of::<CxxVector<usize>>());