use crate::cxx_vector::{CxxVector, VectorElement}; use crate::fmt::display; use crate::kind::Trivial; use crate::string::CxxString; use crate::ExternType; use core::ffi::c_void; use core::fmt::{self, Debug, Display}; use core::marker::PhantomData; use core::mem; use core::ops::{Deref, DerefMut}; use core::pin::Pin; use core::ptr; /// Binding to C++ `std::unique_ptr>`. #[repr(C)] pub struct UniquePtr where T: UniquePtrTarget, { repr: *mut c_void, ty: PhantomData, } impl UniquePtr where T: UniquePtrTarget, { /// Makes a new UniquePtr wrapping a null pointer. /// /// Matches the behavior of default-constructing a std::unique\_ptr. pub fn null() -> Self { UniquePtr { repr: T::__null(), ty: PhantomData, } } /// Allocates memory on the heap and makes a UniquePtr pointing to it. pub fn new(value: T) -> Self where T: ExternType, { UniquePtr { repr: T::__new(value), ty: PhantomData, } } /// Checks whether the UniquePtr does not own an object. /// /// This is the opposite of [std::unique_ptr\::operator bool](https://en.cppreference.com/w/cpp/memory/unique_ptr/operator_bool). pub fn is_null(&self) -> bool { let ptr = unsafe { T::__get(self.repr) }; ptr.is_null() } /// Returns a reference to the object owned by this UniquePtr if any, /// otherwise None. pub fn as_ref(&self) -> Option<&T> { unsafe { T::__get(self.repr).as_ref() } } /// Returns a mutable pinned reference to the object owned by this UniquePtr /// if any, otherwise None. pub fn as_mut(&mut self) -> Option> { unsafe { let mut_reference = (T::__get(self.repr) as *mut T).as_mut()?; Some(Pin::new_unchecked(mut_reference)) } } /// Returns a mutable pinned reference to the object owned by this /// UniquePtr. /// /// # Panics /// /// Panics if the UniquePtr holds a null pointer. pub fn pin_mut(&mut self) -> Pin<&mut T> { match self.as_mut() { Some(target) => target, None => panic!( "called pin_mut on a null UniquePtr<{}>", display(T::__typename), ), } } /// Consumes the UniquePtr, releasing its ownership of the heap-allocated T. /// /// Matches the behavior of [std::unique_ptr\::release](https://en.cppreference.com/w/cpp/memory/unique_ptr/release). pub fn into_raw(self) -> *mut T { let ptr = unsafe { T::__release(self.repr) }; mem::forget(self); ptr } /// Constructs a UniquePtr retaking ownership of a pointer previously /// obtained from `into_raw`. /// /// # Safety /// /// This function is unsafe because improper use may lead to memory /// problems. For example a double-free may occur if the function is called /// twice on the same raw pointer. pub unsafe fn from_raw(raw: *mut T) -> Self { UniquePtr { repr: T::__raw(raw), ty: PhantomData, } } } unsafe impl Send for UniquePtr where T: Send + UniquePtrTarget {} unsafe impl Sync for UniquePtr where T: Sync + UniquePtrTarget {} impl Drop for UniquePtr where T: UniquePtrTarget, { fn drop(&mut self) { unsafe { T::__drop(self.repr) } } } impl Deref for UniquePtr where T: UniquePtrTarget, { type Target = T; fn deref(&self) -> &Self::Target { match self.as_ref() { Some(target) => target, None => panic!( "called deref on a null UniquePtr<{}>", display(T::__typename), ), } } } impl DerefMut for UniquePtr where T: UniquePtrTarget + Unpin, { fn deref_mut(&mut self) -> &mut Self::Target { match self.as_mut() { Some(target) => Pin::into_inner(target), None => panic!( "called deref_mut on a null UniquePtr<{}>", display(T::__typename), ), } } } impl Debug for UniquePtr where T: Debug + UniquePtrTarget, { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { match self.as_ref() { None => formatter.write_str("nullptr"), Some(value) => Debug::fmt(value, formatter), } } } impl Display for UniquePtr where T: Display + UniquePtrTarget, { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { match self.as_ref() { None => formatter.write_str("nullptr"), Some(value) => Display::fmt(value, formatter), } } } /// Trait bound for types which may be used as the `T` inside of a /// `UniquePtr` in generic code. /// /// This trait has no publicly callable or implementable methods. Implementing /// it outside of the CXX codebase is not supported. /// /// # Example /// /// A bound `T: UniquePtrTarget` may be necessary when manipulating /// [`UniquePtr`] in generic code. /// /// ``` /// use cxx::memory::{UniquePtr, UniquePtrTarget}; /// use std::fmt::Display; /// /// pub fn take_generic_ptr(ptr: UniquePtr) /// where /// T: UniquePtrTarget + Display, /// { /// println!("the unique_ptr points to: {}", *ptr); /// } /// ``` /// /// Writing the same generic function without a `UniquePtrTarget` trait bound /// would not compile. pub unsafe trait UniquePtrTarget { #[doc(hidden)] fn __typename(f: &mut fmt::Formatter) -> fmt::Result; #[doc(hidden)] fn __null() -> *mut c_void; #[doc(hidden)] fn __new(value: Self) -> *mut c_void where Self: Sized, { // Opaque C types do not get this method because they can never exist by // value on the Rust side of the bridge. let _ = value; unreachable!() } #[doc(hidden)] unsafe fn __raw(raw: *mut Self) -> *mut c_void; #[doc(hidden)] unsafe fn __get(repr: *mut c_void) -> *const Self; #[doc(hidden)] unsafe fn __release(repr: *mut c_void) -> *mut Self; #[doc(hidden)] unsafe fn __drop(repr: *mut c_void); } extern "C" { #[link_name = "cxxbridge1$unique_ptr$std$string$null"] fn unique_ptr_std_string_null(this: *mut *mut c_void); #[link_name = "cxxbridge1$unique_ptr$std$string$raw"] fn unique_ptr_std_string_raw(this: *mut *mut c_void, raw: *mut CxxString); #[link_name = "cxxbridge1$unique_ptr$std$string$get"] fn unique_ptr_std_string_get(this: *const *mut c_void) -> *const CxxString; #[link_name = "cxxbridge1$unique_ptr$std$string$release"] fn unique_ptr_std_string_release(this: *mut *mut c_void) -> *mut CxxString; #[link_name = "cxxbridge1$unique_ptr$std$string$drop"] fn unique_ptr_std_string_drop(this: *mut *mut c_void); } unsafe impl UniquePtrTarget for CxxString { #[doc(hidden)] fn __typename(f: &mut fmt::Formatter) -> fmt::Result { f.write_str("CxxString") } #[doc(hidden)] fn __null() -> *mut c_void { let mut repr = ptr::null_mut::(); unsafe { unique_ptr_std_string_null(&mut repr); } repr } #[doc(hidden)] unsafe fn __raw(raw: *mut Self) -> *mut c_void { let mut repr = ptr::null_mut::(); unique_ptr_std_string_raw(&mut repr, raw); repr } #[doc(hidden)] unsafe fn __get(repr: *mut c_void) -> *const Self { unique_ptr_std_string_get(&repr) } #[doc(hidden)] unsafe fn __release(mut repr: *mut c_void) -> *mut Self { unique_ptr_std_string_release(&mut repr) } #[doc(hidden)] unsafe fn __drop(mut repr: *mut c_void) { unique_ptr_std_string_drop(&mut repr); } } unsafe impl UniquePtrTarget for CxxVector where T: VectorElement, { #[doc(hidden)] fn __typename(f: &mut fmt::Formatter) -> fmt::Result { write!(f, "CxxVector<{}>", display(T::__typename)) } #[doc(hidden)] fn __null() -> *mut c_void { T::__unique_ptr_null() } #[doc(hidden)] unsafe fn __raw(raw: *mut Self) -> *mut c_void { T::__unique_ptr_raw(raw) } #[doc(hidden)] unsafe fn __get(repr: *mut c_void) -> *const Self { T::__unique_ptr_get(repr) } #[doc(hidden)] unsafe fn __release(repr: *mut c_void) -> *mut Self { T::__unique_ptr_release(repr) } #[doc(hidden)] unsafe fn __drop(repr: *mut c_void) { T::__unique_ptr_drop(repr); } }