1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 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 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 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 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 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
//! Represents a string in the PHP world. Similar to a C string, but is
//! reference counted and contains the length of the string.
use std::{
borrow::Cow,
convert::TryFrom,
ffi::{CStr, CString},
fmt::Debug,
slice,
};
use parking_lot::{const_mutex, Mutex};
use crate::{
boxed::{ZBox, ZBoxable},
convert::{FromZval, IntoZval},
error::{Error, Result},
ffi::{
ext_php_rs_is_known_valid_utf8, ext_php_rs_set_known_valid_utf8,
ext_php_rs_zend_string_init, ext_php_rs_zend_string_release, zend_string,
zend_string_init_interned,
},
flags::DataType,
macros::try_from_zval,
types::Zval,
};
/// A borrowed Zend string.
///
/// Although this object does implement [`Sized`], it is in fact not sized. As C
/// cannot represent unsized types, an array of size 1 is used at the end of the
/// type to represent the contents of the string, therefore this type is
/// actually unsized. All constructors return [`ZBox<ZendStr>`], the owned
/// variant.
///
/// Once the `ptr_metadata` feature lands in stable rust, this type can
/// potentially be changed to a DST using slices and metadata. See the tracking issue here: <https://github.com/rust-lang/rust/issues/81513>
pub type ZendStr = zend_string;
// Adding to the Zend interned string hashtable is not atomic and can be
// contested when PHP is compiled with ZTS, so an empty mutex is used to ensure
// no collisions occur on the Rust side. Not much we can do about collisions
// on the PHP side, but some safety is better than none.
static INTERNED_LOCK: Mutex<()> = const_mutex(());
// Clippy complains about there being no `is_empty` function when implementing
// on the alias `ZendStr` :( <https://github.com/rust-lang/rust-clippy/issues/7702>
#[allow(clippy::len_without_is_empty)]
impl ZendStr {
/// 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
///
/// ```no_run
/// use ext_php_rs::types::ZendStr;
///
/// let s = ZendStr::new("Hello, world!", false);
/// let php = ZendStr::new([80, 72, 80], false);
/// ```
pub fn new(str: impl AsRef<[u8]>, persistent: bool) -> ZBox<Self> {
let s = str.as_ref();
// TODO: we should handle the special cases when length is either 0 or 1
// see `zend_string_init_fast()` in `zend_string.h`
unsafe {
let ptr = ext_php_rs_zend_string_init(s.as_ptr().cast(), s.len(), persistent)
.as_mut()
.expect("Failed to allocate memory for new Zend string");
ZBox::from_raw(ptr)
}
}
/// 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
///
/// ```no_run
/// 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);
/// ```
pub fn from_c_str(str: &CStr, persistent: bool) -> ZBox<Self> {
unsafe {
let ptr =
ext_php_rs_zend_string_init(str.as_ptr(), str.to_bytes().len() as _, persistent);
ZBox::from_raw(
ptr.as_mut()
.expect("Failed to allocate memory for new Zend string"),
)
}
}
/// 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
///
/// ```no_run
/// use ext_php_rs::types::ZendStr;
///
/// let s = ZendStr::new_interned("PHP", true);
/// ```
pub fn new_interned(str: impl AsRef<[u8]>, persistent: bool) -> ZBox<Self> {
let _lock = INTERNED_LOCK.lock();
let s = str.as_ref();
unsafe {
let init = zend_string_init_interned.expect("`zend_string_init_interned` not ready");
let ptr = init(s.as_ptr().cast(), s.len() as _, persistent)
.as_mut()
.expect("Failed to allocate memory for new Zend string");
ZBox::from_raw(ptr)
}
}
/// 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
///
/// ```no_run
/// 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);
/// ```
pub fn interned_from_c_str(str: &CStr, persistent: bool) -> ZBox<Self> {
let _lock = INTERNED_LOCK.lock();
unsafe {
let init = zend_string_init_interned.expect("`zend_string_init_interned` not ready");
let ptr = init(str.as_ptr(), str.to_bytes().len() as _, persistent);
ZBox::from_raw(
ptr.as_mut()
.expect("Failed to allocate memory for new Zend string"),
)
}
}
/// Returns the length of the string.
///
/// # Example
///
/// ```no_run
/// use ext_php_rs::types::ZendStr;
///
/// let s = ZendStr::new("hello, world!", false);
/// assert_eq!(s.len(), 13);
/// ```
pub fn len(&self) -> usize {
self.len
}
/// Returns true if the string is empty, false otherwise.
///
/// # Example
///
/// ```no_run
/// use ext_php_rs::types::ZendStr;
///
/// let s = ZendStr::new("hello, world!", false);
/// assert_eq!(s.is_empty(), false);
/// ```
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()) }
}
/// 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)
}
}
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)
}
}
impl From<ZBox<ZendStr>> for Cow<'_, ZendStr> {
fn from(value: ZBox<ZendStr>) -> Self {
Cow::Owned(value)
}
}
impl From<Cow<'_, ZendStr>> for ZBox<ZendStr> {
fn from(value: Cow<'_, ZendStr>) -> Self {
value.into_owned()
}
}
macro_rules! try_into_zval_str {
($type: ty) => {
impl TryFrom<$type> for Zval {
type Error = Error;
fn try_from(value: $type) -> Result<Self> {
let mut zv = Self::new();
zv.set_string(&value, false)?;
Ok(zv)
}
}
impl IntoZval for $type {
const TYPE: DataType = DataType::String;
fn set_zval(self, zv: &mut Zval, persistent: bool) -> Result<()> {
zv.set_string(&self, persistent)
}
}
};
}
try_into_zval_str!(String);
try_into_zval_str!(&str);
try_from_zval!(String, string, String);
impl<'a> FromZval<'a> for &'a str {
const TYPE: DataType = DataType::String;
fn from_zval(zval: &'a Zval) -> Option<Self> {
zval.str()
}
}
#[cfg(test)]
#[cfg(feature = "embed")]
mod tests {
use crate::embed::Embed;
#[test]
fn test_string() {
Embed::run(|| {
let result = Embed::eval("'foo';");
assert!(result.is_ok());
let zval = result.as_ref().unwrap();
assert!(zval.is_string());
assert_eq!(zval.string().unwrap(), "foo");
});
}
}