speedyspec_php_serialize/
convert.rs1use std::collections::HashMap;
4use std::fmt;
5use std::rc::Rc;
6
7use speedyspec_hooks::{Key, Value};
8
9use crate::{PhpKey, PhpValue};
10
11#[derive(Debug, Clone, PartialEq)]
13pub struct OpaquePhpValue(pub PhpValue);
14
15#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum ConvertError {
18 Foreign,
20}
21
22impl fmt::Display for ConvertError {
23 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24 f.write_str("the value holds something that has no serialized form")
25 }
26}
27
28impl std::error::Error for ConvertError {}
29
30fn number<'a>(value: &'a PhpValue, slots: &mut Vec<&'a PhpValue>) {
32 if matches!(value, PhpValue::Ref(_) | PhpValue::ObjectRef(_)) {
33 return;
34 }
35 slots.push(value);
36 if let PhpValue::Array(items)
37 | PhpValue::Object {
38 properties: items, ..
39 } = value
40 {
41 for (_, v) in items {
42 number(v, slots);
43 }
44 }
45}
46
47struct Converter<'a> {
48 slots: Vec<&'a PhpValue>,
49 next: usize,
50 objects: HashMap<usize, Rc<OpaquePhpValue>>,
51 ancestors: Vec<usize>,
52}
53
54struct Whole;
56
57fn string(s: &[u8]) -> Value {
58 match std::str::from_utf8(s) {
59 Ok(t) => Value::Str(t.to_string()),
60 Err(_) => Value::Bytes(s.to_vec()),
61 }
62}
63
64impl<'a> Converter<'a> {
65 fn convert(&mut self, value: &'a PhpValue) -> Result<Value, Whole> {
66 match value {
67 PhpValue::Ref(n) => {
68 let n = *n as usize;
69 if self.ancestors.contains(&n) {
70 return Err(Whole);
71 }
72 let target = *self.slots.get(n.wrapping_sub(1)).ok_or(Whole)?;
73 Converter {
75 slots: Vec::new(),
76 next: 0,
77 objects: HashMap::new(),
78 ancestors: Vec::new(),
79 }
80 .detached(target)
81 }
82 PhpValue::ObjectRef(n) => self
83 .objects
84 .get(&(*n as usize))
85 .cloned()
86 .map(|rc| Value::Opaque(rc))
87 .ok_or(Whole),
88 _ => {
89 self.next += 1;
90 let slot = self.next;
91 match value {
92 PhpValue::Null => Ok(Value::Null),
93 PhpValue::Bool(b) => Ok(Value::Bool(*b)),
94 PhpValue::Int(i) => Ok(Value::Int(*i)),
95 PhpValue::Float(f) => Ok(Value::Float(*f)),
96 PhpValue::Str(s) => Ok(string(s)),
97 PhpValue::Array(items) => {
98 self.ancestors.push(slot);
99 let mut out = Vec::with_capacity(items.len());
100 for (k, v) in items {
101 let key = match k {
102 PhpKey::Int(i) => Key::Int(*i),
103 PhpKey::Str(s) => {
104 Key::Str(String::from_utf8(s.clone()).map_err(|_| Whole)?)
105 }
106 };
107 out.push((key, self.convert(v)?));
108 }
109 self.ancestors.pop();
110 Ok(Value::Array(out))
111 }
112 PhpValue::Object { properties, .. } => {
113 let mut members = Vec::new();
115 for (_, v) in properties {
116 number(v, &mut members);
117 }
118 self.next += members.len();
119 let rc = Rc::new(OpaquePhpValue(value.clone()));
120 self.objects.insert(slot, rc.clone());
121 Ok(Value::Opaque(rc))
122 }
123 PhpValue::Custom { .. } | PhpValue::Enum { .. } => {
124 let rc = Rc::new(OpaquePhpValue(value.clone()));
125 self.objects.insert(slot, rc.clone());
126 Ok(Value::Opaque(rc))
127 }
128 PhpValue::Ref(_) | PhpValue::ObjectRef(_) => unreachable!("handled above"),
129 }
130 }
131 }
132 }
133
134 fn detached(mut self, value: &'a PhpValue) -> Result<Value, Whole> {
135 number(value, &mut self.slots);
136 self.convert(value)
137 }
138}
139
140pub fn to_hook_value(value: &PhpValue) -> Value {
143 let mut converter = Converter {
144 slots: Vec::new(),
145 next: 0,
146 objects: HashMap::new(),
147 ancestors: Vec::new(),
148 };
149 number(value, &mut converter.slots);
150 converter
151 .convert(value)
152 .unwrap_or_else(|_| Value::Opaque(Rc::new(OpaquePhpValue(value.clone()))))
153}
154
155pub fn from_hook_value(value: &Value) -> Result<PhpValue, ConvertError> {
157 let value = value.read();
158 Ok(match &*value {
159 Value::Null => PhpValue::Null,
160 Value::Bool(b) => PhpValue::Bool(*b),
161 Value::Int(i) => PhpValue::Int(*i),
162 Value::Float(f) => PhpValue::Float(*f),
163 Value::Str(s) => PhpValue::Str(s.as_bytes().to_vec()),
164 Value::Bytes(b) => PhpValue::Str(b.clone()),
165 Value::Array(items) => PhpValue::Array(
166 items
167 .iter()
168 .map(|(k, v)| {
169 let key = match k {
170 Key::Int(i) => PhpKey::Int(*i),
171 Key::Str(s) => PhpKey::Str(s.as_bytes().to_vec()),
172 };
173 Ok((key, from_hook_value(v)?))
174 })
175 .collect::<Result<_, ConvertError>>()?,
176 ),
177 Value::Opaque(any) => any
178 .downcast_ref::<OpaquePhpValue>()
179 .map(|o| o.0.clone())
180 .ok_or(ConvertError::Foreign)?,
181 })
182}