blob: 4bb5d67b1a08d5902beb7d97e3a80d3cf2579ba8 [file] [log] [blame]
David Tolnay7db73692019-10-20 14:51:12 -04001use crate::cxx_string::CxxString;
David Tolnay3b40b6f2020-04-24 17:58:24 -07002use crate::cxx_vector::{self, CxxVector, VectorElement};
Adrian Taylor9f7ff2e2020-10-12 17:29:25 -07003use crate::ExternType;
4use crate::kind::Trivial;
David Tolnay3384c142020-09-14 00:26:47 -04005use core::ffi::c_void;
6use core::fmt::{self, Debug, Display};
7use core::marker::PhantomData;
8use core::mem;
9use core::ops::{Deref, DerefMut};
10use core::ptr;
David Tolnay7db73692019-10-20 14:51:12 -040011
12/// Binding to C++ `std::unique_ptr<T, std::default_delete<T>>`.
13#[repr(C)]
14pub struct UniquePtr<T>
15where
16 T: UniquePtrTarget,
17{
18 repr: *mut c_void,
19 ty: PhantomData<T>,
20}
21
22impl<T> UniquePtr<T>
23where
24 T: UniquePtrTarget,
25{
26 /// Makes a new UniquePtr wrapping a null pointer.
27 ///
28 /// Matches the behavior of default-constructing a std::unique\_ptr.
29 pub fn null() -> Self {
30 UniquePtr {
31 repr: T::__null(),
32 ty: PhantomData,
33 }
34 }
35
36 /// Allocates memory on the heap and makes a UniquePtr pointing to it.
Adrian Taylor9f7ff2e2020-10-12 17:29:25 -070037 pub fn new(value: T) -> Self
38 where
39 T: ExternType<Kind = Trivial> {
David Tolnay7db73692019-10-20 14:51:12 -040040 UniquePtr {
41 repr: T::__new(value),
42 ty: PhantomData,
43 }
44 }
45
46 /// Checks whether the UniquePtr does not own an object.
47 ///
48 /// This is the opposite of [std::unique_ptr\<T\>::operator bool](https://en.cppreference.com/w/cpp/memory/unique_ptr/operator_bool).
49 pub fn is_null(&self) -> bool {
50 let ptr = unsafe { T::__get(self.repr) };
51 ptr.is_null()
52 }
53
54 /// Returns a reference to the object owned by this UniquePtr if any,
55 /// otherwise None.
56 pub fn as_ref(&self) -> Option<&T> {
57 unsafe { T::__get(self.repr).as_ref() }
58 }
59
David Tolnay1a61b162020-04-09 23:20:05 -070060 /// Returns a mutable reference to the object owned by this UniquePtr if
61 /// any, otherwise None.
62 pub fn as_mut(&mut self) -> Option<&mut T> {
63 unsafe { (T::__get(self.repr) as *mut T).as_mut() }
64 }
65
David Tolnay7db73692019-10-20 14:51:12 -040066 /// Consumes the UniquePtr, releasing its ownership of the heap-allocated T.
67 ///
68 /// Matches the behavior of [std::unique_ptr\<T\>::release](https://en.cppreference.com/w/cpp/memory/unique_ptr/release).
69 pub fn into_raw(self) -> *mut T {
70 let ptr = unsafe { T::__release(self.repr) };
71 mem::forget(self);
72 ptr
73 }
74
75 /// Constructs a UniquePtr retaking ownership of a pointer previously
76 /// obtained from `into_raw`.
77 ///
78 /// # Safety
79 ///
80 /// This function is unsafe because improper use may lead to memory
81 /// problems. For example a double-free may occur if the function is called
82 /// twice on the same raw pointer.
83 pub unsafe fn from_raw(raw: *mut T) -> Self {
84 UniquePtr {
85 repr: T::__raw(raw),
86 ty: PhantomData,
87 }
88 }
89}
90
91unsafe impl<T> Send for UniquePtr<T> where T: Send + UniquePtrTarget {}
92unsafe impl<T> Sync for UniquePtr<T> where T: Sync + UniquePtrTarget {}
93
94impl<T> Drop for UniquePtr<T>
95where
96 T: UniquePtrTarget,
97{
98 fn drop(&mut self) {
99 unsafe { T::__drop(self.repr) }
100 }
101}
102
David Tolnayd20032a2020-04-09 23:21:53 -0700103impl<T> Deref for UniquePtr<T>
104where
105 T: UniquePtrTarget,
106{
107 type Target = T;
108
109 fn deref(&self) -> &Self::Target {
110 match self.as_ref() {
111 Some(target) => target,
David Tolnay9f318a12020-04-09 23:44:02 -0700112 None => panic!("called deref on a null UniquePtr<{}>", T::__NAME),
David Tolnayd20032a2020-04-09 23:21:53 -0700113 }
114 }
115}
116
117impl<T> DerefMut for UniquePtr<T>
118where
119 T: UniquePtrTarget,
120{
121 fn deref_mut(&mut self) -> &mut Self::Target {
122 match self.as_mut() {
123 Some(target) => target,
David Tolnay9f318a12020-04-09 23:44:02 -0700124 None => panic!("called deref_mut on a null UniquePtr<{}>", T::__NAME),
David Tolnayd20032a2020-04-09 23:21:53 -0700125 }
126 }
127}
128
David Tolnay7db73692019-10-20 14:51:12 -0400129impl<T> Debug for UniquePtr<T>
130where
131 T: Debug + UniquePtrTarget,
132{
133 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
134 match self.as_ref() {
135 None => formatter.write_str("nullptr"),
136 Some(value) => Debug::fmt(value, formatter),
137 }
138 }
139}
140
141impl<T> Display for UniquePtr<T>
142where
143 T: Display + UniquePtrTarget,
144{
145 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
146 match self.as_ref() {
147 None => formatter.write_str("nullptr"),
148 Some(value) => Display::fmt(value, formatter),
149 }
150 }
151}
152
153// Methods are private; not intended to be implemented outside of cxxbridge
154// codebase.
155pub unsafe trait UniquePtrTarget {
156 #[doc(hidden)]
David Tolnay3b40b6f2020-04-24 17:58:24 -0700157 const __NAME: &'static dyn Display;
David Tolnayad266772020-04-09 23:42:29 -0700158 #[doc(hidden)]
David Tolnay7db73692019-10-20 14:51:12 -0400159 fn __null() -> *mut c_void;
160 #[doc(hidden)]
David Tolnay53838912020-04-09 20:56:44 -0700161 fn __new(value: Self) -> *mut c_void
162 where
163 Self: Sized,
164 {
165 // Opaque C types do not get this method because they can never exist by
166 // value on the Rust side of the bridge.
167 let _ = value;
168 unreachable!()
169 }
David Tolnay7db73692019-10-20 14:51:12 -0400170 #[doc(hidden)]
171 unsafe fn __raw(raw: *mut Self) -> *mut c_void;
172 #[doc(hidden)]
173 unsafe fn __get(repr: *mut c_void) -> *const Self;
174 #[doc(hidden)]
175 unsafe fn __release(repr: *mut c_void) -> *mut Self;
176 #[doc(hidden)]
177 unsafe fn __drop(repr: *mut c_void);
178}
179
180extern "C" {
David Tolnay8f16ae72020-10-08 18:21:13 -0700181 #[link_name = "cxxbridge05$unique_ptr$std$string$null"]
David Tolnay7db73692019-10-20 14:51:12 -0400182 fn unique_ptr_std_string_null(this: *mut *mut c_void);
David Tolnay8f16ae72020-10-08 18:21:13 -0700183 #[link_name = "cxxbridge05$unique_ptr$std$string$raw"]
David Tolnay7db73692019-10-20 14:51:12 -0400184 fn unique_ptr_std_string_raw(this: *mut *mut c_void, raw: *mut CxxString);
David Tolnay8f16ae72020-10-08 18:21:13 -0700185 #[link_name = "cxxbridge05$unique_ptr$std$string$get"]
David Tolnay7db73692019-10-20 14:51:12 -0400186 fn unique_ptr_std_string_get(this: *const *mut c_void) -> *const CxxString;
David Tolnay8f16ae72020-10-08 18:21:13 -0700187 #[link_name = "cxxbridge05$unique_ptr$std$string$release"]
David Tolnay7db73692019-10-20 14:51:12 -0400188 fn unique_ptr_std_string_release(this: *mut *mut c_void) -> *mut CxxString;
David Tolnay8f16ae72020-10-08 18:21:13 -0700189 #[link_name = "cxxbridge05$unique_ptr$std$string$drop"]
David Tolnay7db73692019-10-20 14:51:12 -0400190 fn unique_ptr_std_string_drop(this: *mut *mut c_void);
191}
192
193unsafe impl UniquePtrTarget for CxxString {
David Tolnay3b40b6f2020-04-24 17:58:24 -0700194 const __NAME: &'static dyn Display = &"CxxString";
David Tolnay7db73692019-10-20 14:51:12 -0400195 fn __null() -> *mut c_void {
196 let mut repr = ptr::null_mut::<c_void>();
David Tolnay2c4b35f2020-10-04 21:22:30 -0700197 unsafe {
198 unique_ptr_std_string_null(&mut repr);
199 }
David Tolnay7db73692019-10-20 14:51:12 -0400200 repr
201 }
David Tolnay7db73692019-10-20 14:51:12 -0400202 unsafe fn __raw(raw: *mut Self) -> *mut c_void {
203 let mut repr = ptr::null_mut::<c_void>();
204 unique_ptr_std_string_raw(&mut repr, raw);
205 repr
206 }
207 unsafe fn __get(repr: *mut c_void) -> *const Self {
208 unique_ptr_std_string_get(&repr)
209 }
210 unsafe fn __release(mut repr: *mut c_void) -> *mut Self {
211 unique_ptr_std_string_release(&mut repr)
212 }
213 unsafe fn __drop(mut repr: *mut c_void) {
214 unique_ptr_std_string_drop(&mut repr);
215 }
216}
David Tolnay3b40b6f2020-04-24 17:58:24 -0700217
218unsafe impl<T> UniquePtrTarget for CxxVector<T>
219where
220 T: VectorElement + 'static,
221{
222 const __NAME: &'static dyn Display = &cxx_vector::TypeName::<T>::new();
223 fn __null() -> *mut c_void {
224 T::__unique_ptr_null()
225 }
226 unsafe fn __raw(raw: *mut Self) -> *mut c_void {
227 T::__unique_ptr_raw(raw)
228 }
229 unsafe fn __get(repr: *mut c_void) -> *const Self {
230 T::__unique_ptr_get(repr)
231 }
232 unsafe fn __release(repr: *mut c_void) -> *mut Self {
233 T::__unique_ptr_release(repr)
234 }
235 unsafe fn __drop(repr: *mut c_void) {
236 T::__unique_ptr_drop(repr);
237 }
238}