Skip to main content

speedyspec_php_serialize/
value.rs

1//! PHP values as `serialize()` writes them.
2
3/// An array key or property name.
4#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5pub enum PhpKey {
6    Int(i64),
7    Str(Vec<u8>),
8}
9
10/// A value in PHP's serialize format.
11#[derive(Debug, Clone)]
12pub enum PhpValue {
13    Null,
14    Bool(bool),
15    Int(i64),
16    Float(f64),
17    Str(Vec<u8>),
18    Array(Vec<(PhpKey, PhpValue)>),
19    Object {
20        class: String,
21        properties: Vec<(PhpKey, PhpValue)>,
22    },
23    /// `C:`: a `Serializable` object's own payload.
24    Custom {
25        class: String,
26        data: Vec<u8>,
27    },
28    /// `E:`: an enum case.
29    Enum {
30        class: String,
31        case: String,
32    },
33    /// `R:n`: a PHP reference to slot `n`.
34    Ref(u32),
35    /// `r:n`: the same object as slot `n`.
36    ObjectRef(u32),
37}
38
39impl PartialEq for PhpValue {
40    /// Floats compare bitwise, so `NAN` equals itself and `-0.0` differs from `0.0`.
41    fn eq(&self, other: &Self) -> bool {
42        use PhpValue::*;
43        match (self, other) {
44            (Null, Null) => true,
45            (Bool(a), Bool(b)) => a == b,
46            (Int(a), Int(b)) => a == b,
47            (Float(a), Float(b)) => a.to_bits() == b.to_bits(),
48            (Str(a), Str(b)) => a == b,
49            (Array(a), Array(b)) => a == b,
50            (
51                Object {
52                    class: c1,
53                    properties: p1,
54                },
55                Object {
56                    class: c2,
57                    properties: p2,
58                },
59            ) => c1 == c2 && p1 == p2,
60            (
61                Custom {
62                    class: c1,
63                    data: d1,
64                },
65                Custom {
66                    class: c2,
67                    data: d2,
68                },
69            ) => c1 == c2 && d1 == d2,
70            (
71                Enum {
72                    class: c1,
73                    case: k1,
74                },
75                Enum {
76                    class: c2,
77                    case: k2,
78                },
79            ) => c1 == c2 && k1 == k2,
80            (Ref(a), Ref(b)) => a == b,
81            (ObjectRef(a), ObjectRef(b)) => a == b,
82            _ => false,
83        }
84    }
85}
86
87impl PhpValue {
88    /// True when an object (`O:`, `C:`, `E:` or `r:`) is anywhere inside.
89    pub fn contains_object(&self) -> bool {
90        match self {
91            PhpValue::Object { .. }
92            | PhpValue::Custom { .. }
93            | PhpValue::Enum { .. }
94            | PhpValue::ObjectRef(_) => true,
95            PhpValue::Array(items) => items.iter().any(|(_, v)| v.contains_object()),
96            _ => false,
97        }
98    }
99}