blob: f058d5eb62139cec3452fd125ffa8e756e4c0706 [file] [log] [blame]
David Tolnay7db73692019-10-20 14:51:12 -04001use crate::cxx_string::CxxString;
2use std::ffi::c_void;
3use std::fmt::{self, Debug, Display};
4use std::marker::PhantomData;
David Tolnay25b8c8f2020-04-09 21:11:36 -07005use std::mem;
David Tolnay7db73692019-10-20 14:51:12 -04006use std::ptr;
7
8/// Binding to C++ `std::unique_ptr<T, std::default_delete<T>>`.
9#[repr(C)]
10pub struct UniquePtr<T>
11where
12 T: UniquePtrTarget,
13{
14 repr: *mut c_void,
15 ty: PhantomData<T>,
16}
17
18impl<T> UniquePtr<T>
19where
20 T: UniquePtrTarget,
21{
22 /// Makes a new UniquePtr wrapping a null pointer.
23 ///
24 /// Matches the behavior of default-constructing a std::unique\_ptr.
25 pub fn null() -> Self {
26 UniquePtr {
27 repr: T::__null(),
28 ty: PhantomData,
29 }
30 }
31
32 /// Allocates memory on the heap and makes a UniquePtr pointing to it.
33 pub fn new(value: T) -> Self {
34 UniquePtr {
35 repr: T::__new(value),
36 ty: PhantomData,
37 }
38 }
39
40 /// Checks whether the UniquePtr does not own an object.
41 ///
42 /// This is the opposite of [std::unique_ptr\<T\>::operator bool](https://en.cppreference.com/w/cpp/memory/unique_ptr/operator_bool).
43 pub fn is_null(&self) -> bool {
44 let ptr = unsafe { T::__get(self.repr) };
45 ptr.is_null()
46 }
47
48 /// Returns a reference to the object owned by this UniquePtr if any,
49 /// otherwise None.
50 pub fn as_ref(&self) -> Option<&T> {
51 unsafe { T::__get(self.repr).as_ref() }
52 }
53
54 /// Consumes the UniquePtr, releasing its ownership of the heap-allocated T.
55 ///
56 /// Matches the behavior of [std::unique_ptr\<T\>::release](https://en.cppreference.com/w/cpp/memory/unique_ptr/release).
57 pub fn into_raw(self) -> *mut T {
58 let ptr = unsafe { T::__release(self.repr) };
59 mem::forget(self);
60 ptr
61 }
62
63 /// Constructs a UniquePtr retaking ownership of a pointer previously
64 /// obtained from `into_raw`.
65 ///
66 /// # Safety
67 ///
68 /// This function is unsafe because improper use may lead to memory
69 /// problems. For example a double-free may occur if the function is called
70 /// twice on the same raw pointer.
71 pub unsafe fn from_raw(raw: *mut T) -> Self {
72 UniquePtr {
73 repr: T::__raw(raw),
74 ty: PhantomData,
75 }
76 }
77}
78
79unsafe impl<T> Send for UniquePtr<T> where T: Send + UniquePtrTarget {}
80unsafe impl<T> Sync for UniquePtr<T> where T: Sync + UniquePtrTarget {}
81
82impl<T> Drop for UniquePtr<T>
83where
84 T: UniquePtrTarget,
85{
86 fn drop(&mut self) {
87 unsafe { T::__drop(self.repr) }
88 }
89}
90
91impl<T> Debug for UniquePtr<T>
92where
93 T: Debug + UniquePtrTarget,
94{
95 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
96 match self.as_ref() {
97 None => formatter.write_str("nullptr"),
98 Some(value) => Debug::fmt(value, formatter),
99 }
100 }
101}
102
103impl<T> Display for UniquePtr<T>
104where
105 T: Display + UniquePtrTarget,
106{
107 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
108 match self.as_ref() {
109 None => formatter.write_str("nullptr"),
110 Some(value) => Display::fmt(value, formatter),
111 }
112 }
113}
114
115// Methods are private; not intended to be implemented outside of cxxbridge
116// codebase.
117pub unsafe trait UniquePtrTarget {
118 #[doc(hidden)]
119 fn __null() -> *mut c_void;
120 #[doc(hidden)]
David Tolnay53838912020-04-09 20:56:44 -0700121 fn __new(value: Self) -> *mut c_void
122 where
123 Self: Sized,
124 {
125 // Opaque C types do not get this method because they can never exist by
126 // value on the Rust side of the bridge.
127 let _ = value;
128 unreachable!()
129 }
David Tolnay7db73692019-10-20 14:51:12 -0400130 #[doc(hidden)]
131 unsafe fn __raw(raw: *mut Self) -> *mut c_void;
132 #[doc(hidden)]
133 unsafe fn __get(repr: *mut c_void) -> *const Self;
134 #[doc(hidden)]
135 unsafe fn __release(repr: *mut c_void) -> *mut Self;
136 #[doc(hidden)]
137 unsafe fn __drop(repr: *mut c_void);
138}
139
140extern "C" {
David Tolnay8c730492020-03-13 01:29:06 -0700141 #[link_name = "cxxbridge02$unique_ptr$std$string$null"]
David Tolnay7db73692019-10-20 14:51:12 -0400142 fn unique_ptr_std_string_null(this: *mut *mut c_void);
David Tolnay8c730492020-03-13 01:29:06 -0700143 #[link_name = "cxxbridge02$unique_ptr$std$string$raw"]
David Tolnay7db73692019-10-20 14:51:12 -0400144 fn unique_ptr_std_string_raw(this: *mut *mut c_void, raw: *mut CxxString);
David Tolnay8c730492020-03-13 01:29:06 -0700145 #[link_name = "cxxbridge02$unique_ptr$std$string$get"]
David Tolnay7db73692019-10-20 14:51:12 -0400146 fn unique_ptr_std_string_get(this: *const *mut c_void) -> *const CxxString;
David Tolnay8c730492020-03-13 01:29:06 -0700147 #[link_name = "cxxbridge02$unique_ptr$std$string$release"]
David Tolnay7db73692019-10-20 14:51:12 -0400148 fn unique_ptr_std_string_release(this: *mut *mut c_void) -> *mut CxxString;
David Tolnay8c730492020-03-13 01:29:06 -0700149 #[link_name = "cxxbridge02$unique_ptr$std$string$drop"]
David Tolnay7db73692019-10-20 14:51:12 -0400150 fn unique_ptr_std_string_drop(this: *mut *mut c_void);
151}
152
153unsafe impl UniquePtrTarget for CxxString {
154 fn __null() -> *mut c_void {
155 let mut repr = ptr::null_mut::<c_void>();
156 unsafe { unique_ptr_std_string_null(&mut repr) }
157 repr
158 }
David Tolnay7db73692019-10-20 14:51:12 -0400159 unsafe fn __raw(raw: *mut Self) -> *mut c_void {
160 let mut repr = ptr::null_mut::<c_void>();
161 unique_ptr_std_string_raw(&mut repr, raw);
162 repr
163 }
164 unsafe fn __get(repr: *mut c_void) -> *const Self {
165 unique_ptr_std_string_get(&repr)
166 }
167 unsafe fn __release(mut repr: *mut c_void) -> *mut Self {
168 unique_ptr_std_string_release(&mut repr)
169 }
170 unsafe fn __drop(mut repr: *mut c_void) {
171 unique_ptr_std_string_drop(&mut repr);
172 }
173}