blob: bfb4a4e3766c4151085cfd6dadde723a506e0046 [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 }
Myron Ahneba35cf2020-02-05 19:41:51 +070065}
66
David Tolnay3d88bdc2020-04-24 13:48:18 -070067pub struct Iter<'a, T> {
David Tolnaye90be1d2020-04-24 11:45:57 -070068 v: &'a CxxVector<T>,
Myron Ahneba35cf2020-02-05 19:41:51 +070069 index: usize,
70}
71
David Tolnay4074ad22020-04-24 18:20:11 -070072impl<'a, T> IntoIterator for &'a CxxVector<T>
73where
74 T: VectorElement,
75{
Myron Ahneba35cf2020-02-05 19:41:51 +070076 type Item = &'a T;
David Tolnay3d88bdc2020-04-24 13:48:18 -070077 type IntoIter = Iter<'a, T>;
Myron Ahneba35cf2020-02-05 19:41:51 +070078
79 fn into_iter(self) -> Self::IntoIter {
David Tolnay3d88bdc2020-04-24 13:48:18 -070080 Iter { v: self, index: 0 }
Myron Ahneba35cf2020-02-05 19:41:51 +070081 }
82}
83
David Tolnay4074ad22020-04-24 18:20:11 -070084impl<'a, T> Iterator for Iter<'a, T>
85where
86 T: VectorElement,
87{
Myron Ahneba35cf2020-02-05 19:41:51 +070088 type Item = &'a T;
David Tolnay85db5a02020-04-25 13:17:27 -070089
Myron Ahneba35cf2020-02-05 19:41:51 +070090 fn next(&mut self) -> Option<Self::Item> {
David Tolnay39ee0ed2020-05-05 10:12:29 -070091 let next = self.v.get(self.index);
92 self.index += 1;
93 next
Myron Ahneba35cf2020-02-05 19:41:51 +070094 }
95}
96
David Tolnay3b40b6f2020-04-24 17:58:24 -070097pub struct TypeName<T> {
98 element: PhantomData<T>,
99}
100
101impl<T> TypeName<T> {
102 pub const fn new() -> Self {
103 TypeName {
104 element: PhantomData,
105 }
106 }
107}
108
109impl<T> Display for TypeName<T>
110where
111 T: VectorElement,
112{
113 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
114 write!(formatter, "CxxVector<{}>", T::__NAME)
115 }
116}
117
David Tolnay5104c862020-04-24 13:26:01 -0700118// Methods are private; not intended to be implemented outside of cxxbridge
119// codebase.
David Tolnay1b341192020-04-24 13:04:04 -0700120#[doc(hidden)]
David Tolnayc3ed3a62020-04-24 13:34:50 -0700121pub unsafe trait VectorElement: Sized {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700122 const __NAME: &'static dyn Display;
David Tolnay0e084662020-04-24 14:02:51 -0700123 fn __vector_size(v: &CxxVector<Self>) -> usize;
David Tolnaycc75ad22020-04-24 14:45:16 -0700124 unsafe fn __get_unchecked(v: &CxxVector<Self>, pos: usize) -> &Self;
David Tolnay3b40b6f2020-04-24 17:58:24 -0700125 fn __unique_ptr_null() -> *mut c_void;
126 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void;
127 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self>;
128 unsafe fn __unique_ptr_release(repr: *mut c_void) -> *mut CxxVector<Self>;
129 unsafe fn __unique_ptr_drop(repr: *mut c_void);
David Tolnay1b341192020-04-24 13:04:04 -0700130}
131
David Tolnaye4b6a622020-04-24 14:55:42 -0700132macro_rules! impl_vector_element_for_primitive {
133 ($ty:ident) => {
David Tolnayf0446632020-04-25 11:29:26 -0700134 const_assert_eq!(1, mem::align_of::<CxxVector<$ty>>());
135
David Tolnaye4b6a622020-04-24 14:55:42 -0700136 unsafe impl VectorElement for $ty {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700137 const __NAME: &'static dyn Display = &stringify!($ty);
David Tolnaye4b6a622020-04-24 14:55:42 -0700138 fn __vector_size(v: &CxxVector<$ty>) -> usize {
139 extern "C" {
140 attr! {
David Tolnay69601622020-04-29 18:48:36 -0700141 #[link_name = concat!("cxxbridge03$std$vector$", stringify!($ty), "$size")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700142 fn __vector_size(_: &CxxVector<$ty>) -> usize;
143 }
144 }
145 unsafe { __vector_size(v) }
146 }
147 unsafe fn __get_unchecked(v: &CxxVector<$ty>, pos: usize) -> &$ty {
148 extern "C" {
149 attr! {
David Tolnay69601622020-04-29 18:48:36 -0700150 #[link_name = concat!("cxxbridge03$std$vector$", stringify!($ty), "$get_unchecked")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700151 fn __get_unchecked(_: &CxxVector<$ty>, _: usize) -> *const $ty;
152 }
153 }
154 &*__get_unchecked(v, pos)
155 }
David Tolnay3b40b6f2020-04-24 17:58:24 -0700156 fn __unique_ptr_null() -> *mut c_void {
157 extern "C" {
158 attr! {
David Tolnay69601622020-04-29 18:48:36 -0700159 #[link_name = concat!("cxxbridge03$unique_ptr$std$vector$", stringify!($ty), "$null")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700160 fn __unique_ptr_null(this: *mut *mut c_void);
161 }
162 }
163 let mut repr = ptr::null_mut::<c_void>();
164 unsafe { __unique_ptr_null(&mut repr) }
165 repr
166 }
167 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void {
168 extern "C" {
169 attr! {
David Tolnay69601622020-04-29 18:48:36 -0700170 #[link_name = concat!("cxxbridge03$unique_ptr$std$vector$", stringify!($ty), "$raw")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700171 fn __unique_ptr_raw(this: *mut *mut c_void, raw: *mut CxxVector<$ty>);
172 }
173 }
174 let mut repr = ptr::null_mut::<c_void>();
175 __unique_ptr_raw(&mut repr, raw);
176 repr
177 }
178 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self> {
179 extern "C" {
180 attr! {
David Tolnay69601622020-04-29 18:48:36 -0700181 #[link_name = concat!("cxxbridge03$unique_ptr$std$vector$", stringify!($ty), "$get")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700182 fn __unique_ptr_get(this: *const *mut c_void) -> *const CxxVector<$ty>;
183 }
184 }
185 __unique_ptr_get(&repr)
186 }
187 unsafe fn __unique_ptr_release(mut repr: *mut c_void) -> *mut CxxVector<Self> {
188 extern "C" {
189 attr! {
David Tolnay69601622020-04-29 18:48:36 -0700190 #[link_name = concat!("cxxbridge03$unique_ptr$std$vector$", stringify!($ty), "$release")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700191 fn __unique_ptr_release(this: *mut *mut c_void) -> *mut CxxVector<$ty>;
192 }
193 }
194 __unique_ptr_release(&mut repr)
195 }
196 unsafe fn __unique_ptr_drop(mut repr: *mut c_void) {
197 extern "C" {
198 attr! {
David Tolnay69601622020-04-29 18:48:36 -0700199 #[link_name = concat!("cxxbridge03$unique_ptr$std$vector$", stringify!($ty), "$drop")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700200 fn __unique_ptr_drop(this: *mut *mut c_void);
201 }
202 }
203 __unique_ptr_drop(&mut repr);
204 }
David Tolnaye4b6a622020-04-24 14:55:42 -0700205 }
206 };
207}
208
David Tolnay4b91eaa2020-04-24 14:19:22 -0700209impl_vector_element_for_primitive!(u8);
210impl_vector_element_for_primitive!(u16);
211impl_vector_element_for_primitive!(u32);
212impl_vector_element_for_primitive!(u64);
213impl_vector_element_for_primitive!(usize);
214impl_vector_element_for_primitive!(i8);
215impl_vector_element_for_primitive!(i16);
216impl_vector_element_for_primitive!(i32);
217impl_vector_element_for_primitive!(i64);
218impl_vector_element_for_primitive!(isize);
219impl_vector_element_for_primitive!(f32);
220impl_vector_element_for_primitive!(f64);