Skip to main content

speedyspec_php_serialize/
write.rs

1//! `serialize()`.
2
3use crate::float::php_float;
4use crate::{PhpKey, PhpValue};
5
6fn string(out: &mut Vec<u8>, tag: &str, bytes: &[u8]) {
7    out.extend_from_slice(format!("{tag}:{}:\"", bytes.len()).as_bytes());
8    out.extend_from_slice(bytes);
9    out.push(b'"');
10}
11
12fn key(out: &mut Vec<u8>, k: &PhpKey) {
13    match k {
14        PhpKey::Int(i) => out.extend_from_slice(format!("i:{i};").as_bytes()),
15        PhpKey::Str(s) => {
16            string(out, "s", s);
17            out.push(b';');
18        }
19    }
20}
21
22fn members(out: &mut Vec<u8>, items: &[(PhpKey, PhpValue)]) {
23    out.extend_from_slice(format!("{}:{{", items.len()).as_bytes());
24    for (k, v) in items {
25        key(out, k);
26        write(out, v);
27    }
28    out.push(b'}');
29}
30
31fn write(out: &mut Vec<u8>, v: &PhpValue) {
32    match v {
33        PhpValue::Null => out.extend_from_slice(b"N;"),
34        PhpValue::Bool(b) => out.extend_from_slice(if *b { b"b:1;" } else { b"b:0;" }),
35        PhpValue::Int(i) => out.extend_from_slice(format!("i:{i};").as_bytes()),
36        PhpValue::Float(f) => out.extend_from_slice(format!("d:{};", php_float(*f)).as_bytes()),
37        PhpValue::Str(s) => {
38            string(out, "s", s);
39            out.push(b';');
40        }
41        PhpValue::Array(items) => {
42            out.extend_from_slice(b"a:");
43            members(out, items);
44        }
45        PhpValue::Object { class, properties } => {
46            string(out, "O", class.as_bytes());
47            out.push(b':');
48            members(out, properties);
49        }
50        PhpValue::Custom { class, data } => {
51            string(out, "C", class.as_bytes());
52            out.extend_from_slice(format!(":{}:{{", data.len()).as_bytes());
53            out.extend_from_slice(data);
54            out.push(b'}');
55        }
56        PhpValue::Enum { class, case } => {
57            string(out, "E", format!("{class}:{case}").as_bytes());
58            out.push(b';');
59        }
60        PhpValue::Ref(n) => out.extend_from_slice(format!("R:{n};").as_bytes()),
61        PhpValue::ObjectRef(n) => out.extend_from_slice(format!("r:{n};").as_bytes()),
62    }
63}
64
65/// PHP's `serialize()`.
66pub fn serialize(value: &PhpValue) -> Vec<u8> {
67    let mut out = Vec::new();
68    write(&mut out, value);
69    out
70}