Skip to content

Commit 99bca96

Browse files
authored
Add constant, and replace ToString with Into. (#52)
1 parent 9000501 commit 99bca96

File tree

14 files changed

+158
-38
lines changed

14 files changed

+158
-38
lines changed

examples/http-client/src/response.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ pub fn make_response_class() -> StatefulClass<Option<Response>> {
3131
.ok_or(HttpClientError::ResponseHadRead)
3232
.and_then(|response| response.bytes().map_err(Into::into))
3333
})?;
34-
Ok::<_, HttpClientError>((&body).to_vec())
34+
Ok::<_, HttpClientError>(body.to_vec())
3535
},
3636
vec![],
3737
);

phper/src/classes.rs

+11-11
Original file line numberDiff line numberDiff line change
@@ -57,23 +57,23 @@ pub struct StatefulClass<T: Send + 'static> {
5757
}
5858

5959
impl StatefulClass<()> {
60-
pub fn new(class_name: impl ToString) -> Self {
60+
pub fn new(class_name: impl Into<String>) -> Self {
6161
Self::new_with_state_constructor(class_name, || ())
6262
}
6363
}
6464

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

7171
impl<T: Send + 'static> StatefulClass<T> {
7272
pub fn new_with_state_constructor(
73-
class_name: impl ToString, state_constructor: impl Fn() -> T + Send + Sync + 'static,
73+
class_name: impl Into<String>, state_constructor: impl Fn() -> T + Send + Sync + 'static,
7474
) -> Self {
7575
Self {
76-
class_name: class_name.to_string(),
76+
class_name: class_name.into(),
7777
state_constructor: Arc::new(state_constructor),
7878
method_entities: Vec::new(),
7979
property_entities: Vec::new(),
@@ -86,7 +86,7 @@ impl<T: Send + 'static> StatefulClass<T> {
8686
}
8787

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

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

130-
pub fn extends(&mut self, name: impl ToString) {
131-
let name = name.to_string();
130+
pub fn extends(&mut self, name: impl Into<String>) {
131+
let name = name.into();
132132
self.parent = Some(name);
133133
}
134134
}
@@ -351,9 +351,9 @@ pub struct PropertyEntity {
351351
}
352352

353353
impl PropertyEntity {
354-
pub fn new(name: impl ToString, visibility: Visibility, value: impl Into<Scalar>) -> Self {
354+
pub fn new(name: impl Into<String>, visibility: Visibility, value: impl Into<Scalar>) -> Self {
355355
Self {
356-
name: name.to_string(),
356+
name: name.into(),
357357
visibility,
358358
value: value.into(),
359359
}

phper/src/constants.rs

+61-1
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,64 @@
88
// NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
99
// See the Mulan PSL v2 for more details.
1010

11-
// TODO Add constant.
11+
//! Apis relate to [crate::sys::zend_constant].
12+
13+
use std::ffi::{c_char, c_int};
14+
15+
use crate::{modules::ModuleContext, sys::*, types::Scalar};
16+
17+
pub(crate) struct Constant {
18+
name: String,
19+
value: Scalar,
20+
}
21+
22+
impl Constant {
23+
pub fn new(name: impl Into<String>, value: impl Into<Scalar>) -> Self {
24+
Self {
25+
name: name.into(),
26+
value: value.into(),
27+
}
28+
}
29+
30+
pub(crate) fn register(&self, module_context: &ModuleContext) {
31+
let name_ptr = self.name.as_ptr() as *const c_char;
32+
let name_len = self.name.len() as size_t;
33+
let flags = (CONST_PERSISTENT | CONST_CS) as c_int;
34+
let num = module_context.module_number;
35+
36+
unsafe {
37+
match &self.value {
38+
Scalar::Null => zend_register_null_constant(name_ptr, name_len, flags, num),
39+
Scalar::Bool(b) => {
40+
zend_register_bool_constant(name_ptr, name_len, *b as zend_bool, flags, num)
41+
}
42+
Scalar::I64(i) => {
43+
zend_register_long_constant(name_ptr, name_len, *i as zend_long, flags, num)
44+
}
45+
Scalar::F64(f) => zend_register_double_constant(name_ptr, name_len, *f, flags, num),
46+
Scalar::String(s) => {
47+
let s_ptr = s.as_ptr() as *mut u8;
48+
zend_register_stringl_constant(
49+
name_ptr,
50+
name_len,
51+
s_ptr.cast(),
52+
s.len() as size_t,
53+
flags,
54+
num,
55+
)
56+
}
57+
Scalar::Bytes(s) => {
58+
let s_ptr = s.as_ptr() as *mut u8;
59+
zend_register_stringl_constant(
60+
name_ptr,
61+
name_len,
62+
s_ptr.cast(),
63+
s.len() as size_t,
64+
flags,
65+
num,
66+
)
67+
}
68+
}
69+
}
70+
}
71+
}

phper/src/errors.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,9 @@ pub enum Error {
106106
}
107107

108108
impl Error {
109-
/// An essy way to cause an [anyhow::Error].
110-
pub fn other(message: impl ToString) -> Self {
111-
let message = message.to_string();
109+
/// An easy way to cause an [anyhow::Error].
110+
pub fn other(message: impl Into<String>) -> Self {
111+
let message = message.into();
112112
Other(anyhow!(message))
113113
}
114114
}

phper/src/functions.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ pub struct FunctionEntity {
117117

118118
impl FunctionEntity {
119119
pub(crate) fn new(
120-
name: impl ToString, handler: Box<dyn Callable>, arguments: Vec<Argument>,
120+
name: impl Into<String>, handler: Box<dyn Callable>, arguments: Vec<Argument>,
121121
visibility: Option<Visibility>, r#static: Option<bool>,
122122
) -> Self {
123123
let name = ensure_end_with_zero(name);
@@ -178,7 +178,7 @@ pub struct Argument {
178178
}
179179

180180
impl Argument {
181-
pub fn by_val(name: impl ToString) -> Self {
181+
pub fn by_val(name: impl Into<String>) -> Self {
182182
let name = ensure_end_with_zero(name);
183183
Self {
184184
name,
@@ -187,7 +187,7 @@ impl Argument {
187187
}
188188
}
189189

190-
pub fn by_ref(name: impl ToString) -> Self {
190+
pub fn by_ref(name: impl Into<String>) -> Self {
191191
let name = ensure_end_with_zero(name);
192192
Self {
193193
name,
@@ -196,7 +196,7 @@ impl Argument {
196196
}
197197
}
198198

199-
pub fn by_val_optional(name: impl ToString) -> Self {
199+
pub fn by_val_optional(name: impl Into<String>) -> Self {
200200
let name = ensure_end_with_zero(name);
201201
Self {
202202
name,
@@ -205,7 +205,7 @@ impl Argument {
205205
}
206206
}
207207

208-
pub fn by_ref_optional(name: impl ToString) -> Self {
208+
pub fn by_ref_optional(name: impl Into<String>) -> Self {
209209
let name = ensure_end_with_zero(name);
210210
Self {
211211
name,

phper/src/ini.rs

+6-7
Original file line numberDiff line numberDiff line change
@@ -34,17 +34,16 @@ thread_local! {
3434
pub struct Ini;
3535

3636
impl Ini {
37-
pub fn add(name: impl ToString, default_value: impl TransformIniValue, policy: Policy) {
37+
pub fn add(name: impl Into<String>, default_value: impl TransformIniValue, policy: Policy) {
3838
assert!(
3939
!REGISTERED.load(Ordering::SeqCst),
4040
"shouldn't add ini after registered"
4141
);
4242

43+
let name = name.into();
44+
4345
INI_ENTITIES.with(|ini_entities| {
44-
ini_entities.insert(
45-
name.to_string(),
46-
IniEntity::new(name, default_value, policy),
47-
);
46+
ini_entities.insert(name.clone(), IniEntity::new(name, default_value, policy));
4847
});
4948
}
5049

@@ -194,11 +193,11 @@ pub(crate) struct IniEntity {
194193

195194
impl IniEntity {
196195
pub(crate) fn new<T: TransformIniValue>(
197-
name: impl ToString, default_value: T, policy: Policy,
196+
name: impl Into<String>, default_value: T, policy: Policy,
198197
) -> Self {
199198
assert!(<T>::arg2_size() <= size_of::<usize>());
200199
Self {
201-
name: name.to_string(),
200+
name: name.into(),
202201
value: 0,
203202
value_type_id: <T>::arg2_type(),
204203
default_value: default_value.to_text(),

phper/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ mod macros;
1717
pub mod arrays;
1818
pub mod classes;
1919
pub mod cmd;
20-
pub mod constants;
20+
pub(crate) mod constants;
2121
pub mod errors;
2222
pub mod exceptions;
2323
pub mod functions;

phper/src/modules.rs

+19-5
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,11 @@
1313
use crate::{
1414
c_str_ptr,
1515
classes::{ClassEntity, Classifiable},
16+
constants::Constant,
1617
functions::{Argument, Function, FunctionEntity},
1718
ini::Ini,
1819
sys::*,
20+
types::Scalar,
1921
utils::ensure_end_with_zero,
2022
values::ZVal,
2123
};
@@ -42,6 +44,9 @@ unsafe extern "C" fn module_startup(r#type: c_int, module_number: c_int) -> c_in
4244
let args = ModuleContext::new(r#type, module_number);
4345
write_global_module(|module| {
4446
args.register_ini_entries(Ini::entries());
47+
for constant in &module.constants {
48+
constant.register(&args);
49+
}
4550
for class_entity in &mut module.class_entities {
4651
class_entity.init();
4752
class_entity.declare_properties();
@@ -106,10 +111,13 @@ pub struct Module {
106111
request_shutdown: Option<Box<dyn Fn(ModuleContext) -> bool + Send + Sync>>,
107112
function_entities: Vec<FunctionEntity>,
108113
class_entities: Vec<ClassEntity>,
114+
constants: Vec<Constant>,
109115
}
110116

111117
impl Module {
112-
pub fn new(name: impl ToString, version: impl ToString, author: impl ToString) -> Self {
118+
pub fn new(
119+
name: impl Into<String>, version: impl Into<String>, author: impl Into<String>,
120+
) -> Self {
113121
Self {
114122
name: ensure_end_with_zero(name),
115123
version: ensure_end_with_zero(version),
@@ -120,6 +128,7 @@ impl Module {
120128
request_shutdown: None,
121129
function_entities: vec![],
122130
class_entities: Default::default(),
131+
constants: Default::default(),
123132
}
124133
}
125134

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

150-
pub fn add_function<F, R>(&mut self, name: impl ToString, handler: F, arguments: Vec<Argument>)
151-
where
159+
pub fn add_function<F, R>(
160+
&mut self, name: impl Into<String>, handler: F, arguments: Vec<Argument>,
161+
) where
152162
F: Fn(&mut [ZVal]) -> R + Send + Sync + 'static,
153163
R: Into<ZVal> + 'static,
154164
{
@@ -165,6 +175,10 @@ impl Module {
165175
self.class_entities.push(unsafe { ClassEntity::new(class) });
166176
}
167177

178+
pub fn add_constant(&mut self, name: impl Into<String>, value: impl Into<Scalar>) {
179+
self.constants.push(Constant::new(name, value));
180+
}
181+
168182
/// Leak memory to generate `zend_module_entry` pointer.
169183
#[doc(hidden)]
170184
pub unsafe fn module_entry(self) -> *const zend_module_entry {
@@ -223,8 +237,8 @@ impl Module {
223237

224238
pub struct ModuleContext {
225239
#[allow(dead_code)]
226-
r#type: c_int,
227-
module_number: c_int,
240+
pub(crate) r#type: c_int,
241+
pub(crate) module_number: c_int,
228242
}
229243

230244
impl ModuleContext {

phper/src/output.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ pub enum LogLevel {
2222
Deprecated = E_DEPRECATED,
2323
}
2424

25-
pub fn log(level: LogLevel, message: impl ToString) {
25+
pub fn log(level: LogLevel, message: impl Into<String>) {
2626
let message = ensure_end_with_zero(message);
2727
unsafe {
2828
php_error_docref1(
@@ -34,7 +34,7 @@ pub fn log(level: LogLevel, message: impl ToString) {
3434
}
3535
}
3636

37-
pub fn echo(message: impl ToString) {
37+
pub fn echo(message: impl Into<String>) {
3838
let message = ensure_end_with_zero(message);
3939
unsafe {
4040
zend_write.expect("function zend_write can't be null")(

phper/src/utils.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@
1010

1111
//! Internal useful utils.
1212
13-
pub(crate) fn ensure_end_with_zero(s: impl ToString) -> String {
14-
let mut s = s.to_string();
13+
pub(crate) fn ensure_end_with_zero(s: impl Into<String>) -> String {
14+
let mut s = s.into();
1515
if !s.ends_with('\0') {
1616
s.push('\0');
1717
}

tests/integration/src/constant.rs

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Copyright (c) 2022 PHPER Framework Team
2+
// PHPER is licensed under Mulan PSL v2.
3+
// You can use this software according to the terms and conditions of the Mulan
4+
// PSL v2. You may obtain a copy of Mulan PSL v2 at:
5+
// http://license.coscl.org.cn/MulanPSL2
6+
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
7+
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
8+
// NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
9+
// See the Mulan PSL v2 for more details.
10+
11+
use phper::modules::Module;
12+
13+
pub fn integrate(module: &mut Module) {
14+
module.add_constant("INTEGRATE_CONST_NULL", ());
15+
module.add_constant("INTEGRATE_CONST_TRUE", true);
16+
module.add_constant("INTEGRATE_CONST_FALSE", false);
17+
module.add_constant("INTEGRATE_CONST_LONG", 100i64);
18+
module.add_constant("INTEGRATE_CONST_DOUBLE", 200.);
19+
module.add_constant("INTEGRATE_CONST_STRING", "something");
20+
module.add_constant("INTEGRATE_CONST_BYTES", "something".as_bytes().to_owned());
21+
}

tests/integration/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
mod arguments;
1414
mod arrays;
1515
mod classes;
16+
mod constant;
1617
mod functions;
1718
mod objects;
1819
mod strings;
@@ -35,6 +36,7 @@ pub fn get_module() -> Module {
3536
objects::integrate(&mut module);
3637
strings::integrate(&mut module);
3738
values::integrate(&mut module);
39+
constant::integrate(&mut module);
3840

3941
module
4042
}

0 commit comments

Comments
 (0)