blob: 94b6e251f3e6d1f4f40c3fc5f58960c62518aa17 [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;
5use std::mem::{self, MaybeUninit};
6use 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)]
121 fn __new(value: Self) -> *mut c_void;
122 #[doc(hidden)]
123 unsafe fn __raw(raw: *mut Self) -> *mut c_void;
124 #[doc(hidden)]
125 unsafe fn __get(repr: *mut c_void) -> *const Self;
126 #[doc(hidden)]
127 unsafe fn __release(repr: *mut c_void) -> *mut Self;
128 #[doc(hidden)]
129 unsafe fn __drop(repr: *mut c_void);
130}
131
132extern "C" {
David Tolnay8c730492020-03-13 01:29:06 -0700133 #[link_name = "cxxbridge02$unique_ptr$std$string$null"]
David Tolnay7db73692019-10-20 14:51:12 -0400134 fn unique_ptr_std_string_null(this: *mut *mut c_void);
David Tolnay8c730492020-03-13 01:29:06 -0700135 #[link_name = "cxxbridge02$unique_ptr$std$string$new"]
David Tolnay7db73692019-10-20 14:51:12 -0400136 fn unique_ptr_std_string_new(this: *mut *mut c_void, value: *mut CxxString);
David Tolnay8c730492020-03-13 01:29:06 -0700137 #[link_name = "cxxbridge02$unique_ptr$std$string$raw"]
David Tolnay7db73692019-10-20 14:51:12 -0400138 fn unique_ptr_std_string_raw(this: *mut *mut c_void, raw: *mut CxxString);
David Tolnay8c730492020-03-13 01:29:06 -0700139 #[link_name = "cxxbridge02$unique_ptr$std$string$get"]
David Tolnay7db73692019-10-20 14:51:12 -0400140 fn unique_ptr_std_string_get(this: *const *mut c_void) -> *const CxxString;
David Tolnay8c730492020-03-13 01:29:06 -0700141 #[link_name = "cxxbridge02$unique_ptr$std$string$release"]
David Tolnay7db73692019-10-20 14:51:12 -0400142 fn unique_ptr_std_string_release(this: *mut *mut c_void) -> *mut CxxString;
David Tolnay8c730492020-03-13 01:29:06 -0700143 #[link_name = "cxxbridge02$unique_ptr$std$string$drop"]
David Tolnay7db73692019-10-20 14:51:12 -0400144 fn unique_ptr_std_string_drop(this: *mut *mut c_void);
145}
146
147unsafe impl UniquePtrTarget for CxxString {
148 fn __null() -> *mut c_void {
149 let mut repr = ptr::null_mut::<c_void>();
150 unsafe { unique_ptr_std_string_null(&mut repr) }
151 repr
152 }
153 fn __new(value: Self) -> *mut c_void {
154 let mut repr = ptr::null_mut::<c_void>();
155 let mut value = MaybeUninit::new(value);
156 unsafe { unique_ptr_std_string_new(&mut repr, value.as_mut_ptr() as *mut Self) }
157 repr
158 }
159 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}