ext_php_rs/types/zval.rs
1//! The base value in PHP. A Zval can contain any PHP type, and the type that it
2//! contains is determined by a property inside the struct. The content of the
3//! Zval is stored in a union.
4
5use std::{convert::TryInto, ffi::c_void, fmt::Debug, mem::ManuallyDrop, ptr};
6
7use cfg_if::cfg_if;
8
9use crate::types::ZendIterator;
10use crate::types::iterable::Iterable;
11use crate::{
12 binary::Pack,
13 binary_slice::PackSlice,
14 boxed::ZBox,
15 convert::{FromZval, FromZvalMut, IntoZval, IntoZvalDyn},
16 error::{Error, Result},
17 ffi::{
18 _zval_struct__bindgen_ty_1, _zval_struct__bindgen_ty_2, GC_IMMUTABLE, IS_ARRAY,
19 IS_CONSTANT_AST, IS_DOUBLE, IS_FALSE, IS_INDIRECT, IS_LONG, IS_NULL, IS_OBJECT, IS_PTR,
20 IS_REFERENCE, IS_RESOURCE, IS_STRING, IS_TRUE, ext_php_rs_zend_string_release,
21 zend_array_dup, zend_is_callable, zend_is_identical, zend_is_iterable, zend_is_true,
22 zend_resource, zend_value, zval, zval_ptr_dtor,
23 },
24 flags::{DataType, DataTypeExt, ZvalTypeFlags},
25 types::{ZendCallable, ZendHashTable, ZendLong, ZendObject, ZendStr},
26};
27
28/// A zend value. This is the primary storage container used throughout the Zend
29/// engine.
30///
31/// A zval can be thought of as a Rust enum, a type that can contain different
32/// values such as integers, strings, objects etc.
33pub type Zval = zval;
34
35// TODO(david): can we make zval send+sync? main problem is that refcounted
36// types do not have atomic refcounters, so technically two threads could
37// reference the same object and attempt to modify refcounter at the same time.
38// need to look into how ZTS works.
39
40// unsafe impl Send for Zval {}
41// unsafe impl Sync for Zval {}
42
43impl Zval {
44 /// Creates a new, empty zval.
45 #[must_use]
46 pub const fn new() -> Self {
47 Self {
48 value: zend_value {
49 ptr: ptr::null_mut(),
50 },
51 #[allow(clippy::used_underscore_items)]
52 u1: _zval_struct__bindgen_ty_1 { type_info: IS_NULL },
53 #[allow(clippy::used_underscore_items)]
54 u2: _zval_struct__bindgen_ty_2 { next: 0 },
55 }
56 }
57
58 /// Creates a null zval
59 #[must_use]
60 pub fn null() -> Zval {
61 let mut zval = Zval::new();
62 zval.set_null();
63 zval
64 }
65
66 /// Creates a zval containing an empty array.
67 #[must_use]
68 pub fn new_array() -> Zval {
69 let mut zval = Zval::new();
70 zval.set_hashtable(ZendHashTable::new());
71 zval
72 }
73
74 /// Dereference the zval, if it is a reference or indirect.
75 #[must_use]
76 #[inline]
77 pub fn dereference(&self) -> &Self {
78 if self.is_reference() {
79 // SAFETY: `is_reference()` guarantees `value.ref_` is valid.
80 unsafe { &(*self.value.ref_).val }
81 } else if self.is_indirect() {
82 // SAFETY: `is_indirect()` guarantees `value.zv` is a valid Zval pointer.
83 unsafe { &*(self.value.zv.cast::<Zval>()) }
84 } else {
85 self
86 }
87 }
88
89 /// Dereference the zval mutable, if it is a reference.
90 #[must_use]
91 #[inline]
92 pub fn dereference_mut(&mut self) -> &mut Self {
93 if self.is_reference() {
94 // SAFETY: `is_reference()` guarantees `value.ref_` is valid.
95 let reference = unsafe { self.value.ref_.as_mut().unwrap_unchecked() };
96 return &mut reference.val;
97 }
98 if self.is_indirect() {
99 // SAFETY: `is_indirect()` guarantees `value.zv` is a valid Zval pointer.
100 return unsafe { &mut *self.value.zv.cast::<Zval>() };
101 }
102 self
103 }
104
105 /// Returns the value of the zval if it is a long.
106 ///
107 /// References are dereferenced transparently.
108 #[must_use]
109 pub fn long(&self) -> Option<ZendLong> {
110 if self.is_long() {
111 return Some(unsafe { self.value.lval });
112 }
113 let zval = self.dereference();
114 if zval.is_long() {
115 Some(unsafe { zval.value.lval })
116 } else {
117 None
118 }
119 }
120
121 /// Returns the value of the zval if it is a bool.
122 ///
123 /// References are dereferenced transparently.
124 #[must_use]
125 pub fn bool(&self) -> Option<bool> {
126 if self.is_bool() {
127 return Some(self.is_true());
128 }
129 let zval = self.dereference();
130 zval.is_bool().then_some(zval.is_true())
131 }
132
133 /// Returns the value of the zval if it is a double.
134 ///
135 /// References are dereferenced transparently.
136 #[must_use]
137 pub fn double(&self) -> Option<f64> {
138 if self.is_double() {
139 return Some(unsafe { self.value.dval });
140 }
141 let zval = self.dereference();
142 if zval.is_double() {
143 Some(unsafe { zval.value.dval })
144 } else {
145 None
146 }
147 }
148
149 /// Returns the value of the zval as a zend string, if it is a string.
150 ///
151 /// References are dereferenced transparently.
152 ///
153 /// Note that this functions output will not be the same as
154 /// [`string()`](#method.string), as this function does not attempt to
155 /// convert other types into a [`String`].
156 #[must_use]
157 pub fn zend_str(&self) -> Option<&ZendStr> {
158 if self.is_string() {
159 return unsafe { self.value.str_.as_ref() };
160 }
161 let zval = self.dereference();
162 if zval.is_string() {
163 unsafe { zval.value.str_.as_ref() }
164 } else {
165 None
166 }
167 }
168
169 /// Returns the value of the zval if it is a string.
170 ///
171 /// [`str()`]: #method.str
172 pub fn string(&self) -> Option<String> {
173 self.str().map(ToString::to_string)
174 }
175
176 /// Returns the value of the zval if it is a string.
177 ///
178 /// Note that this functions output will not be the same as
179 /// [`string()`](#method.string), as this function does not attempt to
180 /// convert other types into a [`String`], as it could not pass back a
181 /// [`&str`] in those cases.
182 #[inline]
183 #[must_use]
184 pub fn str(&self) -> Option<&str> {
185 self.zend_str().and_then(|zs| zs.as_str().ok())
186 }
187
188 /// Returns the value of the zval if it is a string and can be unpacked into
189 /// a vector of a given type. Similar to the [`unpack`] function in PHP,
190 /// except you can only unpack one type.
191 ///
192 /// Returns `None` if the zval is not a string, or if the byte length of
193 /// the string is not a whole multiple of `size_of::<T>()`. The previous
194 /// behavior (silent truncation of trailing bytes) hid off-by-one input
195 /// errors and was a correctness hazard.
196 ///
197 /// There is no way to tell if the data stored in the string is actually of
198 /// the given type. The results of this function can also differ from
199 /// platform-to-platform due to the different representation of some
200 /// types on different platforms. Consult the [`pack`] function
201 /// documentation for more details.
202 ///
203 /// [`pack`]: https://www.php.net/manual/en/function.pack.php
204 /// [`unpack`]: https://www.php.net/manual/en/function.unpack.php
205 #[must_use]
206 pub fn binary<T: Pack>(&self) -> Option<Vec<T>> {
207 let s = self.zend_str()?;
208 if !s.len.is_multiple_of(std::mem::size_of::<T>()) {
209 return None;
210 }
211 Some(T::unpack_into(s))
212 }
213
214 /// Returns the value of the zval if it is a string and can be unpacked into
215 /// a slice of a given type. Similar to the [`unpack`] function in PHP,
216 /// except you can only unpack one type.
217 ///
218 /// This function is similar to [`Zval::binary`] except that a slice is
219 /// returned instead of a vector, meaning the contents of the string is
220 /// not copied.
221 ///
222 /// Returns `None` if the zval is not a string, if the byte length of the
223 /// string is not a whole multiple of `size_of::<T>()`, or if the string
224 /// bytes are not aligned for `T`. Zend allocates strings on 8-byte
225 /// boundaries, so the alignment check only fails for types wider than
226 /// `ZEND_MM_ALIGNMENT` or for strings from a foreign allocator.
227 ///
228 /// There is no way to tell if the data stored in the string is actually of
229 /// the given type. The results of this function can also differ from
230 /// platform-to-platform due to the different representation of some
231 /// types on different platforms. Consult the [`pack`] function
232 /// documentation for more details.
233 ///
234 /// [`pack`]: https://www.php.net/manual/en/function.pack.php
235 /// [`unpack`]: https://www.php.net/manual/en/function.unpack.php
236 #[must_use]
237 pub fn binary_slice<T: PackSlice>(&self) -> Option<&[T]> {
238 let s = self.zend_str()?;
239 if !s.len.is_multiple_of(std::mem::size_of::<T>())
240 || s.val.as_ptr().align_offset(std::mem::align_of::<T>()) != 0
241 {
242 return None;
243 }
244 // SAFETY: length and alignment were checked above, which is the whole
245 // `PackSlice::unpack_into` contract.
246 Some(unsafe { T::unpack_into(s) })
247 }
248
249 /// Returns the value of the zval if it is a resource.
250 ///
251 /// References are dereferenced transparently.
252 #[must_use]
253 pub fn resource(&self) -> Option<*mut zend_resource> {
254 if self.is_resource() {
255 return Some(unsafe { self.value.res });
256 }
257 let zval = self.dereference();
258 if zval.is_resource() {
259 Some(unsafe { zval.value.res })
260 } else {
261 None
262 }
263 }
264
265 /// Returns an immutable reference to the underlying zval hashtable if the
266 /// zval contains an array.
267 ///
268 /// References are dereferenced transparently.
269 #[must_use]
270 pub fn array(&self) -> Option<&ZendHashTable> {
271 if self.is_array() {
272 return unsafe { self.value.arr.as_ref() };
273 }
274 let zval = self.dereference();
275 if zval.is_array() {
276 unsafe { zval.value.arr.as_ref() }
277 } else {
278 None
279 }
280 }
281
282 /// Returns a mutable reference to the underlying zval hashtable if the zval
283 /// contains an array.
284 ///
285 /// # Array Separation
286 ///
287 /// PHP arrays use copy-on-write (COW) semantics. Before returning a mutable
288 /// reference, this method checks if the array is shared (refcount > 1) and
289 /// if so, creates a private copy. This is equivalent to PHP's
290 /// `SEPARATE_ARRAY()` macro and prevents the "Assertion failed:
291 /// `zend_gc_refcount` == 1" error that occurs when modifying shared arrays.
292 pub fn array_mut(&mut self) -> Option<&mut ZendHashTable> {
293 let zval = if self.is_array() {
294 self
295 } else {
296 self.dereference_mut()
297 };
298 if zval.is_array() {
299 unsafe {
300 let arr = zval.value.arr;
301 let ht = &*arr;
302 if ht.is_immutable() {
303 zval.value.arr = zend_array_dup(arr);
304 } else if (*arr).gc.refcount > 1 {
305 (*arr).gc.refcount -= 1;
306 zval.value.arr = zend_array_dup(arr);
307 }
308 zval.value.arr.as_mut()
309 }
310 } else {
311 None
312 }
313 }
314
315 /// Returns the value of the zval if it is an object.
316 ///
317 /// References are dereferenced transparently.
318 #[must_use]
319 pub fn object(&self) -> Option<&ZendObject> {
320 if self.is_object() {
321 return unsafe { self.value.obj.as_ref() };
322 }
323 let zval = self.dereference();
324 if zval.is_object() {
325 unsafe { zval.value.obj.as_ref() }
326 } else {
327 None
328 }
329 }
330
331 /// Returns a mutable reference to the object contained in the [`Zval`], if
332 /// any.
333 ///
334 /// References are dereferenced transparently.
335 pub fn object_mut(&mut self) -> Option<&mut ZendObject> {
336 if self.is_object() {
337 return unsafe { self.value.obj.as_mut() };
338 }
339 let zval = self.dereference_mut();
340 if zval.is_object() {
341 unsafe { zval.value.obj.as_mut() }
342 } else {
343 None
344 }
345 }
346
347 /// Attempts to call a method on the object contained in the zval.
348 ///
349 /// # Errors
350 ///
351 /// * Returns an error if the [`Zval`] is not an object.
352 // TODO: Measure this
353 #[allow(clippy::inline_always)]
354 #[inline(always)]
355 pub fn try_call_method(&self, name: &str, params: Vec<&dyn IntoZvalDyn>) -> Result<Zval> {
356 self.object()
357 .ok_or(Error::Object)?
358 .try_call_method(name, params)
359 }
360
361 /// Returns the value of the zval if it is an internal indirect reference.
362 #[must_use]
363 pub fn indirect(&self) -> Option<&Zval> {
364 if self.is_indirect() {
365 Some(unsafe { &*(self.value.zv.cast::<Zval>()) })
366 } else {
367 None
368 }
369 }
370
371 /// Returns a mutable reference to the zval if it is an internal indirect
372 /// reference.
373 #[must_use]
374 pub fn indirect_mut(&mut self) -> Option<&mut Zval> {
375 if self.is_indirect() {
376 Some(unsafe { &mut *(self.value.zv.cast::<Zval>()) })
377 } else {
378 None
379 }
380 }
381
382 /// Returns the value of the zval if it is a reference.
383 #[inline]
384 #[must_use]
385 pub fn reference(&self) -> Option<&Zval> {
386 if self.is_reference() {
387 Some(&unsafe { self.value.ref_.as_ref() }?.val)
388 } else {
389 None
390 }
391 }
392
393 /// Returns a mutable reference to the underlying zval if it is a reference.
394 pub fn reference_mut(&mut self) -> Option<&mut Zval> {
395 if self.is_reference() {
396 Some(&mut unsafe { self.value.ref_.as_mut() }?.val)
397 } else {
398 None
399 }
400 }
401
402 /// Returns the value of the zval if it is callable.
403 #[must_use]
404 pub fn callable(&self) -> Option<ZendCallable<'_>> {
405 // The Zval is checked if it is callable in the `new` function.
406 ZendCallable::new(self).ok()
407 }
408
409 /// Returns an iterator over the zval if it is traversable.
410 #[must_use]
411 pub fn traversable(&mut self) -> Option<&mut ZendIterator> {
412 if self.is_traversable() {
413 let ce = self.object()?.get_class_entry();
414 ce.get_iterator(self, false)
415 } else {
416 None
417 }
418 }
419
420 /// Returns an iterable over the zval if it is an array or traversable. (is
421 /// iterable)
422 #[must_use]
423 pub fn iterable(&mut self) -> Option<Iterable<'_>> {
424 if self.is_iterable() {
425 Iterable::from_zval_mut(self)
426 } else {
427 None
428 }
429 }
430
431 /// Returns the value of the zval if it is a pointer.
432 ///
433 /// # Safety
434 ///
435 /// The caller must ensure that the pointer contained in the zval is in fact
436 /// a pointer to an instance of `T`, as the zval has no way of defining
437 /// the type of pointer.
438 #[must_use]
439 pub unsafe fn ptr<T>(&self) -> Option<*mut T> {
440 if self.is_ptr() {
441 Some(unsafe { self.value.ptr.cast::<T>() })
442 } else {
443 None
444 }
445 }
446
447 /// Attempts to call the zval as a callable with a list of arguments to pass
448 /// to the function. Note that a thrown exception inside the callable is
449 /// not detectable, therefore you should check if the return value is
450 /// valid rather than unwrapping. Returns a result containing the return
451 /// value of the function, or an error.
452 ///
453 /// You should not call this function directly, rather through the
454 /// [`call_user_func`] macro.
455 ///
456 /// # Parameters
457 ///
458 /// * `params` - A list of parameters to call the function with.
459 ///
460 /// # Errors
461 ///
462 /// * Returns an error if the [`Zval`] is not callable.
463 // TODO: Measure this
464 #[allow(clippy::inline_always)]
465 #[inline(always)]
466 pub fn try_call(&self, params: Vec<&dyn IntoZvalDyn>) -> Result<Zval> {
467 self.callable().ok_or(Error::Callable)?.try_call(params)
468 }
469
470 /// Returns the type of the Zval.
471 #[must_use]
472 pub fn get_type(&self) -> DataType {
473 DataType::from_u32(u32::from(unsafe { self.u1.v.type_ }))
474 }
475
476 #[inline]
477 fn has_type(&self, ty: u32) -> bool {
478 u32::from(unsafe { self.u1.v.type_ }) == ty
479 }
480
481 /// Returns true if the zval is a long, false otherwise.
482 #[inline]
483 #[must_use]
484 pub fn is_long(&self) -> bool {
485 self.has_type(IS_LONG)
486 }
487
488 /// Returns true if the zval is null, false otherwise.
489 #[inline]
490 #[must_use]
491 pub fn is_null(&self) -> bool {
492 self.has_type(IS_NULL)
493 }
494
495 /// Returns true if the zval is true, false otherwise.
496 #[inline]
497 #[must_use]
498 pub fn is_true(&self) -> bool {
499 self.has_type(IS_TRUE)
500 }
501
502 /// Returns true if the zval is false, false otherwise.
503 #[inline]
504 #[must_use]
505 pub fn is_false(&self) -> bool {
506 self.has_type(IS_FALSE)
507 }
508
509 /// Returns true if the zval is a bool, false otherwise.
510 #[inline]
511 #[must_use]
512 pub fn is_bool(&self) -> bool {
513 self.is_true() || self.is_false()
514 }
515
516 /// Returns true if the zval is a double, false otherwise.
517 #[inline]
518 #[must_use]
519 pub fn is_double(&self) -> bool {
520 self.has_type(IS_DOUBLE)
521 }
522
523 /// Returns true if the zval is a string, false otherwise.
524 #[inline]
525 #[must_use]
526 pub fn is_string(&self) -> bool {
527 self.has_type(IS_STRING)
528 }
529
530 /// Returns true if the zval is a resource, false otherwise.
531 #[inline]
532 #[must_use]
533 pub fn is_resource(&self) -> bool {
534 self.has_type(IS_RESOURCE)
535 }
536
537 /// Returns true if the zval is an array, false otherwise.
538 #[inline]
539 #[must_use]
540 pub fn is_array(&self) -> bool {
541 self.has_type(IS_ARRAY)
542 }
543
544 /// Returns true if the zval is an object, false otherwise.
545 #[inline]
546 #[must_use]
547 pub fn is_object(&self) -> bool {
548 self.has_type(IS_OBJECT)
549 }
550
551 /// Returns true if the zval is a reference, false otherwise.
552 #[inline]
553 #[must_use]
554 pub fn is_reference(&self) -> bool {
555 self.has_type(IS_REFERENCE)
556 }
557
558 /// Returns true if the zval is an indirect, false otherwise.
559 #[inline]
560 #[must_use]
561 pub fn is_indirect(&self) -> bool {
562 self.has_type(IS_INDIRECT)
563 }
564
565 /// Returns true if the zval is callable, false otherwise.
566 #[must_use]
567 pub fn is_callable(&self) -> bool {
568 let ptr: *const Self = self;
569 unsafe { zend_is_callable(ptr.cast_mut(), 0, std::ptr::null_mut()) }
570 }
571
572 /// Checks if the zval is identical to another one.
573 /// This works like `===` in php.
574 ///
575 /// # Parameters
576 ///
577 /// * `other` - The the zval to check identity against.
578 #[must_use]
579 pub fn is_identical(&self, other: &Self) -> bool {
580 let self_p: *const Self = self;
581 let other_p: *const Self = other;
582 unsafe { zend_is_identical(self_p.cast_mut(), other_p.cast_mut()) }
583 }
584
585 /// Returns true if the zval is traversable, false otherwise.
586 #[must_use]
587 pub fn is_traversable(&self) -> bool {
588 match self.object() {
589 None => false,
590 Some(obj) => obj.is_traversable(),
591 }
592 }
593
594 /// Returns true if the zval is iterable (array or traversable), false
595 /// otherwise.
596 #[must_use]
597 pub fn is_iterable(&self) -> bool {
598 let ptr: *const Self = self;
599 unsafe { zend_is_iterable(ptr.cast_mut()) }
600 }
601
602 /// Returns true if the zval contains a pointer, false otherwise.
603 #[inline]
604 #[must_use]
605 pub fn is_ptr(&self) -> bool {
606 self.has_type(IS_PTR)
607 }
608
609 /// Returns true if the zval is a scalar value (integer, float, string, or
610 /// bool), false otherwise.
611 ///
612 /// This is equivalent to PHP's `is_scalar()` function.
613 #[inline]
614 #[must_use]
615 pub fn is_scalar(&self) -> bool {
616 self.is_long() || self.is_double() || self.is_string() || self.is_bool()
617 }
618
619 // =========================================================================
620 // Type Coercion Methods
621 // =========================================================================
622 //
623 // These methods convert the zval's value to a different type following
624 // PHP's type coercion rules. Unlike the mutating `coerce_into_*` methods
625 // in some implementations, these are pure functions that return a new value.
626
627 /// Coerces the value to a boolean following PHP's type coercion rules.
628 ///
629 /// This uses PHP's internal `zend_is_true` function to determine the
630 /// boolean value, which handles all PHP types correctly:
631 /// - `null` → `false`
632 /// - `false` → `false`, `true` → `true`
633 /// - `0`, `0.0`, `""`, `"0"` → `false`
634 /// - Empty arrays → `false`
635 /// - Everything else → `true`
636 ///
637 /// # Example
638 ///
639 /// ```no_run
640 /// use ext_php_rs::types::Zval;
641 ///
642 /// let mut zv = Zval::new();
643 /// zv.set_long(0);
644 /// assert_eq!(zv.coerce_to_bool(), false);
645 ///
646 /// zv.set_long(42);
647 /// assert_eq!(zv.coerce_to_bool(), true);
648 /// ```
649 #[must_use]
650 pub fn coerce_to_bool(&self) -> bool {
651 cfg_if! {
652 if #[cfg(php84)] {
653 let ptr: *const Self = self;
654 unsafe { zend_is_true(ptr) }
655 } else {
656 // Pre-PHP 8.4: zend_is_true takes *mut and returns c_int
657 let ptr = self as *const Self as *mut Self;
658 unsafe { zend_is_true(ptr) != 0 }
659 }
660 }
661 }
662
663 /// Coerces the value to a string following PHP's type coercion rules.
664 ///
665 /// This is a Rust implementation that matches PHP's behavior. Returns `None`
666 /// for types that cannot be meaningfully converted to strings (arrays,
667 /// resources, objects without `__toString`).
668 ///
669 /// Conversion rules:
670 /// - Strings → returned as-is
671 /// - Integers → decimal string representation
672 /// - Floats → string representation (uses uppercase `E` for scientific
673 /// notation when exponent >= 14 or <= -5, matching PHP)
674 /// - `true` → `"1"`, `false` → `""`
675 /// - `null` → `""`
676 /// - `INF` → `"INF"`, `-INF` → `"-INF"`, `NAN` → `"NAN"` (uppercase)
677 /// - Objects with `__toString()` → result of calling `__toString()`
678 /// - Arrays, resources, objects without `__toString()` → `None`
679 ///
680 /// # Example
681 ///
682 /// ```no_run
683 /// use ext_php_rs::types::Zval;
684 ///
685 /// let mut zv = Zval::new();
686 /// zv.set_long(42);
687 /// assert_eq!(zv.coerce_to_string(), Some("42".to_string()));
688 ///
689 /// zv.set_bool(true);
690 /// assert_eq!(zv.coerce_to_string(), Some("1".to_string()));
691 /// ```
692 #[must_use]
693 pub fn coerce_to_string(&self) -> Option<String> {
694 // Already a string
695 if let Some(s) = self.str() {
696 return Some(s.to_string());
697 }
698
699 // Boolean
700 if let Some(b) = self.bool() {
701 return Some(if b { "1".to_string() } else { String::new() });
702 }
703
704 // Null
705 if self.is_null() {
706 return Some(String::new());
707 }
708
709 // Integer
710 if let Some(l) = self.long() {
711 return Some(l.to_string());
712 }
713
714 // Float
715 if let Some(d) = self.double() {
716 // PHP uses uppercase for special float values
717 if d.is_nan() {
718 return Some("NAN".to_string());
719 }
720 if d.is_infinite() {
721 return Some(if d.is_sign_positive() {
722 "INF".to_string()
723 } else {
724 "-INF".to_string()
725 });
726 }
727 // PHP uses a format similar to printf's %G with ~14 digits precision
728 // and uppercase E for scientific notation
729 return Some(php_float_to_string(d));
730 }
731
732 // Object with __toString
733 if let Some(obj) = self.object()
734 && let Ok(result) = obj.try_call_method("__toString", vec![])
735 {
736 return result.str().map(ToString::to_string);
737 }
738
739 // Arrays, resources, and objects without __toString cannot be converted
740 None
741 }
742
743 /// Coerces the value to an integer following PHP's type coercion rules.
744 ///
745 /// This is a Rust implementation that matches PHP's behavior. Returns `None`
746 /// for types that cannot be meaningfully converted to integers (arrays,
747 /// resources, objects).
748 ///
749 /// Conversion rules:
750 /// - Integers → returned as-is
751 /// - Floats → truncated toward zero
752 /// - `true` → `1`, `false` → `0`
753 /// - `null` → `0`
754 /// - Strings → parsed as integer (leading numeric portion only; stops at
755 /// first non-digit; returns 0 if non-numeric; saturates on overflow)
756 /// - Arrays, resources, objects → `None`
757 ///
758 /// # Example
759 ///
760 /// ```no_run
761 /// use ext_php_rs::types::Zval;
762 ///
763 /// let mut zv = Zval::new();
764 /// zv.set_string("42abc", false);
765 /// assert_eq!(zv.coerce_to_long(), Some(42));
766 ///
767 /// zv.set_double(3.7);
768 /// assert_eq!(zv.coerce_to_long(), Some(3));
769 /// ```
770 #[must_use]
771 pub fn coerce_to_long(&self) -> Option<ZendLong> {
772 // Already an integer
773 if let Some(l) = self.long() {
774 return Some(l);
775 }
776
777 // Boolean
778 if let Some(b) = self.bool() {
779 return Some(ZendLong::from(b));
780 }
781
782 // Null
783 if self.is_null() {
784 return Some(0);
785 }
786
787 // Float - truncate toward zero
788 if let Some(d) = self.double() {
789 #[allow(clippy::cast_possible_truncation)]
790 return Some(d as ZendLong);
791 }
792
793 // String - parse leading numeric portion
794 if let Some(s) = self.str() {
795 return Some(parse_long_from_str(s));
796 }
797
798 // Arrays, resources, objects cannot be converted
799 None
800 }
801
802 /// Coerces the value to a float following PHP's type coercion rules.
803 ///
804 /// This is a Rust implementation that matches PHP's behavior. Returns `None`
805 /// for types that cannot be meaningfully converted to floats (arrays,
806 /// resources, objects).
807 ///
808 /// Conversion rules:
809 /// - Floats → returned as-is
810 /// - Integers → converted to float
811 /// - `true` → `1.0`, `false` → `0.0`
812 /// - `null` → `0.0`
813 /// - Strings → parsed as float (leading numeric portion including decimal
814 /// point and scientific notation; returns 0.0 if non-numeric)
815 /// - Arrays, resources, objects → `None`
816 ///
817 /// # Example
818 ///
819 /// ```no_run
820 /// use ext_php_rs::types::Zval;
821 ///
822 /// let mut zv = Zval::new();
823 /// zv.set_string("3.14abc", false);
824 /// assert_eq!(zv.coerce_to_double(), Some(3.14));
825 ///
826 /// zv.set_long(42);
827 /// assert_eq!(zv.coerce_to_double(), Some(42.0));
828 /// ```
829 #[must_use]
830 pub fn coerce_to_double(&self) -> Option<f64> {
831 // Already a float
832 if let Some(d) = self.double() {
833 return Some(d);
834 }
835
836 // Integer
837 if let Some(l) = self.long() {
838 #[allow(clippy::cast_precision_loss)]
839 return Some(l as f64);
840 }
841
842 // Boolean
843 if let Some(b) = self.bool() {
844 return Some(if b { 1.0 } else { 0.0 });
845 }
846
847 // Null
848 if self.is_null() {
849 return Some(0.0);
850 }
851
852 // String - parse leading numeric portion
853 if let Some(s) = self.str() {
854 return Some(parse_double_from_str(s));
855 }
856
857 // Arrays, resources, objects cannot be converted
858 None
859 }
860
861 /// Sets the value of the zval as a string. Returns nothing in a result when
862 /// successful.
863 ///
864 /// # Parameters
865 ///
866 /// * `val` - The value to set the zval as.
867 /// * `persistent` - Whether the string should persist between requests.
868 ///
869 /// # Persistent Strings
870 ///
871 /// When `persistent` is `true`, the string is allocated from PHP's
872 /// persistent heap (using `malloc`) rather than the request-bound heap.
873 /// This is typically used for strings that need to survive across multiple
874 /// PHP requests, such as class names, function names, or module-level data.
875 ///
876 /// **Important:** The string will still be freed when the Zval is dropped.
877 /// The `persistent` flag only affects which memory allocator is used. If
878 /// you need a string to outlive the Zval, consider using
879 /// [`std::mem::forget`] on the Zval or storing the string elsewhere.
880 ///
881 /// For most use cases (return values, function arguments, temporary
882 /// storage), you should use `persistent: false`.
883 ///
884 /// # Errors
885 ///
886 /// Never returns an error.
887 // TODO: Check if we can drop the result here.
888 pub fn set_string(&mut self, val: &str, persistent: bool) -> Result<()> {
889 self.set_zend_string(ZendStr::new(val, persistent));
890 Ok(())
891 }
892
893 /// Sets the value of the zval as a Zend string.
894 ///
895 /// The Zval takes ownership of the string. When the Zval is dropped,
896 /// the string will be released.
897 ///
898 /// This is the canonical path for assigning any raw `zend_string` to a
899 /// zval from Rust: it reads the string's `GC_IMMUTABLE` flag and picks
900 /// [`ZvalTypeFlags::InternedStringEx`] (non-refcounted) for interned
901 /// permanent statics like `zend_empty_string` / `zend_one_char_string[c]`,
902 /// otherwise [`ZvalTypeFlags::StringEx`] (refcounted). This mirrors
903 /// PHP's own `ZVAL_STR` macro in `Zend/zend_types.h`. Other `set_*`
904 /// helpers that produce strings (including [`Zval::set_binary`]) route
905 /// through this function to stay in lockstep with upstream flag logic.
906 ///
907 /// # Parameters
908 ///
909 /// * `val` - String content.
910 pub fn set_zend_string(&mut self, val: ZBox<ZendStr>) {
911 let is_interned = unsafe { val.gc.u.type_info } & GC_IMMUTABLE != 0;
912 let flags = if is_interned {
913 ZvalTypeFlags::InternedStringEx
914 } else {
915 ZvalTypeFlags::StringEx
916 };
917 self.change_type(flags);
918 self.value.str_ = val.into_raw();
919 }
920
921 /// Sets the value of the zval as a binary string, which is represented in
922 /// Rust as a vector.
923 ///
924 /// # Parameters
925 ///
926 /// * `val` - The value to set the zval as.
927 pub fn set_binary<T: Pack>(&mut self, val: Vec<T>) {
928 let ptr = T::pack_into(val);
929 // SAFETY: Pack::pack_into returns a non-null zend_string from
930 // ext_php_rs_zend_string_init: either a freshly allocated refcounted
931 // string or an interned permanent static (zend_empty_string or
932 // zend_one_char_string[c]) for packed length 0 or 1. Both are valid
933 // inputs for ZBox::from_raw; zend_string_release short-circuits on
934 // interned strings, matching PHP's own zend_string_release.
935 let zs = unsafe { ZBox::from_raw(ptr) };
936 self.set_zend_string(zs);
937 }
938
939 /// Sets the value of the zval as an interned string. Returns nothing in a
940 /// result when successful.
941 ///
942 /// Interned strings are stored once and are immutable. PHP stores them in
943 /// an internal hashtable. Unlike regular strings, interned strings are not
944 /// reference counted and should not be freed by `zval_ptr_dtor`.
945 ///
946 /// # Parameters
947 ///
948 /// * `val` - The value to set the zval as.
949 /// * `persistent` - Whether the string should persist between requests.
950 ///
951 /// # Errors
952 ///
953 /// Never returns an error.
954 // TODO: Check if we can drop the result here.
955 pub fn set_interned_string(&mut self, val: &str, persistent: bool) -> Result<()> {
956 // Use InternedStringEx (without RefCounted) because interned strings
957 // should not have their refcount modified by zval_ptr_dtor.
958 self.change_type(ZvalTypeFlags::InternedStringEx);
959 self.value.str_ = ZendStr::new_interned(val, persistent).into_raw();
960 Ok(())
961 }
962
963 /// Sets the value of the zval as a long.
964 ///
965 /// # Parameters
966 ///
967 /// * `val` - The value to set the zval as.
968 pub fn set_long<T: Into<ZendLong>>(&mut self, val: T) {
969 self.internal_set_long(val.into());
970 }
971
972 fn internal_set_long(&mut self, val: ZendLong) {
973 self.change_type(ZvalTypeFlags::Long);
974 self.value.lval = val;
975 }
976
977 /// Sets the value of the zval as a double.
978 ///
979 /// # Parameters
980 ///
981 /// * `val` - The value to set the zval as.
982 pub fn set_double<T: Into<f64>>(&mut self, val: T) {
983 self.internal_set_double(val.into());
984 }
985
986 fn internal_set_double(&mut self, val: f64) {
987 self.change_type(ZvalTypeFlags::Double);
988 self.value.dval = val;
989 }
990
991 /// Sets the value of the zval as a boolean.
992 ///
993 /// # Parameters
994 ///
995 /// * `val` - The value to set the zval as.
996 pub fn set_bool<T: Into<bool>>(&mut self, val: T) {
997 self.internal_set_bool(val.into());
998 }
999
1000 fn internal_set_bool(&mut self, val: bool) {
1001 self.change_type(if val {
1002 ZvalTypeFlags::True
1003 } else {
1004 ZvalTypeFlags::False
1005 });
1006 }
1007
1008 /// Sets the value of the zval as null.
1009 ///
1010 /// This is the default of a zval.
1011 pub fn set_null(&mut self) {
1012 self.change_type(ZvalTypeFlags::Null);
1013 }
1014
1015 /// Sets the value of the zval as a resource.
1016 ///
1017 /// # Parameters
1018 ///
1019 /// * `val` - The value to set the zval as.
1020 ///
1021 /// # Safety
1022 ///
1023 /// `val` must be non-null and point to a valid Zend-managed resource with
1024 /// one independent reference that can be transferred into this zval. This
1025 /// function does not increment the resource refcount: the caller
1026 /// relinquishes the transferred reference, which the zval releases when it
1027 /// is overwritten or dropped. The resource must remain valid until Zend
1028 /// releases that reference.
1029 ///
1030 /// Replacing a zval with the same resource also requires an independent
1031 /// incoming reference because the old reference is released before `val`
1032 /// is stored.
1033 ///
1034 /// Calling this method requires an unsafe block:
1035 ///
1036 /// ```compile_fail,E0133
1037 /// use ext_php_rs::{ffi::zend_resource, types::Zval};
1038 ///
1039 /// fn assign_resource(zval: &mut Zval, resource: *mut zend_resource) {
1040 /// zval.set_resource(resource);
1041 /// }
1042 /// ```
1043 ///
1044 /// # Examples
1045 ///
1046 /// ```no_run
1047 /// # use ext_php_rs::{ffi::zend_resource, types::Zval};
1048 /// # fn acquire_resource_from_zend() -> *mut zend_resource { unimplemented!() }
1049 /// let resource = acquire_resource_from_zend();
1050 /// let mut zval = Zval::new();
1051 ///
1052 /// // SAFETY: `resource` is a valid Zend resource whose owned reference is
1053 /// // transferred into `zval`.
1054 /// unsafe { zval.set_resource(resource) };
1055 /// ```
1056 pub unsafe fn set_resource(&mut self, val: *mut zend_resource) {
1057 self.change_type(ZvalTypeFlags::ResourceEx);
1058 self.value.res = val;
1059 }
1060
1061 /// Sets the value of the zval as a reference to an object.
1062 ///
1063 /// This is `ZVAL_OBJ_COPY`: the object refcount is incremented because the
1064 /// zval now holds its own reference, which Zend releases when the zval is
1065 /// destroyed. To hand over a reference you already own, use the
1066 /// [`IntoZval`] impl of `ZBox<ZendObject>` instead.
1067 ///
1068 /// # Parameters
1069 ///
1070 /// * `val` - The value to set the zval as.
1071 pub fn set_object(&mut self, val: &mut ZendObject) {
1072 self.change_type(ZvalTypeFlags::ObjectEx);
1073 val.add_ref();
1074 self.value.obj = ptr::from_ref(val).cast_mut();
1075 }
1076
1077 /// Sets the value of the zval as the object `val` points to, adding a
1078 /// reference without forming a `&mut ZendObject`.
1079 ///
1080 /// # Safety
1081 ///
1082 /// `val` must point to a live object.
1083 pub(crate) unsafe fn set_object_ptr(&mut self, val: *mut ZendObject) {
1084 self.change_type(ZvalTypeFlags::ObjectEx);
1085 unsafe { (*val).gc.refcount += 1 };
1086 self.value.obj = val;
1087 }
1088
1089 /// Sets the value of the zval as an array. Returns nothing in a result on
1090 /// success.
1091 ///
1092 /// # Parameters
1093 ///
1094 /// * `val` - The value to set the zval as.
1095 ///
1096 /// # Errors
1097 ///
1098 /// * Returns an error if the conversion to a hashtable fails.
1099 pub fn set_array<T: TryInto<ZBox<ZendHashTable>, Error = Error>>(
1100 &mut self,
1101 val: T,
1102 ) -> Result<()> {
1103 self.set_hashtable(val.try_into()?);
1104 Ok(())
1105 }
1106
1107 /// Sets the value of the zval as an array. Returns nothing in a result on
1108 /// success.
1109 ///
1110 /// # Parameters
1111 ///
1112 /// * `val` - The value to set the zval as.
1113 pub fn set_hashtable(&mut self, val: ZBox<ZendHashTable>) {
1114 // Handle immutable shared arrays (e.g., the empty array) similar to
1115 // ZVAL_EMPTY_ARRAY. Immutable arrays should not be reference counted.
1116 let type_info = if val.is_immutable() {
1117 ZvalTypeFlags::Array
1118 } else {
1119 ZvalTypeFlags::ArrayEx
1120 };
1121 self.change_type(type_info);
1122 self.value.arr = val.into_raw();
1123 }
1124
1125 /// Sets the value of the zval as a raw pointer (`IS_PTR`).
1126 ///
1127 /// The previous value of the zval is released first.
1128 ///
1129 /// # Parameters
1130 ///
1131 /// * `ptr` - The pointer to set the zval as.
1132 ///
1133 /// # Safety
1134 ///
1135 /// `IS_PTR` zvals are opaque to refcounting, so Zend never frees `ptr`, but
1136 /// several engine tables dereference `IS_PTR` entries with a fixed type:
1137 /// property tables read them as `zend_property_info *`, constant tables as
1138 /// `zend_class_constant *`, `EG(ini_directives)` as `zend_ini_entry *`. The
1139 /// caller must not insert this zval into any table the engine reads unless
1140 /// `ptr` points to the type that table expects, and `ptr` must stay valid
1141 /// for as long as the zval (or any copy of it) is alive.
1142 ///
1143 /// Calling this method requires an unsafe block:
1144 ///
1145 /// ```compile_fail,E0133
1146 /// use ext_php_rs::types::Zval;
1147 ///
1148 /// fn assign_ptr(zval: &mut Zval, ptr: *mut u32) {
1149 /// zval.set_ptr(ptr);
1150 /// }
1151 /// ```
1152 ///
1153 /// # Examples
1154 ///
1155 /// ```no_run
1156 /// # use ext_php_rs::types::Zval;
1157 /// let mut slot = 42u32;
1158 /// let mut zval = Zval::new();
1159 ///
1160 /// // SAFETY: `slot` outlives `zval` and the zval never reaches an engine
1161 /// // table.
1162 /// unsafe { zval.set_ptr(&raw mut slot) };
1163 /// ```
1164 pub unsafe fn set_ptr<T>(&mut self, ptr: *mut T) {
1165 self.change_type(ZvalTypeFlags::Ptr);
1166 self.value.ptr = ptr.cast::<c_void>();
1167 }
1168
1169 /// Used to drop the Zval but keep the value of the zval intact.
1170 ///
1171 /// This is important when copying the value of the zval, as the actual
1172 /// value will not be copied, but the pointer to the value (string for
1173 /// example) will be copied.
1174 pub(crate) fn release(mut self) {
1175 // NOTE(david): don't use `change_type` here as we are wanting to keep the
1176 // contents intact.
1177 self.u1.type_info = ZvalTypeFlags::Null.bits();
1178 }
1179
1180 /// Changes the type of the zval, freeing the current contents when
1181 /// applicable.
1182 ///
1183 /// # Parameters
1184 ///
1185 /// * `ty` - The new type of the zval.
1186 fn change_type(&mut self, ty: ZvalTypeFlags) {
1187 // SAFETY: we have exclusive mutable access to this zval so can free the
1188 // contents.
1189 //
1190 // The old value moves out and the zval is null while the old value is
1191 // released, as `zend_assign_to_variable` does: the release can run a
1192 // destructor or a GC run, and this zval can be engine memory the
1193 // collector walks directly (a hashtable bucket, a property slot), so it
1194 // must not hold a value it no longer owns.
1195 //
1196 // For strings, we use zend_string_release directly instead of zval_ptr_dtor
1197 // to correctly handle persistent strings. zend_string_release properly checks
1198 // the IS_STR_PERSISTENT flag and uses the correct deallocator (free vs efree).
1199 // This fixes heap corruption issues when dropping Zvals containing persistent
1200 // strings (see issue #424).
1201 //
1202 // For simple types (Long, Double, Bool, Null, Undef, True, False), we don't
1203 // need to call zval_ptr_dtor because they don't have heap-allocated data.
1204 // This is important for cargo-php stub generation where zval_ptr_dtor is
1205 // stubbed as a null pointer - calling it would crash.
1206 let mut released = ManuallyDrop::new(Zval::new());
1207 released.value = self.value;
1208 released.u1 = self.u1;
1209 // SAFETY: `type_info` is a field of this zval. The write is volatile so
1210 // the optimizer keeps it in memory while the release below runs PHP code.
1211 unsafe { ptr::write_volatile(&raw mut self.u1.type_info, ZvalTypeFlags::Null.bits()) };
1212 if released.is_string() {
1213 unsafe {
1214 if let Some(str_ptr) = released.value.str_.as_mut() {
1215 ext_php_rs_zend_string_release(str_ptr);
1216 }
1217 }
1218 } else if released.is_array()
1219 || released.is_object()
1220 || released.is_resource()
1221 || released.is_reference()
1222 || released.has_type(IS_CONSTANT_AST)
1223 {
1224 // Only call zval_ptr_dtor for reference-counted types
1225 unsafe { zval_ptr_dtor(&raw mut *released) };
1226 }
1227 // Simple types (Long, Double, Bool, Null, etc.) need no cleanup
1228 self.u1.type_info = ty.bits();
1229 }
1230
1231 /// Extracts some type from a `Zval`.
1232 ///
1233 /// This is a wrapper function around `TryFrom`.
1234 ///
1235 /// For `ClassRef<T>` and `ClassRefMut<T>`, `None` can also mean that the
1236 /// Rust value of the object is borrowed. Use [`Zval::try_extract`] to
1237 /// know the cause.
1238 #[must_use]
1239 pub fn extract<'a, T>(&'a self) -> Option<T>
1240 where
1241 T: FromZval<'a>,
1242 {
1243 FromZval::from_zval(self)
1244 }
1245
1246 /// Extracts some type from a `Zval`, and tells why it failed.
1247 ///
1248 /// # Errors
1249 ///
1250 /// * [`Error::ZvalConversion`] - The value is not a `T`.
1251 /// * [`Error::Borrow`] - The value is a class object whose Rust value is
1252 /// borrowed, for `T` a `ClassRef`, a `ClassRefMut` or an `Option` of
1253 /// them.
1254 pub fn try_extract<'a, T>(&'a self) -> Result<T>
1255 where
1256 T: FromZval<'a>,
1257 {
1258 T::try_from_zval(self)
1259 }
1260
1261 /// Creates a shallow clone of the [`Zval`].
1262 ///
1263 /// This copies the contents of the [`Zval`], and increments the reference
1264 /// counter of the underlying value (if it is reference counted).
1265 ///
1266 /// For example, if the zval contains a long, it will simply copy the value.
1267 /// However, if the zval contains an object, the new zval will point to the
1268 /// same object, and the objects reference counter will be incremented.
1269 ///
1270 /// # Returns
1271 ///
1272 /// The cloned zval.
1273 #[must_use]
1274 pub fn shallow_clone(&self) -> Zval {
1275 let mut new = Zval::new();
1276 new.u1 = self.u1;
1277 new.value = self.value;
1278
1279 // SAFETY: `u1` union is only used for easier bitmasking. It is valid to read
1280 // from either of the variants.
1281 //
1282 // SAFETY: If the value if refcounted (`self.u1.type_info & Z_TYPE_FLAGS_MASK`)
1283 // then it is valid to dereference `self.value.counted`.
1284 unsafe {
1285 let flags = ZvalTypeFlags::from_bits_retain(self.u1.type_info);
1286 if flags.contains(ZvalTypeFlags::RefCounted) {
1287 (*self.value.counted).gc.refcount += 1;
1288 }
1289 }
1290
1291 new
1292 }
1293}
1294
1295impl Debug for Zval {
1296 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1297 let mut dbg = f.debug_struct("Zval");
1298 let ty = self.get_type();
1299 dbg.field("type", &ty);
1300
1301 macro_rules! field {
1302 ($value: expr) => {
1303 dbg.field("val", &$value)
1304 };
1305 }
1306
1307 match ty {
1308 // `Iterable` shows no value on purpose: resolving one would invoke the
1309 // Zend `get_iterator` handler, which allocates and can run arbitrary
1310 // user PHP. Formatting must not have side effects on the engine.
1311 DataType::Undef
1312 | DataType::Null
1313 | DataType::ConstantExpression
1314 | DataType::Void
1315 | DataType::Iterable => {
1316 field!(Option::<()>::None)
1317 }
1318 DataType::False => field!(false),
1319 DataType::True => field!(true),
1320 DataType::Long => field!(self.long()),
1321 DataType::Double => field!(self.double()),
1322 DataType::String | DataType::Mixed | DataType::Callable => field!(self.string()),
1323 DataType::Array => field!(self.array()),
1324 DataType::Object(_) => field!(self.object()),
1325 DataType::Resource => field!(self.resource()),
1326 DataType::Reference => field!(self.reference()),
1327 DataType::Bool => field!(self.bool()),
1328 DataType::Indirect => field!(self.indirect()),
1329 // SAFETY: We are not accessing the pointer.
1330 DataType::Ptr => field!(unsafe { self.ptr::<c_void>() }),
1331 };
1332
1333 dbg.finish()
1334 }
1335}
1336
1337impl Drop for Zval {
1338 fn drop(&mut self) {
1339 self.change_type(ZvalTypeFlags::Null);
1340 }
1341}
1342
1343impl Default for Zval {
1344 fn default() -> Self {
1345 Self::new()
1346 }
1347}
1348
1349impl IntoZval for Zval {
1350 const TYPE: DataType = DataType::Mixed;
1351 const NULLABLE: bool = true;
1352
1353 fn set_zval(self, zv: &mut Zval, _: bool) -> Result<()> {
1354 *zv = self;
1355 Ok(())
1356 }
1357}
1358
1359impl<'a> FromZval<'a> for &'a Zval {
1360 const TYPE: DataType = DataType::Mixed;
1361
1362 fn from_zval(zval: &'a Zval) -> Option<Self> {
1363 Some(zval)
1364 }
1365}
1366
1367impl<'a> FromZvalMut<'a> for &'a mut Zval {
1368 const TYPE: DataType = DataType::Mixed;
1369 const BY_REF: bool = true;
1370
1371 fn from_zval_mut(zval: &'a mut Zval) -> Option<Self> {
1372 Some(zval)
1373 }
1374}
1375
1376/// Formats a float to a string following PHP's type coercion rules.
1377///
1378/// This is a Rust implementation that matches PHP's behavior. PHP uses a format
1379/// similar to printf's `%G` with 14 significant digits:
1380/// - Uses scientific notation when exponent >= 14 or <= -5
1381/// - Uses uppercase 'E' for the exponent (e.g., "1.0E+52")
1382/// - Removes trailing zeros after the decimal point
1383fn php_float_to_string(d: f64) -> String {
1384 // Use Rust's %G-like formatting: format with precision, uppercase E
1385 // PHP uses ~14 significant digits
1386 let formatted = format!("{d:.14E}");
1387
1388 // Parse the formatted string to clean it up
1389 if let Some(e_pos) = formatted.find('E') {
1390 let mantissa_part = &formatted[..e_pos];
1391 let exp_part = &formatted[e_pos..];
1392
1393 // Parse exponent to decide format
1394 let exp: i32 = exp_part[1..].parse().unwrap_or(0);
1395
1396 // PHP uses scientific notation when exponent >= 14 or <= -5
1397 if exp >= 14 || exp <= -5 {
1398 // Keep scientific notation, but clean up mantissa
1399 let mantissa = mantissa_part.trim_end_matches('0').trim_end_matches('.');
1400
1401 // Ensure mantissa has at least one decimal digit if there's a decimal point
1402 let mantissa = if mantissa.contains('.') && mantissa.ends_with('.') {
1403 format!("{mantissa}0")
1404 } else if !mantissa.contains('.') {
1405 format!("{mantissa}.0")
1406 } else {
1407 mantissa.to_string()
1408 };
1409
1410 // Format exponent with sign
1411 if exp >= 0 {
1412 format!("{mantissa}E+{exp}")
1413 } else {
1414 format!("{mantissa}E{exp}")
1415 }
1416 } else {
1417 // Use decimal notation
1418 let s = d.to_string();
1419 // Clean up trailing zeros
1420 if s.contains('.') {
1421 s.trim_end_matches('0').trim_end_matches('.').to_string()
1422 } else {
1423 s
1424 }
1425 }
1426 } else {
1427 formatted
1428 }
1429}
1430
1431/// Parses an integer from a string following PHP's type coercion rules.
1432///
1433/// This is a Rust implementation that matches PHP's behavior. It extracts the
1434/// leading numeric portion of a string:
1435/// - `"42"` → 42
1436/// - `"42abc"` → 42
1437/// - `" 42"` → 42 (leading whitespace is skipped)
1438/// - `"-42"` → -42
1439/// - `"abc"` → 0
1440/// - `""` → 0
1441/// - Hexadecimal (`"0xFF"`) → 0 (not interpreted, stops at 'x')
1442/// - Octal (`"010"`) → 10 (not interpreted as octal)
1443/// - Overflow saturates to `ZendLong::MAX` or `ZendLong::MIN`
1444fn parse_long_from_str(s: &str) -> ZendLong {
1445 let s = s.trim_start();
1446 let bytes = s.as_bytes();
1447 if bytes.is_empty() {
1448 return 0;
1449 }
1450
1451 let mut i = 0;
1452 let mut is_negative = false;
1453
1454 // Handle optional sign
1455 if bytes[i] == b'-' || bytes[i] == b'+' {
1456 is_negative = bytes[i] == b'-';
1457 i += 1;
1458 }
1459
1460 let digits_start = i;
1461
1462 // Collect digits
1463 while i < bytes.len() && bytes[i].is_ascii_digit() {
1464 i += 1;
1465 }
1466
1467 // No digits found
1468 if i == digits_start {
1469 return 0;
1470 }
1471
1472 // Parse the slice, saturating on overflow (matching PHP behavior)
1473 match s[..i].parse::<ZendLong>() {
1474 Ok(n) => n,
1475 Err(_) => {
1476 // Overflow: saturate to max or min depending on sign
1477 if is_negative {
1478 ZendLong::MIN
1479 } else {
1480 ZendLong::MAX
1481 }
1482 }
1483 }
1484}
1485
1486/// Parses a float from a string following PHP's type coercion rules.
1487///
1488/// This is a Rust implementation that matches PHP's behavior. It extracts the
1489/// leading numeric portion of a string:
1490/// - `"3.14"` → 3.14
1491/// - `"3.14abc"` → 3.14
1492/// - `" 3.14"` → 3.14 (leading whitespace is skipped)
1493/// - `"-3.14"` → -3.14
1494/// - `"1e10"` → 1e10 (scientific notation supported)
1495/// - `".5"` → 0.5 (leading decimal point)
1496/// - `"5."` → 5.0 (trailing decimal point)
1497/// - `"abc"` → 0.0
1498/// - `""` → 0.0
1499fn parse_double_from_str(s: &str) -> f64 {
1500 let s = s.trim_start();
1501 let bytes = s.as_bytes();
1502 if bytes.is_empty() {
1503 return 0.0;
1504 }
1505
1506 let mut i = 0;
1507 let mut has_decimal = false;
1508 let mut has_exponent = false;
1509 let mut has_digits = false;
1510
1511 // Handle optional sign
1512 if bytes[i] == b'-' || bytes[i] == b'+' {
1513 i += 1;
1514 }
1515
1516 // Collect digits, decimal point, and exponent
1517 while i < bytes.len() {
1518 let c = bytes[i];
1519 if c.is_ascii_digit() {
1520 has_digits = true;
1521 i += 1;
1522 } else if c == b'.' && !has_decimal && !has_exponent {
1523 has_decimal = true;
1524 i += 1;
1525 } else if (c == b'e' || c == b'E') && !has_exponent && has_digits {
1526 has_exponent = true;
1527 i += 1;
1528 // Handle optional sign after exponent
1529 if i < bytes.len() && (bytes[i] == b'-' || bytes[i] == b'+') {
1530 i += 1;
1531 }
1532 } else {
1533 break;
1534 }
1535 }
1536
1537 // Parse the slice or return 0.0
1538 s[..i].parse().unwrap_or(0.0)
1539}
1540
1541#[cfg(test)]
1542mod type_byte_tests {
1543 use super::*;
1544
1545 #[test]
1546 fn type_predicates_match_from_u32_for_every_zval_type_byte() {
1547 for byte in 0u8..=15 {
1548 let mut zv = std::mem::ManuallyDrop::new(Zval::new());
1549 zv.u1.type_info = u32::from(byte);
1550 let ty = DataType::from_u32(u32::from(byte));
1551 let actual = [
1552 zv.is_long(),
1553 zv.is_null(),
1554 zv.is_true(),
1555 zv.is_false(),
1556 zv.is_bool(),
1557 zv.is_double(),
1558 zv.is_string(),
1559 zv.is_resource(),
1560 zv.is_array(),
1561 zv.is_object(),
1562 zv.is_reference(),
1563 zv.is_indirect(),
1564 zv.is_ptr(),
1565 zv.is_scalar(),
1566 ];
1567 let expected = [
1568 ty == DataType::Long,
1569 ty == DataType::Null,
1570 ty == DataType::True,
1571 ty == DataType::False,
1572 matches!(ty, DataType::True | DataType::False),
1573 ty == DataType::Double,
1574 ty == DataType::String,
1575 ty == DataType::Resource,
1576 ty == DataType::Array,
1577 matches!(ty, DataType::Object(_)),
1578 ty == DataType::Reference,
1579 ty == DataType::Indirect,
1580 ty == DataType::Ptr,
1581 matches!(
1582 ty,
1583 DataType::Long
1584 | DataType::Double
1585 | DataType::String
1586 | DataType::True
1587 | DataType::False
1588 ),
1589 ];
1590 assert_eq!(actual, expected, "type byte {byte}");
1591 }
1592 }
1593}
1594
1595#[cfg(test)]
1596#[cfg(feature = "embed")]
1597#[allow(clippy::unwrap_used, clippy::approx_constant)]
1598mod tests {
1599 use super::*;
1600 use crate::embed::Embed;
1601
1602 #[test]
1603 fn test_zval_null() {
1604 Embed::run(|| {
1605 let zval = Zval::null();
1606 assert!(zval.is_null());
1607 });
1608 }
1609
1610 #[test]
1611 fn binary_slice_should_reject_partial_element() {
1612 Embed::run(|| {
1613 let mut zval = Zval::new();
1614 zval.set_string("1234567", false).unwrap();
1615 assert!(zval.binary_slice::<u64>().is_none());
1616 assert_eq!(zval.binary_slice::<u8>().map(<[u8]>::len), Some(7));
1617 });
1618 }
1619
1620 #[test]
1621 fn binary_slice_should_view_packed_u64() {
1622 Embed::run(|| {
1623 let mut zval = Zval::new();
1624 zval.set_binary(vec![1u64, 2, 3]);
1625 assert_eq!(zval.binary_slice::<u64>(), Some(&[1u64, 2, 3][..]));
1626 assert_eq!(zval.binary::<u64>(), Some(vec![1, 2, 3]));
1627 });
1628 }
1629
1630 #[test]
1631 fn test_is_scalar() {
1632 Embed::run(|| {
1633 // Test scalar types - should return true
1634 let mut zval_long = Zval::new();
1635 zval_long.set_long(42);
1636 assert!(zval_long.is_scalar());
1637
1638 let mut zval_double = Zval::new();
1639 zval_double.set_double(1.5);
1640 assert!(zval_double.is_scalar());
1641
1642 let mut zval_true = Zval::new();
1643 zval_true.set_bool(true);
1644 assert!(zval_true.is_scalar());
1645
1646 let mut zval_false = Zval::new();
1647 zval_false.set_bool(false);
1648 assert!(zval_false.is_scalar());
1649
1650 let mut zval_string = Zval::new();
1651 zval_string
1652 .set_string("hello", false)
1653 .expect("set_string should succeed");
1654 assert!(zval_string.is_scalar());
1655
1656 // Test non-scalar types - should return false
1657 let zval_null = Zval::null();
1658 assert!(!zval_null.is_scalar());
1659
1660 let zval_array = Zval::new_array();
1661 assert!(!zval_array.is_scalar());
1662 });
1663 }
1664
1665 #[test]
1666 fn test_coerce_to_bool() {
1667 Embed::run(|| {
1668 let mut zv = Zval::new();
1669
1670 // === Truthy values ===
1671 // Integers
1672 zv.set_long(42);
1673 assert!(zv.coerce_to_bool(), "(bool)42 should be true");
1674
1675 zv.set_long(1);
1676 assert!(zv.coerce_to_bool(), "(bool)1 should be true");
1677
1678 zv.set_long(-1);
1679 assert!(zv.coerce_to_bool(), "(bool)-1 should be true");
1680
1681 // Floats
1682 zv.set_double(0.1);
1683 assert!(zv.coerce_to_bool(), "(bool)0.1 should be true");
1684
1685 zv.set_double(-0.1);
1686 assert!(zv.coerce_to_bool(), "(bool)-0.1 should be true");
1687
1688 // Strings - non-empty and not "0"
1689 zv.set_string("hello", false).unwrap();
1690 assert!(zv.coerce_to_bool(), "(bool)'hello' should be true");
1691
1692 zv.set_string("1", false).unwrap();
1693 assert!(zv.coerce_to_bool(), "(bool)'1' should be true");
1694
1695 // PHP: (bool)"false" is true (non-empty string)
1696 zv.set_string("false", false).unwrap();
1697 assert!(zv.coerce_to_bool(), "(bool)'false' should be true");
1698
1699 // PHP: (bool)"true" is true
1700 zv.set_string("true", false).unwrap();
1701 assert!(zv.coerce_to_bool(), "(bool)'true' should be true");
1702
1703 // PHP: (bool)" " (space) is true
1704 zv.set_string(" ", false).unwrap();
1705 assert!(zv.coerce_to_bool(), "(bool)' ' should be true");
1706
1707 // PHP: (bool)"00" is true (only exactly "0" is false)
1708 zv.set_string("00", false).unwrap();
1709 assert!(zv.coerce_to_bool(), "(bool)'00' should be true");
1710
1711 zv.set_bool(true);
1712 assert!(zv.coerce_to_bool(), "(bool)true should be true");
1713
1714 // === Falsy values ===
1715 // Integer zero
1716 zv.set_long(0);
1717 assert!(!zv.coerce_to_bool(), "(bool)0 should be false");
1718
1719 // Float zero (both positive and negative)
1720 zv.set_double(0.0);
1721 assert!(!zv.coerce_to_bool(), "(bool)0.0 should be false");
1722
1723 zv.set_double(-0.0);
1724 assert!(!zv.coerce_to_bool(), "(bool)-0.0 should be false");
1725
1726 // Empty string
1727 zv.set_string("", false).unwrap();
1728 assert!(!zv.coerce_to_bool(), "(bool)'' should be false");
1729
1730 // String "0" - the only non-empty falsy string
1731 zv.set_string("0", false).unwrap();
1732 assert!(!zv.coerce_to_bool(), "(bool)'0' should be false");
1733
1734 zv.set_bool(false);
1735 assert!(!zv.coerce_to_bool(), "(bool)false should be false");
1736
1737 // Null
1738 let null_zv = Zval::null();
1739 assert!(!null_zv.coerce_to_bool(), "(bool)null should be false");
1740
1741 // Empty array
1742 let empty_array = Zval::new_array();
1743 assert!(!empty_array.coerce_to_bool(), "(bool)[] should be false");
1744 });
1745 }
1746
1747 #[test]
1748 fn test_coerce_to_string() {
1749 Embed::run(|| {
1750 let mut zv = Zval::new();
1751
1752 // === Integer to string ===
1753 zv.set_long(42);
1754 assert_eq!(zv.coerce_to_string(), Some("42".to_string()));
1755
1756 zv.set_long(-123);
1757 assert_eq!(zv.coerce_to_string(), Some("-123".to_string()));
1758
1759 zv.set_long(0);
1760 assert_eq!(zv.coerce_to_string(), Some("0".to_string()));
1761
1762 // === Float to string ===
1763 zv.set_double(3.14);
1764 assert_eq!(zv.coerce_to_string(), Some("3.14".to_string()));
1765
1766 zv.set_double(-3.14);
1767 assert_eq!(zv.coerce_to_string(), Some("-3.14".to_string()));
1768
1769 zv.set_double(0.0);
1770 assert_eq!(zv.coerce_to_string(), Some("0".to_string()));
1771
1772 zv.set_double(1.0);
1773 assert_eq!(zv.coerce_to_string(), Some("1".to_string()));
1774
1775 zv.set_double(1.5);
1776 assert_eq!(zv.coerce_to_string(), Some("1.5".to_string()));
1777
1778 zv.set_double(100.0);
1779 assert_eq!(zv.coerce_to_string(), Some("100".to_string()));
1780
1781 // Special float values (uppercase like PHP)
1782 zv.set_double(f64::INFINITY);
1783 assert_eq!(zv.coerce_to_string(), Some("INF".to_string()));
1784
1785 zv.set_double(f64::NEG_INFINITY);
1786 assert_eq!(zv.coerce_to_string(), Some("-INF".to_string()));
1787
1788 zv.set_double(f64::NAN);
1789 assert_eq!(zv.coerce_to_string(), Some("NAN".to_string()));
1790
1791 // Scientific notation thresholds (PHP uses E notation at exp >= 14 or <= -5)
1792 // PHP: (string)1e13 -> "10000000000000"
1793 zv.set_double(1e13);
1794 assert_eq!(zv.coerce_to_string(), Some("10000000000000".to_string()));
1795
1796 // PHP: (string)1e14 -> "1.0E+14"
1797 zv.set_double(1e14);
1798 assert_eq!(zv.coerce_to_string(), Some("1.0E+14".to_string()));
1799
1800 // PHP: (string)1e52 -> "1.0E+52"
1801 zv.set_double(1e52);
1802 assert_eq!(zv.coerce_to_string(), Some("1.0E+52".to_string()));
1803
1804 // PHP: (string)0.0001 -> "0.0001"
1805 zv.set_double(0.0001);
1806 assert_eq!(zv.coerce_to_string(), Some("0.0001".to_string()));
1807
1808 // PHP: (string)1e-5 -> "1.0E-5"
1809 zv.set_double(1e-5);
1810 assert_eq!(zv.coerce_to_string(), Some("1.0E-5".to_string()));
1811
1812 // Negative scientific notation
1813 // PHP: (string)(-1e52) -> "-1.0E+52"
1814 zv.set_double(-1e52);
1815 assert_eq!(zv.coerce_to_string(), Some("-1.0E+52".to_string()));
1816
1817 // PHP: (string)(-1e-10) -> "-1.0E-10"
1818 zv.set_double(-1e-10);
1819 assert_eq!(zv.coerce_to_string(), Some("-1.0E-10".to_string()));
1820
1821 // === Boolean to string ===
1822 // PHP: (string)true -> "1"
1823 zv.set_bool(true);
1824 assert_eq!(zv.coerce_to_string(), Some("1".to_string()));
1825
1826 // PHP: (string)false -> ""
1827 zv.set_bool(false);
1828 assert_eq!(zv.coerce_to_string(), Some(String::new()));
1829
1830 // === Null to string ===
1831 // PHP: (string)null -> ""
1832 let null_zv = Zval::null();
1833 assert_eq!(null_zv.coerce_to_string(), Some(String::new()));
1834
1835 // === String unchanged ===
1836 zv.set_string("hello", false).unwrap();
1837 assert_eq!(zv.coerce_to_string(), Some("hello".to_string()));
1838
1839 // === Array cannot be converted ===
1840 let arr_zv = Zval::new_array();
1841 assert_eq!(arr_zv.coerce_to_string(), None);
1842 });
1843 }
1844
1845 #[test]
1846 fn test_coerce_to_long() {
1847 Embed::run(|| {
1848 let mut zv = Zval::new();
1849
1850 // === Integer unchanged ===
1851 zv.set_long(42);
1852 assert_eq!(zv.coerce_to_long(), Some(42));
1853
1854 zv.set_long(-42);
1855 assert_eq!(zv.coerce_to_long(), Some(-42));
1856
1857 zv.set_long(0);
1858 assert_eq!(zv.coerce_to_long(), Some(0));
1859
1860 // === Float truncated (towards zero) ===
1861 // PHP: (int)3.14 -> 3
1862 zv.set_double(3.14);
1863 assert_eq!(zv.coerce_to_long(), Some(3));
1864
1865 // PHP: (int)3.99 -> 3
1866 zv.set_double(3.99);
1867 assert_eq!(zv.coerce_to_long(), Some(3));
1868
1869 // PHP: (int)-3.14 -> -3
1870 zv.set_double(-3.14);
1871 assert_eq!(zv.coerce_to_long(), Some(-3));
1872
1873 // PHP: (int)-3.99 -> -3
1874 zv.set_double(-3.99);
1875 assert_eq!(zv.coerce_to_long(), Some(-3));
1876
1877 // PHP: (int)0.0 -> 0
1878 zv.set_double(0.0);
1879 assert_eq!(zv.coerce_to_long(), Some(0));
1880
1881 // PHP: (int)-0.0 -> 0
1882 zv.set_double(-0.0);
1883 assert_eq!(zv.coerce_to_long(), Some(0));
1884
1885 // === Boolean to integer ===
1886 // PHP: (int)true -> 1
1887 zv.set_bool(true);
1888 assert_eq!(zv.coerce_to_long(), Some(1));
1889
1890 // PHP: (int)false -> 0
1891 zv.set_bool(false);
1892 assert_eq!(zv.coerce_to_long(), Some(0));
1893
1894 // === Null to integer ===
1895 // PHP: (int)null -> 0
1896 let null_zv = Zval::null();
1897 assert_eq!(null_zv.coerce_to_long(), Some(0));
1898
1899 // === String to integer (leading numeric portion) ===
1900 // PHP: (int)"123" -> 123
1901 zv.set_string("123", false).unwrap();
1902 assert_eq!(zv.coerce_to_long(), Some(123));
1903
1904 // PHP: (int)" 123" -> 123
1905 zv.set_string(" 123", false).unwrap();
1906 assert_eq!(zv.coerce_to_long(), Some(123));
1907
1908 // PHP: (int)"123abc" -> 123
1909 zv.set_string("123abc", false).unwrap();
1910 assert_eq!(zv.coerce_to_long(), Some(123));
1911
1912 // PHP: (int)"abc123" -> 0
1913 zv.set_string("abc123", false).unwrap();
1914 assert_eq!(zv.coerce_to_long(), Some(0));
1915
1916 // PHP: (int)"" -> 0
1917 zv.set_string("", false).unwrap();
1918 assert_eq!(zv.coerce_to_long(), Some(0));
1919
1920 // PHP: (int)"0" -> 0
1921 zv.set_string("0", false).unwrap();
1922 assert_eq!(zv.coerce_to_long(), Some(0));
1923
1924 // PHP: (int)"-0" -> 0
1925 zv.set_string("-0", false).unwrap();
1926 assert_eq!(zv.coerce_to_long(), Some(0));
1927
1928 // PHP: (int)"+123" -> 123
1929 zv.set_string("+123", false).unwrap();
1930 assert_eq!(zv.coerce_to_long(), Some(123));
1931
1932 // PHP: (int)" -456" -> -456
1933 zv.set_string(" -456", false).unwrap();
1934 assert_eq!(zv.coerce_to_long(), Some(-456));
1935
1936 // PHP: (int)"3.14" -> 3 (stops at decimal point)
1937 zv.set_string("3.14", false).unwrap();
1938 assert_eq!(zv.coerce_to_long(), Some(3));
1939
1940 // PHP: (int)"3.99" -> 3
1941 zv.set_string("3.99", false).unwrap();
1942 assert_eq!(zv.coerce_to_long(), Some(3));
1943
1944 // PHP: (int)"-3.99" -> -3
1945 zv.set_string("-3.99", false).unwrap();
1946 assert_eq!(zv.coerce_to_long(), Some(-3));
1947
1948 // PHP: (int)"abc" -> 0
1949 zv.set_string("abc", false).unwrap();
1950 assert_eq!(zv.coerce_to_long(), Some(0));
1951
1952 // === Array cannot be converted ===
1953 let arr_zv = Zval::new_array();
1954 assert_eq!(arr_zv.coerce_to_long(), None);
1955 });
1956 }
1957
1958 #[test]
1959 fn test_coerce_to_double() {
1960 Embed::run(|| {
1961 let mut zv = Zval::new();
1962
1963 // === Float unchanged ===
1964 zv.set_double(3.14);
1965 assert!((zv.coerce_to_double().unwrap() - 3.14).abs() < f64::EPSILON);
1966
1967 zv.set_double(-3.14);
1968 assert!((zv.coerce_to_double().unwrap() - (-3.14)).abs() < f64::EPSILON);
1969
1970 zv.set_double(0.0);
1971 assert!((zv.coerce_to_double().unwrap() - 0.0).abs() < f64::EPSILON);
1972
1973 // === Integer to float ===
1974 // PHP: (float)42 -> 42.0
1975 zv.set_long(42);
1976 assert!((zv.coerce_to_double().unwrap() - 42.0).abs() < f64::EPSILON);
1977
1978 // PHP: (float)-42 -> -42.0
1979 zv.set_long(-42);
1980 assert!((zv.coerce_to_double().unwrap() - (-42.0)).abs() < f64::EPSILON);
1981
1982 // PHP: (float)0 -> 0.0
1983 zv.set_long(0);
1984 assert!((zv.coerce_to_double().unwrap() - 0.0).abs() < f64::EPSILON);
1985
1986 // === Boolean to float ===
1987 // PHP: (float)true -> 1.0
1988 zv.set_bool(true);
1989 assert!((zv.coerce_to_double().unwrap() - 1.0).abs() < f64::EPSILON);
1990
1991 // PHP: (float)false -> 0.0
1992 zv.set_bool(false);
1993 assert!((zv.coerce_to_double().unwrap() - 0.0).abs() < f64::EPSILON);
1994
1995 // === Null to float ===
1996 // PHP: (float)null -> 0.0
1997 let null_zv = Zval::null();
1998 assert!((null_zv.coerce_to_double().unwrap() - 0.0).abs() < f64::EPSILON);
1999
2000 // === String to float ===
2001 // PHP: (float)"3.14" -> 3.14
2002 zv.set_string("3.14", false).unwrap();
2003 assert!((zv.coerce_to_double().unwrap() - 3.14).abs() < f64::EPSILON);
2004
2005 // PHP: (float)" 3.14" -> 3.14
2006 zv.set_string(" 3.14", false).unwrap();
2007 assert!((zv.coerce_to_double().unwrap() - 3.14).abs() < f64::EPSILON);
2008
2009 // PHP: (float)"3.14abc" -> 3.14
2010 zv.set_string("3.14abc", false).unwrap();
2011 assert!((zv.coerce_to_double().unwrap() - 3.14).abs() < f64::EPSILON);
2012
2013 // PHP: (float)"abc3.14" -> 0.0
2014 zv.set_string("abc3.14", false).unwrap();
2015 assert!((zv.coerce_to_double().unwrap() - 0.0).abs() < f64::EPSILON);
2016
2017 // PHP: (float)"" -> 0.0
2018 zv.set_string("", false).unwrap();
2019 assert!((zv.coerce_to_double().unwrap() - 0.0).abs() < f64::EPSILON);
2020
2021 // PHP: (float)"0" -> 0.0
2022 zv.set_string("0", false).unwrap();
2023 assert!((zv.coerce_to_double().unwrap() - 0.0).abs() < f64::EPSILON);
2024
2025 // PHP: (float)"0.0" -> 0.0
2026 zv.set_string("0.0", false).unwrap();
2027 assert!((zv.coerce_to_double().unwrap() - 0.0).abs() < f64::EPSILON);
2028
2029 // PHP: (float)"+3.14" -> 3.14
2030 zv.set_string("+3.14", false).unwrap();
2031 assert!((zv.coerce_to_double().unwrap() - 3.14).abs() < f64::EPSILON);
2032
2033 // PHP: (float)" -3.14" -> -3.14
2034 zv.set_string(" -3.14", false).unwrap();
2035 assert!((zv.coerce_to_double().unwrap() - (-3.14)).abs() < f64::EPSILON);
2036
2037 // Scientific notation
2038 // PHP: (float)"1e10" -> 1e10
2039 zv.set_string("1e10", false).unwrap();
2040 assert!((zv.coerce_to_double().unwrap() - 1e10).abs() < 1.0);
2041
2042 // PHP: (float)"1E10" -> 1e10
2043 zv.set_string("1E10", false).unwrap();
2044 assert!((zv.coerce_to_double().unwrap() - 1e10).abs() < 1.0);
2045
2046 // PHP: (float)"1.5e-3" -> 0.0015
2047 zv.set_string("1.5e-3", false).unwrap();
2048 assert!((zv.coerce_to_double().unwrap() - 0.0015).abs() < f64::EPSILON);
2049
2050 // PHP: (float)".5" -> 0.5
2051 zv.set_string(".5", false).unwrap();
2052 assert!((zv.coerce_to_double().unwrap() - 0.5).abs() < f64::EPSILON);
2053
2054 // PHP: (float)"5." -> 5.0
2055 zv.set_string("5.", false).unwrap();
2056 assert!((zv.coerce_to_double().unwrap() - 5.0).abs() < f64::EPSILON);
2057
2058 // PHP: (float)"abc" -> 0.0
2059 zv.set_string("abc", false).unwrap();
2060 assert!((zv.coerce_to_double().unwrap() - 0.0).abs() < f64::EPSILON);
2061
2062 // === Array cannot be converted ===
2063 let arr_zv = Zval::new_array();
2064 assert_eq!(arr_zv.coerce_to_double(), None);
2065 });
2066 }
2067
2068 #[test]
2069 fn test_parse_long_from_str() {
2070 use crate::ffi::zend_long as ZendLong;
2071
2072 // Basic cases
2073 assert_eq!(parse_long_from_str("42"), 42);
2074 assert_eq!(parse_long_from_str("0"), 0);
2075 assert_eq!(parse_long_from_str("-42"), -42);
2076 assert_eq!(parse_long_from_str("+42"), 42);
2077
2078 // Leading/trailing content
2079 assert_eq!(parse_long_from_str("42abc"), 42);
2080 assert_eq!(parse_long_from_str(" 42"), 42);
2081 assert_eq!(parse_long_from_str("\t\n42"), 42);
2082 assert_eq!(parse_long_from_str(" -42"), -42);
2083 assert_eq!(parse_long_from_str("42.5"), 42); // stops at decimal point
2084
2085 // Non-numeric strings
2086 assert_eq!(parse_long_from_str("abc"), 0);
2087 assert_eq!(parse_long_from_str(""), 0);
2088 assert_eq!(parse_long_from_str(" "), 0);
2089 assert_eq!(parse_long_from_str("-"), 0);
2090 assert_eq!(parse_long_from_str("+"), 0);
2091 assert_eq!(parse_long_from_str("abc123"), 0);
2092
2093 // Edge cases matching PHP behavior:
2094 // - Hexadecimal: PHP's (int)"0xFF" returns 0 (stops at 'x')
2095 assert_eq!(parse_long_from_str("0xFF"), 0);
2096 assert_eq!(parse_long_from_str("0x10"), 0);
2097
2098 // - Octal notation is NOT interpreted, just reads leading digits
2099 assert_eq!(parse_long_from_str("010"), 10); // not 8
2100
2101 // - Binary notation is NOT interpreted
2102 assert_eq!(parse_long_from_str("0b101"), 0);
2103
2104 // Overflow tests - saturates to max/min
2105 assert_eq!(
2106 parse_long_from_str("99999999999999999999999999"),
2107 ZendLong::MAX
2108 );
2109 assert_eq!(
2110 parse_long_from_str("-99999999999999999999999999"),
2111 ZendLong::MIN
2112 );
2113
2114 // Large but valid numbers
2115 assert_eq!(parse_long_from_str("9223372036854775807"), ZendLong::MAX); // i64::MAX
2116 assert_eq!(parse_long_from_str("-9223372036854775808"), ZendLong::MIN); // i64::MIN
2117 }
2118
2119 #[test]
2120 fn test_parse_double_from_str() {
2121 // Basic cases
2122 assert!((parse_double_from_str("3.14") - 3.14).abs() < f64::EPSILON);
2123 assert!((parse_double_from_str("0.0") - 0.0).abs() < f64::EPSILON);
2124 assert!((parse_double_from_str("-3.14") - (-3.14)).abs() < f64::EPSILON);
2125 assert!((parse_double_from_str("+3.14") - 3.14).abs() < f64::EPSILON);
2126 assert!((parse_double_from_str(".5") - 0.5).abs() < f64::EPSILON);
2127 assert!((parse_double_from_str("5.") - 5.0).abs() < f64::EPSILON);
2128
2129 // Scientific notation
2130 assert!((parse_double_from_str("1e10") - 1e10).abs() < 1.0);
2131 assert!((parse_double_from_str("1E10") - 1e10).abs() < 1.0);
2132 assert!((parse_double_from_str("1.5e-3") - 1.5e-3).abs() < f64::EPSILON);
2133 assert!((parse_double_from_str("1.5E+3") - 1500.0).abs() < f64::EPSILON);
2134 assert!((parse_double_from_str("-1.5e2") - (-150.0)).abs() < f64::EPSILON);
2135
2136 // Leading/trailing content
2137 assert!((parse_double_from_str("3.14abc") - 3.14).abs() < f64::EPSILON);
2138 assert!((parse_double_from_str(" 3.14") - 3.14).abs() < f64::EPSILON);
2139 assert!((parse_double_from_str("\t\n3.14") - 3.14).abs() < f64::EPSILON);
2140 assert!((parse_double_from_str("1e10xyz") - 1e10).abs() < 1.0);
2141
2142 // Non-numeric strings
2143 assert!((parse_double_from_str("abc") - 0.0).abs() < f64::EPSILON);
2144 assert!((parse_double_from_str("") - 0.0).abs() < f64::EPSILON);
2145 assert!((parse_double_from_str(" ") - 0.0).abs() < f64::EPSILON);
2146 assert!((parse_double_from_str("-") - 0.0).abs() < f64::EPSILON);
2147 assert!((parse_double_from_str("e10") - 0.0).abs() < f64::EPSILON); // no digits before e
2148
2149 // Integer values
2150 assert!((parse_double_from_str("42") - 42.0).abs() < f64::EPSILON);
2151 assert!((parse_double_from_str("-42") - (-42.0)).abs() < f64::EPSILON);
2152
2153 // Edge cases:
2154 // - Hexadecimal: not supported, returns 0
2155 assert!((parse_double_from_str("0xFF") - 0.0).abs() < f64::EPSILON);
2156
2157 // - Multiple decimal points: stops at second
2158 assert!((parse_double_from_str("1.2.3") - 1.2).abs() < f64::EPSILON);
2159
2160 // - Multiple exponents: stops at second e
2161 assert!((parse_double_from_str("1e2e3") - 100.0).abs() < f64::EPSILON);
2162 }
2163
2164 #[test]
2165 fn test_php_float_to_string() {
2166 // Basic decimal values
2167 assert_eq!(php_float_to_string(3.14), "3.14");
2168 assert_eq!(php_float_to_string(42.0), "42");
2169 assert_eq!(php_float_to_string(-3.14), "-3.14");
2170 assert_eq!(php_float_to_string(0.0), "0");
2171
2172 // Large numbers use scientific notation with uppercase E
2173 // PHP: (string)(float)'999...9' -> "1.0E+52"
2174 assert_eq!(php_float_to_string(1e52), "1.0E+52");
2175 assert_eq!(php_float_to_string(1e20), "1.0E+20");
2176 assert_eq!(php_float_to_string(1e14), "1.0E+14");
2177
2178 // Very small numbers also use scientific notation (at exp <= -5)
2179 assert_eq!(php_float_to_string(1e-10), "1.0E-10");
2180 assert_eq!(php_float_to_string(1e-5), "1.0E-5");
2181 assert_eq!(php_float_to_string(0.00001), "1.0E-5");
2182
2183 // Numbers that don't need scientific notation
2184 assert_eq!(php_float_to_string(1e13), "10000000000000");
2185 assert_eq!(php_float_to_string(0.001), "0.001");
2186 assert_eq!(php_float_to_string(0.0001), "0.0001"); // 1e-4 is decimal
2187 }
2188
2189 #[test]
2190 fn test_set_binary_interned_flag() {
2191 Embed::run(|| {
2192 // Regression for #729: packed length 0 or 1 returns an interned
2193 // permanent static; flagging the zval as refcounted corrupts the
2194 // heap on drop. Mirrors Zval::set_zend_string's GC_IMMUTABLE check.
2195
2196 let assert_interned = |zv: &Zval, label: &str| {
2197 let flags = ZvalTypeFlags::from_bits_truncate(unsafe { zv.u1.type_info });
2198 assert!(
2199 flags.contains(ZvalTypeFlags::String),
2200 "{label}: expected String type, got {flags:?}",
2201 );
2202 assert!(
2203 !flags.contains(ZvalTypeFlags::RefCounted),
2204 "{label}: interned string zval must not carry RefCounted, got {flags:?}",
2205 );
2206 };
2207
2208 let mut zv = Zval::new();
2209 zv.set_binary::<u8>(vec![]);
2210 assert_eq!(zv.get_type(), DataType::String);
2211 assert_interned(&zv, "empty u8");
2212
2213 let mut zv = Zval::new();
2214 zv.set_binary::<u8>(vec![42u8]);
2215 assert_eq!(zv.get_type(), DataType::String);
2216 assert_interned(&zv, "single u8");
2217 assert_eq!(zv.binary::<u8>(), Some(vec![42u8]));
2218
2219 let mut zv = Zval::new();
2220 zv.set_binary::<u32>(Vec::<u32>::new());
2221 assert_eq!(zv.get_type(), DataType::String);
2222 assert_interned(&zv, "empty u32");
2223
2224 // A packed payload of 2+ bytes must still take the refcounted path.
2225 let mut zv = Zval::new();
2226 zv.set_binary::<u32>(vec![42u32]);
2227 let flags = ZvalTypeFlags::from_bits_truncate(unsafe { zv.u1.type_info });
2228 assert!(
2229 flags.contains(ZvalTypeFlags::RefCounted),
2230 "multi-byte packed string must be refcounted, got {flags:?}",
2231 );
2232 });
2233 }
2234
2235 #[test]
2236 fn test_binary_roundtrip_and_size_mismatch() {
2237 Embed::run(|| {
2238 // Roundtrip at the native widths used by Pack.
2239 let u32s = vec![1u32, 0xdead_beef, 42u32, 0u32];
2240 let mut zv = Zval::new();
2241 zv.set_binary::<u32>(u32s.clone());
2242 assert_eq!(zv.binary::<u32>(), Some(u32s));
2243
2244 let u16s = vec![0x1234u16, 0xabcdu16, 0xffffu16];
2245 let mut zv = Zval::new();
2246 zv.set_binary::<u16>(u16s.clone());
2247 assert_eq!(zv.binary::<u16>(), Some(u16s));
2248
2249 // Empty string roundtrips cleanly at every width.
2250 for width in [1usize, 2, 4, 8] {
2251 let mut zv = Zval::new();
2252 match width {
2253 1 => zv.set_binary::<u8>(vec![]),
2254 2 => zv.set_binary::<u16>(vec![]),
2255 4 => zv.set_binary::<u32>(vec![]),
2256 8 => zv.set_binary::<u64>(vec![]),
2257 _ => unreachable!(),
2258 }
2259 assert_eq!(zv.binary::<u8>(), Some(vec![]));
2260 }
2261
2262 // A byte count that isn't a multiple of size_of::<T>() must return
2263 // None rather than silently dropping trailing bytes. 5 bytes of u8
2264 // should unpack as u8 (len=5) but refuse to unpack as u32 (5 % 4 != 0).
2265 let mut zv = Zval::new();
2266 zv.set_binary::<u8>(vec![1u8, 2, 3, 4, 5]);
2267 assert_eq!(zv.binary::<u8>(), Some(vec![1u8, 2, 3, 4, 5]));
2268 assert!(zv.binary::<u32>().is_none());
2269 assert!(zv.binary::<u16>().is_none());
2270 assert!(zv.binary::<u64>().is_none());
2271
2272 // Single-byte payload must fail cleanly for any width > 1.
2273 let mut zv = Zval::new();
2274 zv.set_binary::<u8>(vec![42u8]);
2275 assert_eq!(zv.binary::<u8>(), Some(vec![42u8]));
2276 assert!(zv.binary::<u16>().is_none());
2277 assert!(zv.binary::<u32>().is_none());
2278 });
2279 }
2280}