blob: 5fb08071b2465b43e16f3e0832e734885af16ec6 [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 {
David Tolnaya5a14ce2020-09-24 16:02:40 -040072 // The slice::from_raw_parts in the other branch requires a nonnull
73 // and properly aligned data ptr. C++ standard does not guarantee
74 // that data() on a vector with size 0 would return a nonnull
75 // pointer or sufficiently aligned pointer, so using it would be
76 // undefined behavior. Create our own empty slice in Rust instead
77 // which upholds the invariants.
David Tolnayacc7fb02020-09-24 18:10:09 -040078 &[]
David Tolnay93637ca2020-09-24 15:58:20 -040079 } else {
80 let ptr = unsafe { T::__get_unchecked(self, 0) };
81 unsafe { slice::from_raw_parts(ptr, len) }
82 }
David Tolnay4944f2f2020-04-24 13:46:12 -070083 }
Myron Ahneba35cf2020-02-05 19:41:51 +070084}
85
David Tolnay3d88bdc2020-04-24 13:48:18 -070086pub struct Iter<'a, T> {
David Tolnaye90be1d2020-04-24 11:45:57 -070087 v: &'a CxxVector<T>,
Myron Ahneba35cf2020-02-05 19:41:51 +070088 index: usize,
89}
90
David Tolnay4074ad22020-04-24 18:20:11 -070091impl<'a, T> IntoIterator for &'a CxxVector<T>
92where
93 T: VectorElement,
94{
Myron Ahneba35cf2020-02-05 19:41:51 +070095 type Item = &'a T;
David Tolnay3d88bdc2020-04-24 13:48:18 -070096 type IntoIter = Iter<'a, T>;
Myron Ahneba35cf2020-02-05 19:41:51 +070097
98 fn into_iter(self) -> Self::IntoIter {
David Tolnay3d88bdc2020-04-24 13:48:18 -070099 Iter { v: self, index: 0 }
Myron Ahneba35cf2020-02-05 19:41:51 +0700100 }
101}
102
David Tolnay4074ad22020-04-24 18:20:11 -0700103impl<'a, T> Iterator for Iter<'a, T>
104where
105 T: VectorElement,
106{
Myron Ahneba35cf2020-02-05 19:41:51 +0700107 type Item = &'a T;
David Tolnay85db5a02020-04-25 13:17:27 -0700108
Myron Ahneba35cf2020-02-05 19:41:51 +0700109 fn next(&mut self) -> Option<Self::Item> {
David Tolnay39ee0ed2020-05-05 10:12:29 -0700110 let next = self.v.get(self.index);
111 self.index += 1;
112 next
Myron Ahneba35cf2020-02-05 19:41:51 +0700113 }
114}
115
David Tolnay3b40b6f2020-04-24 17:58:24 -0700116pub struct TypeName<T> {
117 element: PhantomData<T>,
118}
119
120impl<T> TypeName<T> {
121 pub const fn new() -> Self {
122 TypeName {
123 element: PhantomData,
124 }
125 }
126}
127
128impl<T> Display for TypeName<T>
129where
130 T: VectorElement,
131{
132 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
133 write!(formatter, "CxxVector<{}>", T::__NAME)
134 }
135}
136
David Tolnay5104c862020-04-24 13:26:01 -0700137// Methods are private; not intended to be implemented outside of cxxbridge
138// codebase.
David Tolnay1b341192020-04-24 13:04:04 -0700139#[doc(hidden)]
David Tolnayc3ed3a62020-04-24 13:34:50 -0700140pub unsafe trait VectorElement: Sized {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700141 const __NAME: &'static dyn Display;
David Tolnay0e084662020-04-24 14:02:51 -0700142 fn __vector_size(v: &CxxVector<Self>) -> usize;
David Tolnay93637ca2020-09-24 15:58:20 -0400143 unsafe fn __get_unchecked(v: &CxxVector<Self>, pos: usize) -> *const Self;
David Tolnay3b40b6f2020-04-24 17:58:24 -0700144 fn __unique_ptr_null() -> *mut c_void;
145 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void;
146 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self>;
147 unsafe fn __unique_ptr_release(repr: *mut c_void) -> *mut CxxVector<Self>;
148 unsafe fn __unique_ptr_drop(repr: *mut c_void);
David Tolnay1b341192020-04-24 13:04:04 -0700149}
150
David Tolnay47e239d2020-08-28 00:32:04 -0700151macro_rules! impl_vector_element {
152 ($segment:expr, $name:expr, $ty:ty) => {
David Tolnayf0446632020-04-25 11:29:26 -0700153 const_assert_eq!(1, mem::align_of::<CxxVector<$ty>>());
154
David Tolnaye4b6a622020-04-24 14:55:42 -0700155 unsafe impl VectorElement for $ty {
David Tolnay47e239d2020-08-28 00:32:04 -0700156 const __NAME: &'static dyn Display = &$name;
David Tolnaye4b6a622020-04-24 14:55:42 -0700157 fn __vector_size(v: &CxxVector<$ty>) -> usize {
158 extern "C" {
159 attr! {
David Tolnay8f16ae72020-10-08 18:21:13 -0700160 #[link_name = concat!("cxxbridge05$std$vector$", $segment, "$size")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700161 fn __vector_size(_: &CxxVector<$ty>) -> usize;
162 }
163 }
164 unsafe { __vector_size(v) }
165 }
David Tolnay93637ca2020-09-24 15:58:20 -0400166 unsafe fn __get_unchecked(v: &CxxVector<$ty>, pos: usize) -> *const $ty {
David Tolnaye4b6a622020-04-24 14:55:42 -0700167 extern "C" {
168 attr! {
David Tolnay8f16ae72020-10-08 18:21:13 -0700169 #[link_name = concat!("cxxbridge05$std$vector$", $segment, "$get_unchecked")]
David Tolnaye4b6a622020-04-24 14:55:42 -0700170 fn __get_unchecked(_: &CxxVector<$ty>, _: usize) -> *const $ty;
171 }
172 }
David Tolnay93637ca2020-09-24 15:58:20 -0400173 __get_unchecked(v, pos)
David Tolnaye4b6a622020-04-24 14:55:42 -0700174 }
David Tolnay3b40b6f2020-04-24 17:58:24 -0700175 fn __unique_ptr_null() -> *mut c_void {
176 extern "C" {
177 attr! {
David Tolnay8f16ae72020-10-08 18:21:13 -0700178 #[link_name = concat!("cxxbridge05$unique_ptr$std$vector$", $segment, "$null")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700179 fn __unique_ptr_null(this: *mut *mut c_void);
180 }
181 }
182 let mut repr = ptr::null_mut::<c_void>();
183 unsafe { __unique_ptr_null(&mut repr) }
184 repr
185 }
186 unsafe fn __unique_ptr_raw(raw: *mut CxxVector<Self>) -> *mut c_void {
187 extern "C" {
188 attr! {
David Tolnay8f16ae72020-10-08 18:21:13 -0700189 #[link_name = concat!("cxxbridge05$unique_ptr$std$vector$", $segment, "$raw")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700190 fn __unique_ptr_raw(this: *mut *mut c_void, raw: *mut CxxVector<$ty>);
191 }
192 }
193 let mut repr = ptr::null_mut::<c_void>();
194 __unique_ptr_raw(&mut repr, raw);
195 repr
196 }
197 unsafe fn __unique_ptr_get(repr: *mut c_void) -> *const CxxVector<Self> {
198 extern "C" {
199 attr! {
David Tolnay8f16ae72020-10-08 18:21:13 -0700200 #[link_name = concat!("cxxbridge05$unique_ptr$std$vector$", $segment, "$get")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700201 fn __unique_ptr_get(this: *const *mut c_void) -> *const CxxVector<$ty>;
202 }
203 }
204 __unique_ptr_get(&repr)
205 }
206 unsafe fn __unique_ptr_release(mut repr: *mut c_void) -> *mut CxxVector<Self> {
207 extern "C" {
208 attr! {
David Tolnay8f16ae72020-10-08 18:21:13 -0700209 #[link_name = concat!("cxxbridge05$unique_ptr$std$vector$", $segment, "$release")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700210 fn __unique_ptr_release(this: *mut *mut c_void) -> *mut CxxVector<$ty>;
211 }
212 }
213 __unique_ptr_release(&mut repr)
214 }
215 unsafe fn __unique_ptr_drop(mut repr: *mut c_void) {
216 extern "C" {
217 attr! {
David Tolnay8f16ae72020-10-08 18:21:13 -0700218 #[link_name = concat!("cxxbridge05$unique_ptr$std$vector$", $segment, "$drop")]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700219 fn __unique_ptr_drop(this: *mut *mut c_void);
220 }
221 }
222 __unique_ptr_drop(&mut repr);
223 }
David Tolnaye4b6a622020-04-24 14:55:42 -0700224 }
225 };
226}
227
David Tolnay47e239d2020-08-28 00:32:04 -0700228macro_rules! impl_vector_element_for_primitive {
229 ($ty:ident) => {
230 impl_vector_element!(stringify!($ty), stringify!($ty), $ty);
231 };
232}
233
David Tolnay4b91eaa2020-04-24 14:19:22 -0700234impl_vector_element_for_primitive!(u8);
235impl_vector_element_for_primitive!(u16);
236impl_vector_element_for_primitive!(u32);
237impl_vector_element_for_primitive!(u64);
238impl_vector_element_for_primitive!(usize);
239impl_vector_element_for_primitive!(i8);
240impl_vector_element_for_primitive!(i16);
241impl_vector_element_for_primitive!(i32);
242impl_vector_element_for_primitive!(i64);
243impl_vector_element_for_primitive!(isize);
244impl_vector_element_for_primitive!(f32);
245impl_vector_element_for_primitive!(f64);
David Tolnay47e239d2020-08-28 00:32:04 -0700246
247impl_vector_element!("string", "CxxString", CxxString);