Skip to content

Migration of ZString, ZArray, ZObject to EBox #208

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
/.cargo
/vendor
core
compile_commands.json
2 changes: 2 additions & 0 deletions examples/http-server/tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
// See the Mulan PSL v2 for more details.

use axum::http::header::CONTENT_TYPE;
use hyper::StatusCode;
use phper_test::{cli::test_long_term_php_script_with_condition, utils::get_lib_path};
use reqwest::blocking::Client;
use std::{
Expand Down Expand Up @@ -39,6 +40,7 @@ fn test_php() {
let client = Client::new();
for _ in 0..5 {
let response = client.get("http://127.0.0.1:9000/").send().unwrap();
assert_eq!(response.status(), StatusCode::OK);
let content_type = response.headers().get(CONTENT_TYPE).unwrap();
assert_eq!(content_type, "text/plain");
let body = response.text().unwrap();
Expand Down
80 changes: 1 addition & 79 deletions phper-alloc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,85 +12,7 @@
#![warn(clippy::dbg_macro, clippy::print_stdout)]
#![doc = include_str!("../README.md")]

#[macro_use]
mod macros;

use phper_sys::*;
use std::{
borrow::Borrow,
mem::{ManuallyDrop, size_of},
ops::{Deref, DerefMut},
};

/// The Box which use php `emalloc` and `efree` to manage memory.
///
/// TODO Now feature `allocator_api` is still unstable, implement myself, use
/// Box<T, Alloc> later.
pub struct EBox<T> {
ptr: *mut T,
}

impl<T> EBox<T> {
/// Allocates heap memory using `emalloc` then places `x` into it.
///
/// # Panic
///
/// Panic if `size_of::<T>()` equals zero.
#[allow(clippy::useless_conversion)]
pub fn new(x: T) -> Self {
unsafe {
assert_ne!(size_of::<T>(), 0);
let ptr: *mut T = phper_emalloc(size_of::<T>().try_into().unwrap()).cast();
// TODO Deal with ptr is zero, when memory limit is reached.
ptr.write(x);
Self { ptr }
}
}

/// Constructs from a raw pointer.
///
/// # Safety
///
/// Make sure the pointer is from `into_raw`, or created from `emalloc`.
pub unsafe fn from_raw(raw: *mut T) -> Self {
Self { ptr: raw }
}

/// Consumes and returning a wrapped raw pointer.
///
/// Will leak memory.
pub fn into_raw(b: EBox<T>) -> *mut T {
ManuallyDrop::new(b).ptr
}

/// Consumes the `EBox`, returning the wrapped value.
pub fn into_inner(self) -> T {
unsafe { self.ptr.read() }
}
}

impl<T> Deref for EBox<T> {
type Target = T;

fn deref(&self) -> &Self::Target {
unsafe { self.ptr.as_ref().unwrap() }
}
}

impl<T> DerefMut for EBox<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { self.ptr.as_mut().unwrap() }
}
}

impl<T> Drop for EBox<T> {
fn drop(&mut self) {
unsafe {
self.ptr.drop_in_place();
phper_efree(self.ptr.cast());
}
}
}
use std::borrow::Borrow;

/// Duplicate an object without deep copy, but to only add the refcount, for php
/// refcount struct.
Expand Down
21 changes: 0 additions & 21 deletions phper-alloc/src/macros.rs

This file was deleted.

2 changes: 1 addition & 1 deletion phper-doc/doc/_05_internal_types/_01_z_str/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use phper::strings::ZString;
let s = ZString::new("Hello world!");
// Will leak memory.
let ptr = s.into_raw();
let ptr = ZString::into_raw(s);
// retake pointer.
let ss = unsafe { ZString::from_raw(ptr) };
Expand Down
1 change: 0 additions & 1 deletion phper-test/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ impl Context {
ContextCommand { cmd, args }
}

#[cfg_attr(docsrs, doc(cfg(feature = "fpm")))]
pub fn find_php_fpm(&self) -> Option<String> {
use std::ffi::OsStr;

Expand Down
2 changes: 1 addition & 1 deletion phper-test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

#![warn(rust_2018_idioms, missing_docs)]
#![warn(clippy::dbg_macro, clippy::print_stdout)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![doc = include_str!("../README.md")]

pub mod cli;
Expand Down
98 changes: 98 additions & 0 deletions phper/src/alloc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// Copyright (c) 2025 PHPER Framework Team
// PHPER is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan
// PSL v2. You may obtain a copy of Mulan PSL v2 at:
// http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.

//! Memory allocation utilities and boxed types for PHP values.
pub use phper_alloc::{RefClone, ToRefOwned};
use std::{
borrow::{Borrow, BorrowMut},
fmt::{self},
mem::ManuallyDrop,
ops::{Deref, DerefMut},
};

/// A smart pointer for PHP values allocated in the Zend Engine memory.
///
/// `EBox<T>` provides owned access to values allocated in PHP's memory
/// management system. It automatically handles deallocation when dropped,
/// ensuring proper cleanup of PHP resources.
pub struct EBox<T> {
ptr: *mut T,
}

impl<T> EBox<T> {
/// Constructs from a raw pointer.
///
/// # Safety
///
/// Make sure the pointer is from `into_raw`, or created from `emalloc`.
pub unsafe fn from_raw(raw: *mut T) -> Self {
Self { ptr: raw }
}

/// Consumes and returning a wrapped raw pointer.
///
/// Will leak memory.
pub fn into_raw(b: EBox<T>) -> *mut T {
ManuallyDrop::new(b).ptr
}
}

impl<T: fmt::Debug> fmt::Debug for EBox<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}

impl<T> Deref for EBox<T> {
type Target = T;

fn deref(&self) -> &Self::Target {
unsafe { self.ptr.as_ref().unwrap() }
}
}

impl<T> DerefMut for EBox<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { self.ptr.as_mut().unwrap() }
}
}

impl<T> Drop for EBox<T> {
fn drop(&mut self) {
unsafe {
self.ptr.drop_in_place();
}
}
}

impl<T> Borrow<T> for EBox<T> {
fn borrow(&self) -> &T {
unsafe { self.ptr.as_ref().unwrap() }
}
}

impl<T> BorrowMut<T> for EBox<T> {
fn borrow_mut(&mut self) -> &mut T {
unsafe { self.ptr.as_mut().unwrap() }
}
}

impl<T> AsRef<T> for EBox<T> {
fn as_ref(&self) -> &T {
unsafe { self.ptr.as_ref().unwrap() }
}
}

impl<T> AsMut<T> for EBox<T> {
fn as_mut(&mut self) -> &mut T {
unsafe { self.ptr.as_mut().unwrap() }
}
}
Loading
Loading