Skip to content

Add constant, and replace ToString with Into. #52

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 4 commits into from
Sep 23, 2022
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
2 changes: 1 addition & 1 deletion examples/http-client/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub fn make_response_class() -> StatefulClass<Option<Response>> {
.ok_or(HttpClientError::ResponseHadRead)
.and_then(|response| response.bytes().map_err(Into::into))
})?;
Ok::<_, HttpClientError>((&body).to_vec())
Ok::<_, HttpClientError>(body.to_vec())
},
vec![],
);
Expand Down
22 changes: 11 additions & 11 deletions phper/src/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,23 +57,23 @@ pub struct StatefulClass<T: Send + 'static> {
}

impl StatefulClass<()> {
pub fn new(class_name: impl ToString) -> Self {
pub fn new(class_name: impl Into<String>) -> Self {
Self::new_with_state_constructor(class_name, || ())
}
}

impl<T: Default + Send + 'static> StatefulClass<T> {
pub fn new_with_default_state(class_name: impl ToString) -> Self {
pub fn new_with_default_state(class_name: impl Into<String>) -> Self {
Self::new_with_state_constructor(class_name, Default::default)
}
}

impl<T: Send + 'static> StatefulClass<T> {
pub fn new_with_state_constructor(
class_name: impl ToString, state_constructor: impl Fn() -> T + Send + Sync + 'static,
class_name: impl Into<String>, state_constructor: impl Fn() -> T + Send + Sync + 'static,
) -> Self {
Self {
class_name: class_name.to_string(),
class_name: class_name.into(),
state_constructor: Arc::new(state_constructor),
method_entities: Vec::new(),
property_entities: Vec::new(),
Expand All @@ -86,7 +86,7 @@ impl<T: Send + 'static> StatefulClass<T> {
}

pub fn add_method<F, R>(
&mut self, name: impl ToString, vis: Visibility, handler: F, arguments: Vec<Argument>,
&mut self, name: impl Into<String>, vis: Visibility, handler: F, arguments: Vec<Argument>,
) where
F: Fn(&mut StatefulObj<T>, &mut [ZVal]) -> R + Send + Sync + 'static,
R: Into<ZVal> + 'static,
Expand All @@ -101,7 +101,7 @@ impl<T: Send + 'static> StatefulClass<T> {
}

pub fn add_static_method<F, R>(
&mut self, name: impl ToString, vis: Visibility, handler: F, arguments: Vec<Argument>,
&mut self, name: impl Into<String>, vis: Visibility, handler: F, arguments: Vec<Argument>,
) where
F: Fn(&mut [ZVal]) -> R + Send + Sync + 'static,
R: Into<ZVal> + 'static,
Expand All @@ -121,14 +121,14 @@ impl<T: Send + 'static> StatefulClass<T> {
/// receive only scalar zval , otherwise will report fatal error:
/// "Internal zvals cannot be refcounted".
pub fn add_property(
&mut self, name: impl ToString, visibility: Visibility, value: impl Into<Scalar>,
&mut self, name: impl Into<String>, visibility: Visibility, value: impl Into<Scalar>,
) {
self.property_entities
.push(PropertyEntity::new(name, visibility, value));
}

pub fn extends(&mut self, name: impl ToString) {
let name = name.to_string();
pub fn extends(&mut self, name: impl Into<String>) {
let name = name.into();
self.parent = Some(name);
}
}
Expand Down Expand Up @@ -351,9 +351,9 @@ pub struct PropertyEntity {
}

impl PropertyEntity {
pub fn new(name: impl ToString, visibility: Visibility, value: impl Into<Scalar>) -> Self {
pub fn new(name: impl Into<String>, visibility: Visibility, value: impl Into<Scalar>) -> Self {
Self {
name: name.to_string(),
name: name.into(),
visibility,
value: value.into(),
}
Expand Down
62 changes: 61 additions & 1 deletion phper/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,64 @@
// NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.

// TODO Add constant.
//! Apis relate to [crate::sys::zend_constant].

use std::ffi::{c_char, c_int};

use crate::{modules::ModuleContext, sys::*, types::Scalar};

pub(crate) struct Constant {
name: String,
value: Scalar,
}

impl Constant {
pub fn new(name: impl Into<String>, value: impl Into<Scalar>) -> Self {
Self {
name: name.into(),
value: value.into(),
}
}

pub(crate) fn register(&self, module_context: &ModuleContext) {
let name_ptr = self.name.as_ptr() as *const c_char;
let name_len = self.name.len() as size_t;
let flags = (CONST_PERSISTENT | CONST_CS) as c_int;
let num = module_context.module_number;

unsafe {
match &self.value {
Scalar::Null => zend_register_null_constant(name_ptr, name_len, flags, num),
Scalar::Bool(b) => {
zend_register_bool_constant(name_ptr, name_len, *b as zend_bool, flags, num)
}
Scalar::I64(i) => {
zend_register_long_constant(name_ptr, name_len, *i as zend_long, flags, num)
}
Scalar::F64(f) => zend_register_double_constant(name_ptr, name_len, *f, flags, num),
Scalar::String(s) => {
let s_ptr = s.as_ptr() as *mut u8;
zend_register_stringl_constant(
name_ptr,
name_len,
s_ptr.cast(),
s.len() as size_t,
flags,
num,
)
}
Scalar::Bytes(s) => {
let s_ptr = s.as_ptr() as *mut u8;
zend_register_stringl_constant(
name_ptr,
name_len,
s_ptr.cast(),
s.len() as size_t,
flags,
num,
)
}
}
}
}
}
6 changes: 3 additions & 3 deletions phper/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,9 @@ pub enum Error {
}

impl Error {
/// An essy way to cause an [anyhow::Error].
pub fn other(message: impl ToString) -> Self {
let message = message.to_string();
/// An easy way to cause an [anyhow::Error].
pub fn other(message: impl Into<String>) -> Self {
let message = message.into();
Other(anyhow!(message))
}
}
Expand Down
10 changes: 5 additions & 5 deletions phper/src/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ pub struct FunctionEntity {

impl FunctionEntity {
pub(crate) fn new(
name: impl ToString, handler: Box<dyn Callable>, arguments: Vec<Argument>,
name: impl Into<String>, handler: Box<dyn Callable>, arguments: Vec<Argument>,
visibility: Option<Visibility>, r#static: Option<bool>,
) -> Self {
let name = ensure_end_with_zero(name);
Expand Down Expand Up @@ -178,7 +178,7 @@ pub struct Argument {
}

impl Argument {
pub fn by_val(name: impl ToString) -> Self {
pub fn by_val(name: impl Into<String>) -> Self {
let name = ensure_end_with_zero(name);
Self {
name,
Expand All @@ -187,7 +187,7 @@ impl Argument {
}
}

pub fn by_ref(name: impl ToString) -> Self {
pub fn by_ref(name: impl Into<String>) -> Self {
let name = ensure_end_with_zero(name);
Self {
name,
Expand All @@ -196,7 +196,7 @@ impl Argument {
}
}

pub fn by_val_optional(name: impl ToString) -> Self {
pub fn by_val_optional(name: impl Into<String>) -> Self {
let name = ensure_end_with_zero(name);
Self {
name,
Expand All @@ -205,7 +205,7 @@ impl Argument {
}
}

pub fn by_ref_optional(name: impl ToString) -> Self {
pub fn by_ref_optional(name: impl Into<String>) -> Self {
let name = ensure_end_with_zero(name);
Self {
name,
Expand Down
13 changes: 6 additions & 7 deletions phper/src/ini.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,16 @@ thread_local! {
pub struct Ini;

impl Ini {
pub fn add(name: impl ToString, default_value: impl TransformIniValue, policy: Policy) {
pub fn add(name: impl Into<String>, default_value: impl TransformIniValue, policy: Policy) {
assert!(
!REGISTERED.load(Ordering::SeqCst),
"shouldn't add ini after registered"
);

let name = name.into();

INI_ENTITIES.with(|ini_entities| {
ini_entities.insert(
name.to_string(),
IniEntity::new(name, default_value, policy),
);
ini_entities.insert(name.clone(), IniEntity::new(name, default_value, policy));
});
}

Expand Down Expand Up @@ -194,11 +193,11 @@ pub(crate) struct IniEntity {

impl IniEntity {
pub(crate) fn new<T: TransformIniValue>(
name: impl ToString, default_value: T, policy: Policy,
name: impl Into<String>, default_value: T, policy: Policy,
) -> Self {
assert!(<T>::arg2_size() <= size_of::<usize>());
Self {
name: name.to_string(),
name: name.into(),
value: 0,
value_type_id: <T>::arg2_type(),
default_value: default_value.to_text(),
Expand Down
2 changes: 1 addition & 1 deletion phper/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ mod macros;
pub mod arrays;
pub mod classes;
pub mod cmd;
pub mod constants;
pub(crate) mod constants;
pub mod errors;
pub mod exceptions;
pub mod functions;
Expand Down
24 changes: 19 additions & 5 deletions phper/src/modules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@
use crate::{
c_str_ptr,
classes::{ClassEntity, Classifiable},
constants::Constant,
functions::{Argument, Function, FunctionEntity},
ini::Ini,
sys::*,
types::Scalar,
utils::ensure_end_with_zero,
values::ZVal,
};
Expand All @@ -42,6 +44,9 @@ unsafe extern "C" fn module_startup(r#type: c_int, module_number: c_int) -> c_in
let args = ModuleContext::new(r#type, module_number);
write_global_module(|module| {
args.register_ini_entries(Ini::entries());
for constant in &module.constants {
constant.register(&args);
}
for class_entity in &mut module.class_entities {
class_entity.init();
class_entity.declare_properties();
Expand Down Expand Up @@ -106,10 +111,13 @@ pub struct Module {
request_shutdown: Option<Box<dyn Fn(ModuleContext) -> bool + Send + Sync>>,
function_entities: Vec<FunctionEntity>,
class_entities: Vec<ClassEntity>,
constants: Vec<Constant>,
}

impl Module {
pub fn new(name: impl ToString, version: impl ToString, author: impl ToString) -> Self {
pub fn new(
name: impl Into<String>, version: impl Into<String>, author: impl Into<String>,
) -> Self {
Self {
name: ensure_end_with_zero(name),
version: ensure_end_with_zero(version),
Expand All @@ -120,6 +128,7 @@ impl Module {
request_shutdown: None,
function_entities: vec![],
class_entities: Default::default(),
constants: Default::default(),
}
}

Expand Down Expand Up @@ -147,8 +156,9 @@ impl Module {
self.request_shutdown = Some(Box::new(func));
}

pub fn add_function<F, R>(&mut self, name: impl ToString, handler: F, arguments: Vec<Argument>)
where
pub fn add_function<F, R>(
&mut self, name: impl Into<String>, handler: F, arguments: Vec<Argument>,
) where
F: Fn(&mut [ZVal]) -> R + Send + Sync + 'static,
R: Into<ZVal> + 'static,
{
Expand All @@ -165,6 +175,10 @@ impl Module {
self.class_entities.push(unsafe { ClassEntity::new(class) });
}

pub fn add_constant(&mut self, name: impl Into<String>, value: impl Into<Scalar>) {
self.constants.push(Constant::new(name, value));
}

/// Leak memory to generate `zend_module_entry` pointer.
#[doc(hidden)]
pub unsafe fn module_entry(self) -> *const zend_module_entry {
Expand Down Expand Up @@ -223,8 +237,8 @@ impl Module {

pub struct ModuleContext {
#[allow(dead_code)]
r#type: c_int,
module_number: c_int,
pub(crate) r#type: c_int,
pub(crate) module_number: c_int,
}

impl ModuleContext {
Expand Down
4 changes: 2 additions & 2 deletions phper/src/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub enum LogLevel {
Deprecated = E_DEPRECATED,
}

pub fn log(level: LogLevel, message: impl ToString) {
pub fn log(level: LogLevel, message: impl Into<String>) {
let message = ensure_end_with_zero(message);
unsafe {
php_error_docref1(
Expand All @@ -34,7 +34,7 @@ pub fn log(level: LogLevel, message: impl ToString) {
}
}

pub fn echo(message: impl ToString) {
pub fn echo(message: impl Into<String>) {
let message = ensure_end_with_zero(message);
unsafe {
zend_write.expect("function zend_write can't be null")(
Expand Down
4 changes: 2 additions & 2 deletions phper/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@

//! Internal useful utils.

pub(crate) fn ensure_end_with_zero(s: impl ToString) -> String {
let mut s = s.to_string();
pub(crate) fn ensure_end_with_zero(s: impl Into<String>) -> String {
let mut s = s.into();
if !s.ends_with('\0') {
s.push('\0');
}
Expand Down
21 changes: 21 additions & 0 deletions tests/integration/src/constant.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright (c) 2022 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.

use phper::modules::Module;

pub fn integrate(module: &mut Module) {
module.add_constant("INTEGRATE_CONST_NULL", ());
module.add_constant("INTEGRATE_CONST_TRUE", true);
module.add_constant("INTEGRATE_CONST_FALSE", false);
module.add_constant("INTEGRATE_CONST_LONG", 100i64);
module.add_constant("INTEGRATE_CONST_DOUBLE", 200.);
module.add_constant("INTEGRATE_CONST_STRING", "something");
module.add_constant("INTEGRATE_CONST_BYTES", "something".as_bytes().to_owned());
}
2 changes: 2 additions & 0 deletions tests/integration/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
mod arguments;
mod arrays;
mod classes;
mod constant;
mod functions;
mod objects;
mod strings;
Expand All @@ -35,6 +36,7 @@ pub fn get_module() -> Module {
objects::integrate(&mut module);
strings::integrate(&mut module);
values::integrate(&mut module);
constant::integrate(&mut module);

module
}
Loading