Skip to main content

ext_php_rs/types/
mod.rs

1//! Types defined by the Zend engine used in PHP.
2//!
3//! Generally, it is easier to work directly with Rust types, converting into
4//! these PHP types when required.
5
6pub mod array;
7mod callable;
8mod class_object;
9mod iterable;
10mod iterator;
11mod long;
12mod object;
13mod payload;
14mod php_ref;
15mod separated;
16mod string;
17mod zval;
18
19pub use array::{ArrayKey, Entry, OccupiedEntry, VacantEntry, ZendEmptyArray, ZendHashTable};
20pub use callable::ZendCallable;
21pub use class_object::ZendClassObject;
22pub use iterable::Iterable;
23pub use iterator::ZendIterator;
24pub use long::ZendLong;
25pub use object::{PropertyQuery, ZendObject};
26pub use payload::{BorrowError, ClassRef, ClassRefMut};
27pub use php_ref::PhpRef;
28pub use separated::Separated;
29pub use string::ZendStr;
30pub use zval::Zval;
31
32use crate::{
33    convert::FromZval,
34    error::{Error, Result},
35    flags::DataType,
36};
37
38into_zval!(f32, set_double, Double);
39into_zval!(f64, set_double, Double);
40into_zval!(bool, set_bool, Bool);
41
42try_from_zval!(bool, bool, Bool);
43
44impl FromZval<'_> for f64 {
45    const TYPE: DataType = DataType::Double;
46
47    #[allow(
48        clippy::cast_precision_loss,
49        reason = "PHP casts an int given for a float parameter the same way"
50    )]
51    fn from_zval(zval: &Zval) -> Option<Self> {
52        zval.double().or_else(|| zval.long().map(|v| v as f64))
53    }
54}
55
56impl TryFrom<Zval> for f64 {
57    type Error = Error;
58
59    fn try_from(value: Zval) -> Result<Self> {
60        Self::from_zval(&value).ok_or(Error::ZvalConversion(value.get_type()))
61    }
62}
63
64impl FromZval<'_> for f32 {
65    const TYPE: DataType = DataType::Double;
66
67    fn from_zval(zval: &Zval) -> Option<Self> {
68        #[allow(clippy::cast_possible_truncation)]
69        f64::from_zval(zval).map(|v| v as f32)
70    }
71}
72
73#[cfg(test)]
74#[cfg(feature = "embed")]
75mod tests {
76    use super::*;
77
78    #[test]
79    fn floats_accept_a_php_int() {
80        assert_eq!(f64::from_zval(&Zval::from(2)), Some(2.0));
81        assert_eq!(f32::from_zval(&Zval::from(2)), Some(2.0));
82    }
83}