Skip to main content

serde_php/
lib.rs

1#![forbid(missing_docs)]
2#![allow(clippy::float_cmp)]
3//! # PHP serialization format support for serde
4//!
5//! PHP uses a custom serialization format through its
6//! [`serialize()`](https://www.php.net/manual/en/function.serialize.php)
7//! and
8//! [`unserialize()`](https://www.php.net/manual/en/function.unserialize.php)
9//! methods. This crate adds partial support for this format using `serde`.
10//!
11//! An overview of the format can be seen at
12//! <https://stackoverflow.com/questions/14297926/structure-of-a-serialized-php-string>,
13//! details are available at
14//! <http://www.phpinternalsbook.com/php5/classes_objects/serialization.html>.
15//!
16//! ## What is supported?
17//!
18//! * Basic and compound types:
19//!
20//!   | PHP type                | Rust type                                             |
21//!   | ---                     | ---                                                   |
22//!   | boolean                 | `bool`                                                |
23//!   | integer                 | `i64` (automatic conversion to other types supported) |
24//!   | float                   | `f64` (automatic conversion to `f32` supported)       |
25//!   | strings                 | `Vec<u8>` (PHP strings are not UTF8)                  |
26//!   | null                    | decoded as `None`                                     |
27//!   | array (non-associative) | tuple `struct`s or `Vec<_>`                           |
28//!   | array (associative)     | regular `struct`s or `HashMap<_, _>`                  |
29//!
30//! * Rust `String`s are transparently UTF8-converted to PHP bytestrings.
31//!
32//! ### Out-of-order arrays
33//!
34//! PHP arrays can be created "out of order", as they store every array index as an
35//! explicit integer in the array. Thus the following code
36//!
37//! ```php
38//! $arr = array();
39//! $arr[0] = "zero";
40//! $arr[3] = "three";
41//! $arr[2] = "two";
42//! $arr[1] = "one";
43//! ```
44//!
45//! results in an array that would be equivalent to ["zero", "one", "two", "three"],
46//! at least when iterated over.
47//!
48//! Because deserialization does not buffer values, these arrays cannot be directly
49//! serialized into a `Vec`. Instead they should be deserialized into a map, which
50//! can then be turned into a `Vec` if desired.
51//!
52//! A second concern are "holes" in the array, e.g. if the entry with key `1` is
53//! missing. How to fill these is typically up to the user.
54//!
55//! The helper function `deserialize_unordered_array` can be used with serde's
56//! `deserialize_with` decorator to automatically buffer and order things, as well
57//! as plugging holes by closing any gaps.
58//!
59//! ## What is missing?
60//!
61//! * PHP objects
62//! * Non-string/numeric array keys, except when deserializing into a `HashMap`
63//! * Mixed arrays. Array keys are assumed to always have the same key type
64//!   (Note: If this is required, consider extending this library with a variant
65//!    type).
66//!
67//! ## Example use
68//!
69//! Given an example data structure storing a session token using the following
70//! PHP code
71//!
72//! ```php
73//! <?php
74//! $serialized = serialize(array("user", "", array()));
75//! echo($serialized);
76//! ```
77//!
78//! and thus the following output
79//!
80//! ```text
81//! a:3:{i:0;s:4:"user";i:1;s:0:"";i:2;a:0:{}}
82//! ```
83//!
84//! , the data can be reconstructed using the following rust code:
85//!
86//! ```rust
87//! use serde::Deserialize;
88//! use serde_php::from_bytes;
89//!
90//! #[derive(Debug, Deserialize, Eq, PartialEq)]
91//! struct Data(Vec<u8>, Vec<u8>, SubData);
92//!
93//! #[derive(Debug, Deserialize, Eq, PartialEq)]
94//! struct SubData();
95//!
96//! let input = br#"a:3:{i:0;s:4:"user";i:1;s:0:"";i:2;a:0:{}}"#;
97//! assert_eq!(
98//!     from_bytes::<Data>(input).unwrap(),
99//!     Data(b"user".to_vec(), b"".to_vec(), SubData())
100//! );
101//! ```
102//!
103//! Likewise, structs are supported as well, if the PHP arrays use keys:
104//!
105//! ```php
106//! <?php
107//! $serialized = serialize(
108//!     array("foo" => true,
109//!           "bar" => "xyz",
110//!           "sub" => array("x" => 42))
111//! );
112//! echo($serialized);
113//! ```
114//!
115//! In Rust:
116//!
117//! ```rust
118//!# use serde::Deserialize;
119//!# use serde_php::from_bytes;
120//! #[derive(Debug, Deserialize, Eq, PartialEq)]
121//! struct Outer {
122//!     foo: bool,
123//!     bar: String,
124//!     sub: Inner,
125//! }
126//!
127//! #[derive(Debug, Deserialize, Eq, PartialEq)]
128//! struct Inner {
129//!     x: i64,
130//! }
131//!
132//! let input = br#"a:3:{s:3:"foo";b:1;s:3:"bar";s:3:"xyz";s:3:"sub";a:1:{s:1:"x";i:42;}}"#;
133//! let expected = Outer {
134//!     foo: true,
135//!     bar: "xyz".to_owned(),
136//!     sub: Inner { x: 42 },
137//! };
138//!
139//! let deserialized: Outer = from_bytes(input).expect("deserialization failed");
140//!
141//! assert_eq!(deserialized, expected);
142//! ```
143//!
144//! ### Optional values
145//!
146//! Missing values can be left optional, as in this example:
147//!
148//! ```php
149//! <?php
150//! $location_a = array();
151//! $location_b = array("province" => "Newfoundland and Labrador, CA");
152//! $location_c = array("postalcode" => "90002",
153//!                     "country" => "United States of America");
154//! echo(serialize($location_a) . "\n");
155//! echo(serialize($location_b) . "\n");
156//! # -> a:1:{s:8:"province";s:29:"Newfoundland and Labrador, CA";}
157//! echo(serialize($location_c) . "\n");
158//! # -> a:2:{s:10:"postalcode";s:5:"90002";s:7:"country";
159//! #         s:24:"United States of America";}
160//! ```
161//!
162//! The following declaration of `Location` will be able to parse all three
163//! example inputs.
164//!
165//! ```rust
166//!# use serde::Deserialize;
167//! #[derive(Debug, Deserialize, Eq, PartialEq)]
168//! struct Location {
169//!     province: Option<String>,
170//!     postalcode: Option<String>,
171//!     country: Option<String>,
172//! }
173//! ```
174//!
175//! # Full roundtrip example
176//!
177//! ```rust
178//! use serde::{Deserialize, Serialize};
179//! use serde_php::{to_vec, from_bytes};
180//!
181//! #[derive(Debug, Deserialize, Eq, PartialEq, Serialize)]
182//! struct UserProfile {
183//!     id: u32,
184//!     name: String,
185//!     tags: Vec<String>,
186//! }
187//!
188//! let orig = UserProfile {
189//!     id: 42,
190//!     name: "Bob".to_owned(),
191//!     tags: vec!["foo".to_owned(), "bar".to_owned()],
192//! };
193//!
194//! let serialized = to_vec(&orig).expect("serialization failed");
195//! let expected = br#"a:3:{s:2:"id";i:42;s:4:"name";s:3:"Bob";s:4:"tags";a:2:{i:0;s:3:"foo";i:1;s:3:"bar";}}"#;
196//! assert_eq!(serialized, &expected[..]);
197//!
198//! let profile: UserProfile = from_bytes(&serialized).expect("deserialization failed");
199//! assert_eq!(profile, orig);
200//! ```
201
202mod de;
203mod error;
204mod ser;
205
206pub use de::{deserialize_unordered_array, from_bytes};
207pub use error::{Error, Result};
208pub use ser::{to_vec, to_writer};
209
210#[cfg(test)]
211mod tests {
212    use super::{from_bytes, to_vec};
213    use proptest::prelude::any;
214    use proptest::proptest;
215    use serde::{Deserialize, Serialize};
216    use std::collections::HashMap;
217
218    macro_rules! roundtrip {
219        ($ty:ty, $value:expr) => {
220            let val = $value;
221
222            let serialized = to_vec(&val).expect("Serialization failed");
223            eprintln!("{}", String::from_utf8_lossy(serialized.as_slice()));
224
225            let deserialized: $ty =
226                from_bytes(serialized.as_slice()).expect("Deserialization failed");
227
228            assert_eq!(deserialized, val);
229        };
230    }
231
232    #[test]
233    fn roundtrip_newtype() {
234        #[derive(Debug, Deserialize, Eq, PartialEq, Serialize)]
235        struct MyNewtype(i32);
236
237        roundtrip!(MyNewtype, MyNewtype(0));
238        roundtrip!(MyNewtype, MyNewtype(1));
239        roundtrip!(MyNewtype, MyNewtype(-1));
240    }
241
242    proptest! {
243        #[test]
244        fn roundtrip_unit(v in any::<()>()) {
245            roundtrip!((), v);
246        }
247
248        #[test]
249        fn roundtrip_bool(v in any::<bool>()) {
250            roundtrip!(bool, v);
251        }
252
253        #[test]
254        fn roundtrip_u8(v in any::<u8>()) {
255            roundtrip!(u8, v);
256        }
257
258        #[test]
259        fn roundtrip_u16(v in any::<u16>()) {
260            roundtrip!(u16, v);
261        }
262
263        #[test]
264        fn roundtrip_u32(v in any::<u32>()) {
265            roundtrip!(u32, v);
266        }
267
268        #[test]
269        fn roundtrip_u64(v in 0..(std::i64::MAX as u64)) {
270            roundtrip!(u64, v);
271        }
272
273        #[test]
274        fn roundtrip_i8(v in any::<i8>()) {
275            roundtrip!(i8, v);
276        }
277
278        #[test]
279        fn roundtrip_i16(v in any::<i16>()) {
280            roundtrip!(i16, v);
281        }
282
283        #[test]
284        fn roundtrip_i32(v in any::<i32>()) {
285            roundtrip!(i32, v);
286        }
287
288        #[test]
289        fn roundtrip_i64(v in any::<i64>()) {
290            roundtrip!(i64, v);
291        }
292
293        #[test]
294        fn roundtrip_f32(v in any::<f32>()) {
295            roundtrip!(f32, v);
296        }
297
298        #[test]
299        fn roundtrip_f64(v in any::<f64>()) {
300            roundtrip!(f64, v);
301        }
302
303        #[test]
304        fn roundtrip_bytes(v in any::<Vec<u8>>()) {
305            roundtrip!(Vec<u8>, v);
306        }
307
308        #[test]
309        fn roundtrip_char(v in any::<char>()) {
310            roundtrip!(char, v);
311        }
312
313        #[test]
314        fn roundtrip_string(v in any::<String>()) {
315            roundtrip!(String, v);
316        }
317
318        #[test]
319        fn roundtrip_option(v in any::<Option<i32>>()) {
320            roundtrip!(Option<i32>, v);
321        }
322
323        #[test]
324        fn roundtrip_same_type_tuple(v in any::<(u32, u32)>()) {
325            roundtrip!((u32, u32), v);
326        }
327
328        #[test]
329        fn roundtrip_mixed_type_tuple(v in any::<(String, i32)>()) {
330            roundtrip!((String, i32), v);
331        }
332
333        #[test]
334        fn roundtrip_string_string_hashmap(v in proptest::collection::hash_map(any::<String>(), any::<String>(), 0..100)) {
335            roundtrip!(HashMap<String, String>, v);
336        }
337    }
338}