Struct ext_php_rs::ffi::_zend_string
source · #[repr(C)]pub struct _zend_string {
pub gc: zend_refcounted_h,
pub h: zend_ulong,
pub len: usize,
pub val: [c_char; 1],
}
Fields§
§gc: zend_refcounted_h
§h: zend_ulong
§len: usize
§val: [c_char; 1]
Implementations§
source§impl _zend_string
impl _zend_string
sourcepub fn new(str: impl AsRef<[u8]>, persistent: bool) -> ZBox<Self>
pub fn new(str: impl AsRef<[u8]>, persistent: bool) -> ZBox<Self>
Creates a new Zend string from a slice of bytes.
Parameters
str
- String content.persistent
- Whether the string should persist through the request boundary.
Panics
Panics if the function was unable to allocate memory for the Zend string.
Safety
When passing persistent
as false
, the caller must ensure that the
object does not attempt to live after the request finishes. When a
request starts and finishes in PHP, the Zend heap is deallocated and a
new one is created, which would leave a dangling pointer in the
ZBox
.
Example
use ext_php_rs::types::ZendStr;
let s = ZendStr::new("Hello, world!", false);
let php = ZendStr::new([80, 72, 80], false);
Examples found in repository?
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
fn to_owned(&self) -> Self::Owned {
Self::new(self.as_bytes(), false)
}
}
impl<'a> TryFrom<&'a ZendStr> for &'a CStr {
type Error = Error;
fn try_from(value: &'a ZendStr) -> Result<Self> {
value.as_c_str()
}
}
impl<'a> TryFrom<&'a ZendStr> for &'a str {
type Error = Error;
fn try_from(value: &'a ZendStr) -> Result<Self> {
value.as_str()
}
}
impl TryFrom<&ZendStr> for String {
type Error = Error;
fn try_from(value: &ZendStr) -> Result<Self> {
value.as_str().map(ToString::to_string)
}
}
impl<'a> From<&'a ZendStr> for Cow<'a, ZendStr> {
fn from(value: &'a ZendStr) -> Self {
Cow::Borrowed(value)
}
}
impl From<&CStr> for ZBox<ZendStr> {
fn from(value: &CStr) -> Self {
ZendStr::from_c_str(value, false)
}
}
impl From<CString> for ZBox<ZendStr> {
fn from(value: CString) -> Self {
ZendStr::from_c_str(&value, false)
}
}
impl From<&str> for ZBox<ZendStr> {
fn from(value: &str) -> Self {
ZendStr::new(value.as_bytes(), false)
}
}
impl From<String> for ZBox<ZendStr> {
fn from(value: String) -> Self {
ZendStr::new(value.as_str(), false)
}
More examples
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
pub fn get_property<'a, T>(&'a self, name: &str) -> Result<T>
where
T: FromZval<'a>,
{
if !self.has_property(name, PropertyQuery::Exists)? {
return Err(Error::InvalidProperty);
}
let mut name = ZendStr::new(name, false);
let mut rv = Zval::new();
let zv = unsafe {
self.handlers()?.read_property.ok_or(Error::InvalidScope)?(
self.mut_ptr(),
name.deref_mut(),
1,
std::ptr::null_mut(),
&mut rv,
)
.as_ref()
}
.ok_or(Error::InvalidScope)?;
T::from_zval(zv).ok_or_else(|| Error::ZvalConversion(zv.get_type()))
}
/// Attempts to set a property on the object.
///
/// # Parameters
///
/// * `name` - The name of the property.
/// * `value` - The value to set the property to.
pub fn set_property(&mut self, name: &str, value: impl IntoZval) -> Result<()> {
let mut name = ZendStr::new(name, false);
let mut value = value.into_zval(false)?;
unsafe {
self.handlers()?.write_property.ok_or(Error::InvalidScope)?(
self,
name.deref_mut(),
&mut value,
std::ptr::null_mut(),
)
.as_ref()
}
.ok_or(Error::InvalidScope)?;
Ok(())
}
/// Checks if a property exists on an object. Takes a property name and
/// query parameter, which defines what classifies if a property exists
/// or not. See [`PropertyQuery`] for more information.
///
/// # Parameters
///
/// * `name` - The name of the property.
/// * `query` - The 'query' to classify if a property exists.
pub fn has_property(&self, name: &str, query: PropertyQuery) -> Result<bool> {
let mut name = ZendStr::new(name, false);
Ok(unsafe {
self.handlers()?.has_property.ok_or(Error::InvalidScope)?(
self.mut_ptr(),
name.deref_mut(),
query as _,
std::ptr::null_mut(),
)
} > 0)
}
sourcepub fn from_c_str(str: &CStr, persistent: bool) -> ZBox<Self>
pub fn from_c_str(str: &CStr, persistent: bool) -> ZBox<Self>
Creates a new Zend string from a CStr
.
Parameters
str
- String content.persistent
- Whether the string should persist through the request boundary.
Panics
Panics if the function was unable to allocate memory for the Zend string.
Safety
When passing persistent
as false
, the caller must ensure that the
object does not attempt to live after the request finishes. When a
request starts and finishes in PHP, the Zend heap is deallocated and a
new one is created, which would leave a dangling pointer in the
ZBox
.
Example
use ext_php_rs::types::ZendStr;
use std::ffi::CString;
let c_s = CString::new("Hello world!").unwrap();
let s = ZendStr::from_c_str(&c_s, false);
sourcepub fn new_interned(str: impl AsRef<[u8]>, persistent: bool) -> ZBox<Self>
pub fn new_interned(str: impl AsRef<[u8]>, persistent: bool) -> ZBox<Self>
Creates a new interned Zend string from a slice of bytes.
An interned string is only ever stored once and is immutable. PHP stores the string in an internal hashtable which stores the interned strings.
As Zend hashtables are not thread-safe, a mutex is used to prevent two interned strings from being created at the same time.
Interned strings are not used very often. You should almost always use a regular zend string, except in the case that you know you will use a string that PHP will already have interned, such as “PHP”.
Parameters
str
- String content.persistent
- Whether the string should persist through the request boundary.
Panics
Panics under the following circumstances:
- The function used to create interned strings has not been set.
- The function could not allocate enough memory for the Zend string.
Safety
When passing persistent
as false
, the caller must ensure that the
object does not attempt to live after the request finishes. When a
request starts and finishes in PHP, the Zend heap is deallocated and a
new one is created, which would leave a dangling pointer in the
ZBox
.
Example
use ext_php_rs::types::ZendStr;
let s = ZendStr::new_interned("PHP", true);
Examples found in repository?
More examples
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
pub fn build(mut self) -> Result<&'static mut ClassEntry> {
self.ce.name = ZendStr::new_interned(&self.name, true).into_raw();
self.methods.push(FunctionEntry::end());
let func = Box::into_raw(self.methods.into_boxed_slice()) as *const FunctionEntry;
self.ce.info.internal.builtin_functions = func;
let class = unsafe {
zend_register_internal_class_ex(
&mut self.ce,
match self.extends {
Some(ptr) => (ptr as *const _) as *mut _,
None => std::ptr::null_mut(),
},
)
.as_mut()
.ok_or(Error::InvalidPointer)?
};
// disable serialization if the class has an associated object
if self.object_override.is_some() {
cfg_if::cfg_if! {
if #[cfg(any(php81, php82))] {
class.ce_flags |= ClassFlags::NotSerializable.bits();
} else {
class.serialize = Some(crate::ffi::zend_class_serialize_deny);
class.unserialize = Some(crate::ffi::zend_class_unserialize_deny);
}
}
}
for iface in self.interfaces {
unsafe {
zend_do_implement_interface(
class,
iface as *const crate::ffi::_zend_class_entry
as *mut crate::ffi::_zend_class_entry,
)
};
}
for (name, mut default, flags) in self.properties {
unsafe {
zend_declare_property(
class,
CString::new(name.as_str())?.as_ptr(),
name.len() as _,
&mut default,
flags.bits() as _,
);
}
}
for (name, value) in self.constants {
let value = Box::into_raw(Box::new(value));
unsafe {
zend_declare_class_constant(
class,
CString::new(name.as_str())?.as_ptr(),
name.len(),
value,
)
};
}
if let Some(object_override) = self.object_override {
class.__bindgen_anon_2.create_object = Some(object_override);
}
Ok(class)
}
sourcepub fn interned_from_c_str(str: &CStr, persistent: bool) -> ZBox<Self>
pub fn interned_from_c_str(str: &CStr, persistent: bool) -> ZBox<Self>
Creates a new interned Zend string from a CStr
.
An interned string is only ever stored once and is immutable. PHP stores the string in an internal hashtable which stores the interned strings.
As Zend hashtables are not thread-safe, a mutex is used to prevent two interned strings from being created at the same time.
Interned strings are not used very often. You should almost always use a regular zend string, except in the case that you know you will use a string that PHP will already have interned, such as “PHP”.
Parameters
str
- String content.persistent
- Whether the string should persist through the request boundary.
Panics
Panics under the following circumstances:
- The function used to create interned strings has not been set.
- The function could not allocate enough memory for the Zend string.
Safety
When passing persistent
as false
, the caller must ensure that the
object does not attempt to live after the request finishes. When a
request starts and finishes in PHP, the Zend heap is deallocated and a
new one is created, which would leave a dangling pointer in the
ZBox
.
Example
use ext_php_rs::types::ZendStr;
use std::ffi::CString;
let c_s = CString::new("PHP").unwrap();
let s = ZendStr::interned_from_c_str(&c_s, true);
sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the length of the string.
Example
use ext_php_rs::types::ZendStr;
let s = ZendStr::new("hello, world!", false);
assert_eq!(s.len(), 13);
Examples found in repository?
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Attempts to return a reference to the underlying bytes inside the Zend
/// string as a [`CStr`].
///
/// Returns an [Error::InvalidCString] variant if the string contains null
/// bytes.
pub fn as_c_str(&self) -> Result<&CStr> {
let bytes_with_null =
unsafe { slice::from_raw_parts(self.val.as_ptr().cast(), self.len() + 1) };
CStr::from_bytes_with_nul(bytes_with_null).map_err(|_| Error::InvalidCString)
}
/// Attempts to return a reference to the underlying bytes inside the Zend
/// string.
///
/// Returns an [Error::InvalidUtf8] variant if the [`str`] contains
/// non-UTF-8 characters.
///
/// # Example
///
/// ```no_run
/// use ext_php_rs::types::ZendStr;
///
/// let s = ZendStr::new("hello, world!", false);
/// assert!(s.as_str().is_ok());
/// ```
pub fn as_str(&self) -> Result<&str> {
if unsafe { ext_php_rs_is_known_valid_utf8(self.as_ptr()) } {
let str = unsafe { std::str::from_utf8_unchecked(self.as_bytes()) };
return Ok(str);
}
let str = std::str::from_utf8(self.as_bytes()).map_err(|_| Error::InvalidUtf8)?;
unsafe { ext_php_rs_set_known_valid_utf8(self.as_ptr() as *mut _) };
Ok(str)
}
/// Returns a reference to the underlying bytes inside the Zend string.
pub fn as_bytes(&self) -> &[u8] {
unsafe { slice::from_raw_parts(self.val.as_ptr().cast(), self.len()) }
}
sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true if the string is empty, false otherwise.
Example
use ext_php_rs::types::ZendStr;
let s = ZendStr::new("hello, world!", false);
assert_eq!(s.is_empty(), false);
sourcepub fn as_c_str(&self) -> Result<&CStr>
pub fn as_c_str(&self) -> Result<&CStr>
Attempts to return a reference to the underlying bytes inside the Zend
string as a CStr
.
Returns an Error::InvalidCString variant if the string contains null bytes.
sourcepub fn as_str(&self) -> Result<&str>
pub fn as_str(&self) -> Result<&str>
Attempts to return a reference to the underlying bytes inside the Zend string.
Returns an Error::InvalidUtf8 variant if the str
contains
non-UTF-8 characters.
Example
use ext_php_rs::types::ZendStr;
let s = ZendStr::new("hello, world!", false);
assert!(s.as_str().is_ok());
Examples found in repository?
More examples
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.as_str().fmt(f)
}
}
impl AsRef<[u8]> for ZendStr {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl<T> PartialEq<T> for ZendStr
where
T: AsRef<[u8]>,
{
fn eq(&self, other: &T) -> bool {
self.as_ref() == other.as_ref()
}
}
impl ToOwned for ZendStr {
type Owned = ZBox<ZendStr>;
fn to_owned(&self) -> Self::Owned {
Self::new(self.as_bytes(), false)
}
}
impl<'a> TryFrom<&'a ZendStr> for &'a CStr {
type Error = Error;
fn try_from(value: &'a ZendStr) -> Result<Self> {
value.as_c_str()
}
}
impl<'a> TryFrom<&'a ZendStr> for &'a str {
type Error = Error;
fn try_from(value: &'a ZendStr) -> Result<Self> {
value.as_str()
}
}
impl TryFrom<&ZendStr> for String {
type Error = Error;
fn try_from(value: &ZendStr) -> Result<Self> {
value.as_str().map(ToString::to_string)
}
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
unsafe fn internal<T: RegisteredClass>(
object: *mut ZendObject,
member: *mut ZendStr,
type_: c_int,
cache_slot: *mut *mut c_void,
rv: *mut Zval,
) -> PhpResult<*mut Zval> {
let obj = object
.as_mut()
.and_then(|obj| ZendClassObject::<T>::from_zend_obj_mut(obj))
.ok_or("Invalid object pointer given")?;
let prop_name = member
.as_ref()
.ok_or("Invalid property name pointer given")?;
let self_ = &mut **obj;
let props = T::get_metadata().get_properties();
let prop = props.get(prop_name.as_str()?);
// retval needs to be treated as initialized, so we set the type to null
let rv_mut = rv.as_mut().ok_or("Invalid return zval given")?;
rv_mut.u1.type_info = ZvalTypeFlags::Null.bits();
Ok(match prop {
Some(prop) => {
prop.get(self_, rv_mut)?;
rv
}
None => zend_std_read_property(object, member, type_, cache_slot, rv),
})
}
match internal::<T>(object, member, type_, cache_slot, rv) {
Ok(rv) => rv,
Err(e) => {
let _ = e.throw();
(*rv).set_null();
rv
}
}
}
unsafe extern "C" fn write_property<T: RegisteredClass>(
object: *mut ZendObject,
member: *mut ZendStr,
value: *mut Zval,
cache_slot: *mut *mut c_void,
) -> *mut Zval {
#[inline(always)]
unsafe fn internal<T: RegisteredClass>(
object: *mut ZendObject,
member: *mut ZendStr,
value: *mut Zval,
cache_slot: *mut *mut c_void,
) -> PhpResult<*mut Zval> {
let obj = object
.as_mut()
.and_then(|obj| ZendClassObject::<T>::from_zend_obj_mut(obj))
.ok_or("Invalid object pointer given")?;
let prop_name = member
.as_ref()
.ok_or("Invalid property name pointer given")?;
let self_ = &mut **obj;
let props = T::get_metadata().get_properties();
let prop = props.get(prop_name.as_str()?);
let value_mut = value.as_mut().ok_or("Invalid return zval given")?;
Ok(match prop {
Some(prop) => {
prop.set(self_, value_mut)?;
value
}
None => zend_std_write_property(object, member, value, cache_slot),
})
}
match internal::<T>(object, member, value, cache_slot) {
Ok(rv) => rv,
Err(e) => {
let _ = e.throw();
value
}
}
}
unsafe extern "C" fn get_properties<T: RegisteredClass>(
object: *mut ZendObject,
) -> *mut ZendHashTable {
#[inline(always)]
unsafe fn internal<T: RegisteredClass>(
object: *mut ZendObject,
props: &mut ZendHashTable,
) -> PhpResult {
let obj = object
.as_mut()
.and_then(|obj| ZendClassObject::<T>::from_zend_obj_mut(obj))
.ok_or("Invalid object pointer given")?;
let self_ = &mut **obj;
let struct_props = T::get_metadata().get_properties();
for (name, val) in struct_props {
let mut zv = Zval::new();
if val.get(self_, &mut zv).is_err() {
continue;
}
props.insert(name, zv).map_err(|e| {
format!("Failed to insert value into properties hashtable: {:?}", e)
})?;
}
Ok(())
}
let props = zend_std_get_properties(object)
.as_mut()
.or_else(|| Some(ZendHashTable::new().into_raw()))
.expect("Failed to get property hashtable");
if let Err(e) = internal::<T>(object, props) {
let _ = e.throw();
}
props
}
unsafe extern "C" fn has_property<T: RegisteredClass>(
object: *mut ZendObject,
member: *mut ZendStr,
has_set_exists: c_int,
cache_slot: *mut *mut c_void,
) -> c_int {
#[inline(always)]
unsafe fn internal<T: RegisteredClass>(
object: *mut ZendObject,
member: *mut ZendStr,
has_set_exists: c_int,
cache_slot: *mut *mut c_void,
) -> PhpResult<c_int> {
let obj = object
.as_mut()
.and_then(|obj| ZendClassObject::<T>::from_zend_obj_mut(obj))
.ok_or("Invalid object pointer given")?;
let prop_name = member
.as_ref()
.ok_or("Invalid property name pointer given")?;
let props = T::get_metadata().get_properties();
let prop = props.get(prop_name.as_str()?);
let self_ = &mut **obj;
match has_set_exists {
//
// * 0 (has) whether property exists and is not NULL
0 => {
if let Some(val) = prop {
let mut zv = Zval::new();
val.get(self_, &mut zv)?;
if !zv.is_null() {
return Ok(1);
}
}
}
//
// * 1 (set) whether property exists and is true
1 => {
if let Some(val) = prop {
let mut zv = Zval::new();
val.get(self_, &mut zv)?;
if zend_is_true(&mut zv) == 1 {
return Ok(1);
}
}
}
//
// * 2 (exists) whether property exists
2 => {
if prop.is_some() {
return Ok(1);
}
}
_ => return Err(
"Invalid value given for `has_set_exists` in struct `has_property` function."
.into(),
),
};
Ok(zend_std_has_property(
object,
member,
has_set_exists,
cache_slot,
))
}
sourcepub fn as_bytes(&self) -> &[u8] ⓘ
pub fn as_bytes(&self) -> &[u8] ⓘ
Returns a reference to the underlying bytes inside the Zend string.
Examples found in repository?
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
pub fn as_str(&self) -> Result<&str> {
if unsafe { ext_php_rs_is_known_valid_utf8(self.as_ptr()) } {
let str = unsafe { std::str::from_utf8_unchecked(self.as_bytes()) };
return Ok(str);
}
let str = std::str::from_utf8(self.as_bytes()).map_err(|_| Error::InvalidUtf8)?;
unsafe { ext_php_rs_set_known_valid_utf8(self.as_ptr() as *mut _) };
Ok(str)
}
/// Returns a reference to the underlying bytes inside the Zend string.
pub fn as_bytes(&self) -> &[u8] {
unsafe { slice::from_raw_parts(self.val.as_ptr().cast(), self.len()) }
}
/// Returns a raw pointer to this object
pub fn as_ptr(&self) -> *const ZendStr {
self as *const _
}
/// Returns a mutable pointer to this object
pub fn as_mut_ptr(&mut self) -> *mut ZendStr {
self as *mut _
}
}
unsafe impl ZBoxable for ZendStr {
fn free(&mut self) {
unsafe { ext_php_rs_zend_string_release(self) };
}
}
impl Debug for ZendStr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.as_str().fmt(f)
}
}
impl AsRef<[u8]> for ZendStr {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl<T> PartialEq<T> for ZendStr
where
T: AsRef<[u8]>,
{
fn eq(&self, other: &T) -> bool {
self.as_ref() == other.as_ref()
}
}
impl ToOwned for ZendStr {
type Owned = ZBox<ZendStr>;
fn to_owned(&self) -> Self::Owned {
Self::new(self.as_bytes(), false)
}
sourcepub fn as_mut_ptr(&mut self) -> *mut ZendStr
pub fn as_mut_ptr(&mut self) -> *mut ZendStr
Returns a mutable pointer to this object