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