|
| 1 | +//! Memory allocation utilities and boxed types for PHP values. |
| 2 | +
|
| 3 | +pub use phper_alloc::{RefClone, ToRefOwned}; |
| 4 | +use std::{ |
| 5 | + borrow::{Borrow, BorrowMut}, |
| 6 | + fmt::{self}, |
| 7 | + mem::ManuallyDrop, |
| 8 | + ops::{Deref, DerefMut}, |
| 9 | +}; |
| 10 | + |
| 11 | +/// A smart pointer for PHP values allocated in the Zend Engine memory. |
| 12 | +/// |
| 13 | +/// `EBox<T>` provides owned access to values allocated in PHP's memory |
| 14 | +/// management system. It automatically handles deallocation when dropped, |
| 15 | +/// ensuring proper cleanup of PHP resources. |
| 16 | +pub struct EBox<T> { |
| 17 | + ptr: *mut T, |
| 18 | +} |
| 19 | + |
| 20 | +impl<T> EBox<T> { |
| 21 | + /// Constructs from a raw pointer. |
| 22 | + /// |
| 23 | + /// # Safety |
| 24 | + /// |
| 25 | + /// Make sure the pointer is from `into_raw`, or created from `emalloc`. |
| 26 | + pub unsafe fn from_raw(raw: *mut T) -> Self { |
| 27 | + Self { ptr: raw } |
| 28 | + } |
| 29 | + |
| 30 | + /// Consumes and returning a wrapped raw pointer. |
| 31 | + /// |
| 32 | + /// Will leak memory. |
| 33 | + pub fn into_raw(b: EBox<T>) -> *mut T { |
| 34 | + ManuallyDrop::new(b).ptr |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +impl<T: fmt::Debug> fmt::Debug for EBox<T> { |
| 39 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 40 | + fmt::Debug::fmt(&**self, f) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +impl<T> Deref for EBox<T> { |
| 45 | + type Target = T; |
| 46 | + |
| 47 | + fn deref(&self) -> &Self::Target { |
| 48 | + unsafe { self.ptr.as_ref().unwrap() } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +impl<T> DerefMut for EBox<T> { |
| 53 | + fn deref_mut(&mut self) -> &mut Self::Target { |
| 54 | + unsafe { self.ptr.as_mut().unwrap() } |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +impl<T> Drop for EBox<T> { |
| 59 | + fn drop(&mut self) { |
| 60 | + unsafe { |
| 61 | + self.ptr.drop_in_place(); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +impl<T> Borrow<T> for EBox<T> { |
| 67 | + fn borrow(&self) -> &T { |
| 68 | + unsafe { self.ptr.as_ref().unwrap() } |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +impl<T> BorrowMut<T> for EBox<T> { |
| 73 | + fn borrow_mut(&mut self) -> &mut T { |
| 74 | + unsafe { self.ptr.as_mut().unwrap() } |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +impl<T> AsRef<T> for EBox<T> { |
| 79 | + fn as_ref(&self) -> &T { |
| 80 | + unsafe { self.ptr.as_ref().unwrap() } |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +impl<T> AsMut<T> for EBox<T> { |
| 85 | + fn as_mut(&mut self) -> &mut T { |
| 86 | + unsafe { self.ptr.as_mut().unwrap() } |
| 87 | + } |
| 88 | +} |
0 commit comments