1use core::fmt;
6use core::marker::PhantomData;
7use core::mem::forget;
8use core::ops::Deref;
9use core::ptr::NonNull;
10
11pub struct Owned<'buf, T: ?Sized> {
16 ptr: NonNull<T>,
17 _phantom: PhantomData<&'buf mut [u8]>,
18}
19
20unsafe impl<T: Send + ?Sized> Send for Owned<'_, T> {}
23
24unsafe impl<T: Sync + ?Sized> Sync for Owned<'_, T> {}
26
27impl<T: ?Sized> Drop for Owned<'_, T> {
28 fn drop(&mut self) {
29 unsafe {
30 self.ptr.as_ptr().drop_in_place();
31 }
32 }
33}
34
35impl<T: ?Sized> Owned<'_, T> {
36 pub unsafe fn new_unchecked(ptr: *mut T) -> Self {
43 Self { ptr: unsafe { NonNull::new_unchecked(ptr) }, _phantom: PhantomData }
44 }
45
46 pub fn into_raw(self) -> *mut T {
48 let result = self.ptr.as_ptr();
49 forget(self);
50 result
51 }
52}
53
54impl<T: ?Sized> Deref for Owned<'_, T> {
55 type Target = T;
56
57 fn deref(&self) -> &Self::Target {
58 unsafe { self.ptr.as_ref() }
59 }
60}
61
62impl<T: fmt::Debug + ?Sized> fmt::Debug for Owned<'_, T> {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 self.deref().fmt(f)
65 }
66}