1use std::fmt::Write as _;
5
6use crate::error::{Error, Result};
7
8const MAX_DEPTH: usize = 128;
10
11#[derive(Debug, Clone, PartialEq)]
17pub enum Value {
18 Null,
20 Bool(bool),
22 Int(i64),
24 Float(f64),
26 String(String),
28 Bytes(Vec<u8>),
31 List(Vec<Value>),
33 Map(Vec<(Key, Value)>),
35 Object {
40 class: String,
42 properties: Vec<(Key, Value)>,
44 },
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Hash)]
49pub enum Key {
50 Int(i64),
52 String(String),
54}
55
56impl Value {
57 pub fn list<I, V>(items: I) -> Self
59 where
60 I: IntoIterator<Item = V>,
61 V: Into<Value>,
62 {
63 Value::List(items.into_iter().map(Into::into).collect())
64 }
65
66 pub fn map<I, K, V>(entries: I) -> Self
68 where
69 I: IntoIterator<Item = (K, V)>,
70 K: Into<Key>,
71 V: Into<Value>,
72 {
73 Value::Map(
74 entries
75 .into_iter()
76 .map(|(k, v)| (k.into(), v.into()))
77 .collect(),
78 )
79 }
80
81 pub fn is_null(&self) -> bool {
83 matches!(self, Value::Null)
84 }
85
86 pub fn as_bool(&self) -> Option<bool> {
88 match self {
89 Value::Bool(b) => Some(*b),
90 _ => None,
91 }
92 }
93
94 pub fn as_i64(&self) -> Option<i64> {
96 match self {
97 Value::Int(i) => Some(*i),
98 _ => None,
99 }
100 }
101
102 pub fn as_f64(&self) -> Option<f64> {
104 match self {
105 Value::Float(f) => Some(*f),
106 _ => None,
107 }
108 }
109
110 pub fn as_str(&self) -> Option<&str> {
112 match self {
113 Value::String(s) => Some(s),
114 _ => None,
115 }
116 }
117
118 pub fn as_list(&self) -> Option<&[Value]> {
120 match self {
121 Value::List(items) => Some(items),
122 _ => None,
123 }
124 }
125
126 pub fn get(&self, key: &str) -> Option<&Value> {
128 let entries = match self {
129 Value::Map(entries) => entries,
130 Value::Object { properties, .. } => properties,
131 _ => return None,
132 };
133 entries
134 .iter()
135 .find(|(k, _)| matches!(k, Key::String(s) if s == key))
136 .map(|(_, v)| v)
137 }
138}
139
140impl From<&str> for Key {
141 fn from(s: &str) -> Self {
142 Key::String(s.to_owned())
143 }
144}
145
146impl From<String> for Key {
147 fn from(s: String) -> Self {
148 Key::String(s)
149 }
150}
151
152impl From<i64> for Key {
153 fn from(i: i64) -> Self {
154 Key::Int(i)
155 }
156}
157
158impl From<i32> for Key {
159 fn from(i: i32) -> Self {
160 Key::Int(i64::from(i))
161 }
162}
163
164impl From<bool> for Value {
165 fn from(b: bool) -> Self {
166 Value::Bool(b)
167 }
168}
169
170macro_rules! value_from_int {
171 ($($t:ty),*) => {$(
172 impl From<$t> for Value {
173 fn from(i: $t) -> Self {
174 Value::Int(i64::from(i))
175 }
176 }
177 )*};
178}
179value_from_int!(i8, i16, i32, i64, u8, u16, u32);
180
181impl From<f32> for Value {
182 fn from(f: f32) -> Self {
183 Value::Float(f64::from(f))
184 }
185}
186
187impl From<f64> for Value {
188 fn from(f: f64) -> Self {
189 Value::Float(f)
190 }
191}
192
193impl From<&str> for Value {
194 fn from(s: &str) -> Self {
195 Value::String(s.to_owned())
196 }
197}
198
199impl From<String> for Value {
200 fn from(s: String) -> Self {
201 Value::String(s)
202 }
203}
204
205impl<T: Into<Value>> From<Vec<T>> for Value {
206 fn from(items: Vec<T>) -> Self {
207 Value::list(items)
208 }
209}
210
211impl<T: Into<Value>> From<Option<T>> for Value {
212 fn from(v: Option<T>) -> Self {
213 v.map_or(Value::Null, Into::into)
214 }
215}
216
217pub(crate) fn serialize(value: &Value) -> Result<Vec<u8>> {
219 let mut out = Vec::new();
220 encode(&mut out, value)?;
221 Ok(out)
222}
223
224fn encode(out: &mut Vec<u8>, value: &Value) -> Result<()> {
225 match value {
226 Value::Null => out.extend_from_slice(b"N;"),
227 Value::Bool(b) => out.extend_from_slice(if *b { b"b:1;" } else { b"b:0;" }),
228 Value::Int(i) => push_fmt(out, format_args!("i:{i};")),
229 Value::Float(f) => push_fmt(out, format_args!("d:{};", format_float(*f))),
230 Value::String(s) => encode_string(out, s.as_bytes()),
231 Value::Bytes(b) => encode_string(out, b),
232 Value::List(items) => {
233 push_fmt(out, format_args!("a:{}:{{", items.len()));
234 for (i, item) in items.iter().enumerate() {
235 push_fmt(out, format_args!("i:{i};"));
236 encode(out, item)?;
237 }
238 out.push(b'}');
239 }
240 Value::Map(entries) => {
241 push_fmt(out, format_args!("a:{}:{{", entries.len()));
242 for (key, item) in entries {
243 match key {
244 Key::Int(i) => push_fmt(out, format_args!("i:{i};")),
245 Key::String(s) => encode_string(out, s.as_bytes()),
246 }
247 encode(out, item)?;
248 }
249 out.push(b'}');
250 }
251 Value::Object { .. } => return Err(Error::Serialize),
252 }
253 Ok(())
254}
255
256fn push_fmt(out: &mut Vec<u8>, args: std::fmt::Arguments<'_>) {
257 let mut s = String::new();
258 let _ = s.write_fmt(args);
260 out.extend_from_slice(s.as_bytes());
261}
262
263fn encode_string(out: &mut Vec<u8>, bytes: &[u8]) {
264 push_fmt(out, format_args!("s:{}:\"", bytes.len()));
265 out.extend_from_slice(bytes);
266 out.extend_from_slice(b"\";");
267}
268
269fn format_float(f: f64) -> String {
273 if f.is_nan() {
274 return "NAN".into();
275 }
276 if f.is_infinite() {
277 return if f > 0.0 { "INF" } else { "-INF" }.into();
278 }
279 if f == 0.0 {
280 return if f.is_sign_negative() { "-0" } else { "0" }.into();
281 }
282
283 let sci = format!("{:e}", f.abs());
285 let (mantissa, exp) = sci.split_once('e').unwrap_or((&sci, "0"));
286 let digits: String = mantissa.chars().filter(|c| *c != '.').collect();
287 let exp: i32 = exp.parse().unwrap_or(0);
288 let decpt = exp + 1;
290
291 let mut out = String::new();
292 if f < 0.0 {
293 out.push('-');
294 }
295
296 let (first, rest) = digits.split_at(1);
297 if !(-3..=17).contains(&decpt) {
298 out.push_str(first);
299 out.push('.');
300 out.push_str(if rest.is_empty() { "0" } else { rest });
301 let _ = write!(out, "E{}{}", if exp < 0 { '-' } else { '+' }, exp.abs());
302 } else if decpt <= 0 {
303 out.push_str("0.");
304 out.push_str(&"0".repeat((-decpt) as usize));
305 out.push_str(&digits);
306 } else {
307 let int_len = decpt as usize;
308 if digits.len() <= int_len {
309 out.push_str(&digits);
310 out.push_str(&"0".repeat(int_len - digits.len()));
311 } else {
312 out.push_str(&digits[..int_len]);
313 out.push('.');
314 out.push_str(&digits[int_len..]);
315 }
316 }
317 out
318}
319
320pub(crate) fn unserialize(data: &[u8]) -> Result<Value> {
322 let mut d = Decoder { data, pos: 0 };
323 let value = d.value(0)?;
324 if d.pos != data.len() {
325 return Err(Error::Unserialize);
326 }
327 Ok(value)
328}
329
330struct Decoder<'a> {
331 data: &'a [u8],
332 pos: usize,
333}
334
335impl<'a> Decoder<'a> {
336 fn remaining(&self) -> usize {
337 self.data.len() - self.pos
338 }
339
340 fn expect(&mut self, lit: &[u8]) -> Result<()> {
341 if self.data[self.pos..].starts_with(lit) {
342 self.pos += lit.len();
343 Ok(())
344 } else {
345 Err(Error::Unserialize)
346 }
347 }
348
349 fn until(&mut self, sep: u8) -> Result<&'a [u8]> {
351 let rest = &self.data[self.pos..];
352 let n = rest
353 .iter()
354 .position(|&b| b == sep)
355 .ok_or(Error::Unserialize)?;
356 self.pos += n + 1;
357 Ok(&rest[..n])
358 }
359
360 fn int(&mut self, sep: u8) -> Result<i64> {
361 let raw = self.until(sep)?;
362 std::str::from_utf8(raw)
363 .ok()
364 .and_then(|s| s.parse::<i64>().ok())
365 .ok_or(Error::Unserialize)
366 }
367
368 fn len(&mut self, sep: u8) -> Result<usize> {
369 usize::try_from(self.int(sep)?).map_err(|_| Error::Unserialize)
370 }
371
372 fn value(&mut self, depth: usize) -> Result<Value> {
373 if depth > MAX_DEPTH {
374 return Err(Error::Unserialize);
375 }
376 match *self.data.get(self.pos).ok_or(Error::Unserialize)? {
377 b'N' => {
378 self.expect(b"N;")?;
379 Ok(Value::Null)
380 }
381 b'b' => {
382 self.expect(b"b:")?;
383 match self.until(b';')? {
384 b"1" => Ok(Value::Bool(true)),
385 b"0" => Ok(Value::Bool(false)),
386 _ => Err(Error::Unserialize),
387 }
388 }
389 b'i' => {
390 self.expect(b"i:")?;
391 Ok(Value::Int(self.int(b';')?))
392 }
393 b'd' => {
394 self.expect(b"d:")?;
395 Ok(Value::Float(parse_float(self.until(b';')?)?))
396 }
397 b's' => Ok(string_value(self.string()?)),
398 b'a' => {
399 self.expect(b"a:")?;
400 let count = self.len(b':')?;
401 let entries = self.entries(count, depth)?;
402 Ok(assemble(entries))
403 }
404 b'O' => self.object(depth),
405 _ => Err(Error::Unserialize),
406 }
407 }
408
409 fn string(&mut self) -> Result<&'a [u8]> {
411 self.expect(b"s:")?;
412 let len = self.len(b':')?;
413 self.expect(b"\"")?;
414 if len > self.remaining() {
415 return Err(Error::Unserialize);
416 }
417 let bytes = &self.data[self.pos..self.pos + len];
418 self.pos += len;
419 self.expect(b"\";")?;
420 Ok(bytes)
421 }
422
423 fn key(&mut self) -> Result<Key> {
424 match self.data.get(self.pos) {
425 Some(b'i') => {
426 self.expect(b"i:")?;
427 Ok(Key::Int(self.int(b';')?))
428 }
429 Some(b's') => {
430 let bytes = self.string()?;
431 String::from_utf8(bytes.to_vec())
432 .map(Key::String)
433 .map_err(|_| Error::Unserialize)
434 }
435 _ => Err(Error::Unserialize),
436 }
437 }
438
439 fn entries(&mut self, count: usize, depth: usize) -> Result<Vec<(Key, Value)>> {
441 self.expect(b"{")?;
442 let mut entries = Vec::with_capacity(count.min(self.remaining() / 4));
445 for _ in 0..count {
446 let key = self.key()?;
447 let value = self.value(depth + 1)?;
448 entries.push((key, value));
449 }
450 self.expect(b"}")?;
451 Ok(entries)
452 }
453
454 fn object(&mut self, depth: usize) -> Result<Value> {
456 self.expect(b"O:")?;
457 let len = self.len(b':')?;
458 self.expect(b"\"")?;
459 if len > self.remaining() {
460 return Err(Error::Unserialize);
461 }
462 let class = String::from_utf8(self.data[self.pos..self.pos + len].to_vec())
463 .map_err(|_| Error::Unserialize)?;
464 self.pos += len;
465 self.expect(b"\":")?;
466 let count = self.len(b':')?;
467 let properties = self.entries(count, depth)?;
468 Ok(Value::Object { class, properties })
469 }
470}
471
472fn string_value(bytes: &[u8]) -> Value {
473 match std::str::from_utf8(bytes) {
474 Ok(s) => Value::String(s.to_owned()),
475 Err(_) => Value::Bytes(bytes.to_vec()),
476 }
477}
478
479fn parse_float(raw: &[u8]) -> Result<f64> {
480 match raw {
481 b"INF" => return Ok(f64::INFINITY),
482 b"-INF" => return Ok(f64::NEG_INFINITY),
483 b"NAN" => return Ok(f64::NAN),
484 _ => {}
485 }
486 if raw.is_empty()
488 || !raw
489 .iter()
490 .all(|b| b.is_ascii_digit() || matches!(b, b'+' | b'-' | b'.' | b'e' | b'E'))
491 {
492 return Err(Error::Unserialize);
493 }
494 std::str::from_utf8(raw)
495 .ok()
496 .and_then(|s| s.parse::<f64>().ok())
497 .ok_or(Error::Unserialize)
498}
499
500fn assemble(entries: Vec<(Key, Value)>) -> Value {
502 let is_list = entries
503 .iter()
504 .enumerate()
505 .all(|(i, (k, _))| matches!(k, Key::Int(n) if usize::try_from(*n) == Ok(i)));
506 if is_list {
507 Value::List(entries.into_iter().map(|(_, v)| v).collect())
508 } else {
509 Value::Map(entries)
510 }
511}
512
513#[cfg(test)]
514mod tests {
515 use super::*;
516
517 fn ser(v: &Value) -> String {
518 String::from_utf8(serialize(v).unwrap()).unwrap()
519 }
520
521 fn unser(s: &str) -> Result<Value> {
522 unserialize(s.as_bytes())
523 }
524
525 #[test]
528 fn serializes_scalars_like_php() {
529 assert_eq!(ser(&Value::Null), "N;");
530 assert_eq!(ser(&true.into()), "b:1;");
531 assert_eq!(ser(&false.into()), "b:0;");
532 assert_eq!(ser(&Value::Int(-42)), "i:-42;");
533 assert_eq!(ser(&Value::Int(i64::MIN)), "i:-9223372036854775808;");
534 assert_eq!(ser(&"héllo \"w\"".into()), "s:10:\"héllo \"w\"\";");
535 assert_eq!(
536 serialize(&Value::Bytes(vec![0, 0xff])).unwrap(),
537 b"s:2:\"\0\xff\";"
538 );
539 }
540
541 #[test]
542 fn serializes_floats_like_php() {
543 let cases = [
544 (2.0, "d:2;"),
545 (2.5, "d:2.5;"),
546 (0.1, "d:0.1;"),
547 (0.1 + 0.2, "d:0.30000000000000004;"),
548 (100.0, "d:100;"),
549 (0.5, "d:0.5;"),
550 (1e14, "d:100000000000000;"),
551 (1e15, "d:1000000000000000;"),
552 (1e16, "d:10000000000000000;"),
553 (1e17, "d:1.0E+17;"),
554 (1e18, "d:1.0E+18;"),
555 (123456789012345678.0, "d:1.2345678901234568E+17;"),
556 (0.0001, "d:0.0001;"),
557 (0.00009, "d:9.0E-5;"),
558 (0.00001, "d:1.0E-5;"),
559 (1.5e-7, "d:1.5E-7;"),
560 (-1.5e25, "d:-1.5E+25;"),
561 (5e-324, "d:5.0E-324;"),
562 (f64::MAX, "d:1.7976931348623157E+308;"),
563 (-0.0, "d:-0;"),
564 (f64::INFINITY, "d:INF;"),
565 (f64::NEG_INFINITY, "d:-INF;"),
566 (f64::NAN, "d:NAN;"),
567 ];
568 for (f, want) in cases {
569 assert_eq!(ser(&Value::Float(f)), want, "{f:?}");
570 }
571 }
572
573 #[test]
574 fn serializes_arrays_like_php() {
575 assert_eq!(ser(&Value::List(vec![])), "a:0:{}");
576 assert_eq!(
577 ser(&Value::list([Value::from("x"), 1.into(), true.into()])),
578 r#"a:3:{i:0;s:1:"x";i:1;i:1;i:2;b:1;}"#
579 );
580 let map = Value::Map(vec![(Key::Int(5), "a".into()), ("x".into(), Value::Null)]);
582 assert_eq!(ser(&map), r#"a:2:{i:5;s:1:"a";s:1:"x";N;}"#);
583 }
584
585 #[test]
586 fn objects_are_not_serializable() {
587 let object = Value::Object {
588 class: "stdClass".into(),
589 properties: vec![],
590 };
591 assert_eq!(serialize(&object), Err(Error::Serialize));
592 assert_eq!(serialize(&Value::list([object])), Err(Error::Serialize));
594 }
595
596 #[test]
597 fn unserializes_php_output() {
598 assert_eq!(unser("N;"), Ok(Value::Null));
599 assert_eq!(unser("b:1;"), Ok(Value::Bool(true)));
600 assert_eq!(unser("i:7;"), Ok(Value::Int(7)));
601 assert_eq!(unser("i:-9223372036854775808;"), Ok(Value::Int(i64::MIN)));
602 assert_eq!(unser("d:2.5;"), Ok(Value::Float(2.5)));
603 assert_eq!(unser("d:1.0E+25;"), Ok(Value::Float(1e25)));
604 assert_eq!(unser("d:2;"), Ok(Value::Float(2.0)));
605 assert_eq!(unser("d:INF;"), Ok(Value::Float(f64::INFINITY)));
606 assert_eq!(unser("d:-INF;"), Ok(Value::Float(f64::NEG_INFINITY)));
607 assert!(matches!(unser("d:NAN;"), Ok(Value::Float(f)) if f.is_nan()));
608 assert_eq!(
610 unser("s:14:\"héllo \"world\"\";"),
611 Ok(Value::String("héllo \"world\"".into()))
612 );
613 assert_eq!(unser("s:0:\"\";"), Ok(Value::String(String::new())));
614 assert_eq!(
615 unser("s:2:\"\u{0}\u{0}\";"),
616 Ok(Value::String("\0\0".into()))
617 );
618 assert_eq!(
619 unserialize(b"s:2:\"\xff\xfe\";"),
620 Ok(Value::Bytes(vec![0xff, 0xfe]))
621 );
622 }
623
624 #[test]
625 fn unserializes_lists_and_maps() {
626 assert_eq!(unser("a:0:{}"), Ok(Value::List(vec![])));
627 assert_eq!(
628 unser(r#"a:2:{i:0;s:1:"x";i:1;a:1:{i:0;N;}}"#),
629 Ok(Value::list([Value::from("x"), Value::list([Value::Null])]))
630 );
631 for src in [
633 r#"a:2:{i:1;s:1:"a";i:0;s:1:"b";}"#,
634 r#"a:1:{i:1;s:1:"a";}"#,
635 r#"a:1:{s:1:"0";s:1:"a";}"#,
636 ] {
637 assert!(matches!(unser(src), Ok(Value::Map(_))), "{src}");
638 }
639 assert_eq!(
640 unser(r#"a:2:{s:1:"b";i:1;s:1:"a";i:2;}"#),
641 Ok(Value::Map(vec![
642 ("b".into(), Value::Int(1)),
643 ("a".into(), Value::Int(2)),
644 ]))
645 );
646 }
647
648 #[test]
649 fn unserializes_objects_without_instantiating() {
650 let v = unser(r#"O:8:"stdClass":2:{s:1:"a";i:1;s:1:"b";s:3:"two";}"#).unwrap();
651 assert_eq!(
652 v,
653 Value::Object {
654 class: "stdClass".into(),
655 properties: vec![("a".into(), Value::Int(1)), ("b".into(), "two".into())],
656 }
657 );
658 assert!(matches!(
660 unser(r#"O:13:"Evil\Gadget\X":0:{}"#),
661 Ok(Value::Object { class, .. }) if class == r"Evil\Gadget\X"
662 ));
663 }
664
665 #[test]
666 fn round_trips() {
667 let values = [
668 Value::Null,
669 Value::Int(0),
670 Value::Float(-3.25),
671 Value::Float(1e300),
672 Value::from("plain"),
673 Value::Bytes(vec![0, 1, 2, 0xff]),
674 Value::map([
675 ("user", Value::from("alice")),
676 ("tags", Value::list(["x", "y"])),
677 ("meta", Value::Null),
678 ]),
679 Value::Map(vec![(3.into(), Value::list([1.5, 2.5]))]),
680 ];
681 for v in values {
682 assert_eq!(unserialize(&serialize(&v).unwrap()), Ok(v));
683 }
684 }
685
686 #[test]
687 fn rejects_malformed_input() {
688 let bad = [
689 "",
690 "x",
691 "X;",
692 "N",
693 "N:",
694 "b:",
695 "b:2;",
696 "b:1",
697 "i:;",
698 "i:abc;",
699 "i:5",
700 "i:9223372036854775808;",
701 "d:;",
702 "d:abc;",
703 "d:inf;",
704 "d:nan;",
705 "d:infinity;",
706 "d:5",
707 "s:abc:\"x\";",
708 "s:-1:\"\";",
709 "s:2:ab\";",
710 "s:2:\"ab",
711 "s:2:\"ab\"",
712 "s:5:\"ab\";",
713 "s:99999999999999999999:\"ab\";",
714 "a:x:{}",
715 "a:-1:{}",
716 "a:1:",
717 "a:1:{i:0;}",
718 "a:2:{i:0;b:1;}",
719 "a:1:{i:0;b:1;",
720 "a:1:{b:1;b:1;}",
721 "a:1:{d:1.5;b:1;}",
722 "a:1:{N;b:1;}",
723 "O:abc:\"x\":0:{}",
724 "O:8:\"stdClass\"",
725 "O:3:abc\":1:{}",
726 "O:3:\"abc\":x:{}",
727 "O:99:\"abc\":0:{}",
728 "S:1:\"a\";",
730 "C:3:\"Foo\":0:{}",
731 "r:1;",
732 "R:1;",
733 "E:7:\"Foo:Bar\";",
734 ];
735 for src in bad {
736 assert_eq!(unser(src), Err(Error::Unserialize), "{src:?}");
737 }
738 }
739
740 #[test]
741 fn rejects_trailing_data() {
742 assert_eq!(unser("N;N;"), Err(Error::Unserialize));
743 assert_eq!(unser("i:1;x"), Err(Error::Unserialize));
744 }
745
746 #[test]
747 fn rejects_non_utf8_keys_and_class_names() {
748 assert_eq!(
749 unserialize(b"a:1:{s:1:\"\xff\";N;}"),
750 Err(Error::Unserialize)
751 );
752 assert_eq!(unserialize(b"O:1:\"\xff\":0:{}"), Err(Error::Unserialize));
753 }
754
755 #[test]
756 fn nesting_depth_is_limited_without_overflowing_the_stack() {
757 let nested = |depth: usize| {
758 let mut s = "a:1:{i:0;".repeat(depth);
759 s.push_str("N;");
760 s.push_str(&"}".repeat(depth));
761 s
762 };
763 assert!(unser(&nested(MAX_DEPTH)).is_ok());
764 assert_eq!(unser(&nested(MAX_DEPTH + 1)), Err(Error::Unserialize));
765 assert_eq!(unser(&nested(100_000)), Err(Error::Unserialize));
766 }
767
768 #[test]
769 fn hostile_element_counts_do_not_allocate_or_loop() {
770 assert_eq!(unser("a:9223372036854775807:{}"), Err(Error::Unserialize));
771 assert_eq!(unser("a:4000000000:{i:0;N;}"), Err(Error::Unserialize));
772 }
773}