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
//! 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_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
/// varaint.
///
/// 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 [`str`].
///
/// # Parameters
///
/// * `str` - String content.
/// * `persistent` - Whether the string should persist through the request
/// boundary.
///
/// # Returns
///
/// Returns a result containing the Zend string if successful. Returns an
/// error if the given string contains NUL bytes, which cannot be
/// contained inside a C string.
///
/// # 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).unwrap();
/// ```
pub fn new(str: &str, persistent: bool) -> Result<ZBox<Self>> {
Ok(Self::from_c_str(&CString::new(str)?, persistent))
}
/// 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 [`str`].
///
/// 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.
///
/// # Returns
///
/// Returns a result containing the Zend string if successful. Returns an
/// error if the given string contains NUL bytes, which cannot be
/// contained inside a C string.
///
/// # 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_interned("PHP", true);
/// ```
pub fn new_interned(str: &str, persistent: bool) -> Result<ZBox<Self>> {
Ok(Self::interned_from_c_str(&CString::new(str)?, persistent))
}
/// 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 ptr = zend_string_init_interned.expect("`zend_string_init_interned` not ready")(
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).unwrap();
/// assert_eq!(s.len(), 13);
/// ```
pub fn len(&self) -> usize {
self.len as usize
}
/// 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).unwrap();
/// assert_eq!(s.is_empty(), false);
/// ```
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns a reference to the underlying [`CStr`] inside the Zend string.
pub fn as_c_str(&self) -> &CStr {
// SAFETY: Zend strings store their readable length in a fat pointer.
unsafe {
let slice = slice::from_raw_parts(self.val.as_ptr() as *const u8, self.len() + 1);
CStr::from_bytes_with_nul_unchecked(slice)
}
}
/// Attempts to return a reference to the underlying [`str`] inside the Zend
/// string.
///
/// Returns the [`None`] variant if the [`CStr`] contains non-UTF-8
/// characters.
///
/// # Example
///
/// ```no_run
/// use ext_php_rs::types::ZendStr;
///
/// let s = ZendStr::new("hello, world!", false).unwrap();
/// let as_str = s.as_str();
/// assert_eq!(as_str, Some("hello, world!"));
/// ```
pub fn as_str(&self) -> Option<&str> {
self.as_c_str().to_str().ok()
}
}
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_c_str().fmt(f)
}
}
impl ToOwned for ZendStr {
type Owned = ZBox<ZendStr>;
fn to_owned(&self) -> Self::Owned {
Self::from_c_str(self.as_c_str(), false)
}
}
impl PartialEq for ZendStr {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.as_c_str().eq(other.as_c_str())
}
}
impl<'a> From<&'a ZendStr> for &'a CStr {
fn from(value: &'a ZendStr) -> 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().ok_or(Error::InvalidCString)
}
}
impl<'a> TryFrom<&ZendStr> for String {
type Error = Error;
fn try_from(value: &ZendStr) -> Result<Self> {
value
.as_str()
.map(|s| s.to_string())
.ok_or(Error::InvalidCString)
}
}
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 TryFrom<&str> for ZBox<ZendStr> {
type Error = Error;
fn try_from(value: &str) -> Result<Self> {
ZendStr::new(value, false)
}
}
impl TryFrom<String> for ZBox<ZendStr> {
type Error = Error;
fn try_from(value: String) -> Result<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()
}
}