ext_php_rs/alloc.rs
1//! Functions relating to the Zend Memory Manager, used to allocate
2//! request-bound memory.
3
4use crate::ffi::{_efree, _emalloc};
5use std::{alloc::Layout, ffi::c_void};
6
7/// Uses the PHP memory allocator to allocate request-bound memory.
8///
9/// # Parameters
10///
11/// * `layout` - The layout of the requested memory.
12///
13/// # Returns
14///
15/// A pointer to the memory allocated.
16pub fn emalloc(layout: Layout) -> *mut u8 {
17 // TODO account for alignment
18 let size = layout.size();
19
20 (unsafe {
21 #[cfg(php_debug)]
22 {
23 _emalloc(size as _, std::ptr::null_mut(), 0, std::ptr::null_mut(), 0)
24 }
25 #[cfg(not(php_debug))]
26 {
27 _emalloc(size as _)
28 }
29 }) as *mut u8
30}
31
32/// Frees a given memory pointer which was allocated through the PHP memory
33/// manager.
34///
35/// # Parameters
36///
37/// * `ptr` - The pointer to the memory to free.
38///
39/// # Safety
40///
41/// Caller must guarantee that the given pointer is valid (aligned and non-null)
42/// and was originally allocated through the Zend memory manager.
43pub unsafe fn efree(ptr: *mut u8) {
44 #[cfg(php_debug)]
45 {
46 _efree(
47 ptr as *mut c_void,
48 std::ptr::null_mut(),
49 0,
50 std::ptr::null_mut(),
51 0,
52 )
53 }
54 #[cfg(not(php_debug))]
55 {
56 _efree(ptr as *mut c_void)
57 }
58}