Skip to main content

value_box/
owned.rs

1use std::any::{Any, type_name};
2use std::mem::ManuallyDrop;
3
4use crate::erased::{from_raw, into_raw};
5use crate::{BoxerError, Result};
6
7#[must_use]
8#[repr(transparent)]
9pub struct OwnedPtr<T: Any> {
10    ptr: *mut T,
11}
12
13impl<T: Any> OwnedPtr<T> {
14    pub fn new(value: T) -> Self {
15        Self {
16            ptr: into_raw(Box::new(value)),
17        }
18    }
19
20    /// # Safety
21    ///
22    /// `ptr` must be uniquely owned, created by `Box::into_raw(Box<T>)` for the
23    /// same `T`, and must not have already been reclaimed.
24    pub const unsafe fn from_raw(ptr: *mut T) -> Self {
25        Self { ptr }
26    }
27
28    pub const fn null() -> Self {
29        Self {
30            ptr: std::ptr::null_mut(),
31        }
32    }
33
34    pub fn is_null(&self) -> bool {
35        self.ptr.is_null()
36    }
37
38    pub fn take_value(self) -> Result<T> {
39        let pointer = self.into_ptr();
40        if pointer.is_null() {
41            return BoxerError::NullPointer(type_name::<T>().to_string()).into();
42        }
43
44        Ok(unsafe { *from_raw(pointer) })
45    }
46    fn into_ptr(self) -> *mut T {
47        let this = ManuallyDrop::new(self);
48        this.ptr
49    }
50}
51
52impl<T: Any> Default for OwnedPtr<T> {
53    fn default() -> Self {
54        Self::null()
55    }
56}
57
58impl<T: Any> From<T> for OwnedPtr<T> {
59    fn from(value: T) -> Self {
60        Self::new(value)
61    }
62}
63
64impl<T: Any> Drop for OwnedPtr<T> {
65    fn drop(&mut self) {
66        if self.ptr.is_null() {
67            return;
68        }
69
70        unsafe {
71            drop(from_raw(self.ptr));
72        }
73    }
74}