utopia-php-std 0.1.0

PHP engine semantics (the value model, juggling and comparison, string, number, JSON, serialize, igbinary, sorting, filter and URL functions) for crates that must behave exactly like PHP.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
//! `serialize`, `unserialize` and `var_export`, in PHP 8.5's formats.
//!
//! | PHP | Rust |
//! |---|---|
//! | `serialize($value)` | [`serialize`] ([`Value`]) |
//! | `unserialize($data, ['max_depth' => $n])` | [`unserialize`], [`Options`] |
//! | `var_export($value, true)` | [`var_export`] |
//! | warnings `unserialize()` emits | [`Unserialized::warnings`], [`Error::Failed`] |
//!
//! Values are scalars, arrays and `stdClass` objects. Floats use
//! `serialize_precision = -1` (`d:0.1;`, `d:1.0E+25;`, `d:INF;`). An
//! [`Value::Ext`] object is written as its [`Extension::to_array`] (PHP code
//! serializes `getArrayCopy()`, not the object).
//!
//! `unserialize` reads every format PHP writes for those values (`N`, `b`,
//! `i`, `d`, `s`, `S`, `a`, `O`/`C` of `stdClass`, and the `r`/`R`
//! back-references), with PHP's error offsets, warnings and depth limit.
//! Back-references resolve to the value at that slot when they are read,
//! which is what PHP produces for data `serialize` writes; [`Value`] has no
//! references or object identity, so they become copies. Objects of other
//! classes, enums (`E:`), and back-references to a container that is still
//! being read (recursive structures) cannot be represented and fail with
//! [`Error::Unsupported`].

use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;

use indexmap::IndexMap;

use crate::json::push_int;
use crate::number;
use crate::types::{Array, ArrayKey, Builder, Extension, KeyRef, Str, Value};

// ---------------------------------------------------------------------------
// serialize (ext/standard/var.c)
// ---------------------------------------------------------------------------

/// `serialize($value)`: PHP's byte string.
pub fn serialize<X: Extension>(value: &Value<X>) -> Vec<u8> {
    let mut out = Vec::with_capacity(128);
    serialize_into(&mut out, value);
    out
}

/// `serialize($value)`, appended to `out`.
pub fn serialize_into<X: Extension>(out: &mut Vec<u8>, value: &Value<X>) {
    match value {
        Value::Null => out.extend_from_slice(b"N;"),
        Value::Bool(b) => out.extend_from_slice(if *b { b"b:1;" } else { b"b:0;" }),
        Value::Int(i) => {
            out.extend_from_slice(b"i:");
            push_int(out, *i);
            out.push(b';');
        }
        Value::Float(f) => {
            out.extend_from_slice(b"d:");
            number::gcvt_into(out, *f, -1, b'E');
            out.push(b';');
        }
        Value::Str(s) => serialize_string(out, s),
        Value::Array(a) => {
            out.extend_from_slice(b"a:");
            nested(out, a);
        }
        Value::Object(a) => {
            out.extend_from_slice(b"O:8:\"stdClass\":");
            nested(out, a);
        }
        Value::Ext(x) => {
            out.extend_from_slice(b"a:");
            nested(out, &x.to_array());
        }
    }
}

fn serialize_string(out: &mut Vec<u8>, s: &[u8]) {
    out.extend_from_slice(b"s:");
    push_int(out, s.len() as i64);
    out.extend_from_slice(b":\"");
    out.extend_from_slice(s);
    out.extend_from_slice(b"\";");
}

/// `php_var_serialize_nested_data`.
fn nested<X: Extension>(out: &mut Vec<u8>, entries: &Array<X>) {
    push_int(out, entries.len() as i64);
    out.extend_from_slice(b":{");
    for (key, value) in entries.iter() {
        match key {
            KeyRef::Int(i) => {
                out.extend_from_slice(b"i:");
                push_int(out, i);
                out.push(b';');
            }
            KeyRef::Str(s) => serialize_string(out, s),
        }
        serialize_into(out, value);
    }
    out.push(b'}');
}

// ---------------------------------------------------------------------------
// var_export (ext/standard/var.c)
// ---------------------------------------------------------------------------

/// `var_export($value, true)`: PHP source code for the value, as bytes
/// (string contents are copied verbatim).
pub fn var_export<X: Extension>(value: &Value<X>) -> Vec<u8> {
    let mut out = Vec::new();
    export(&mut out, value, 1);
    out
}

/// `buffer_append_spaces`: `%*c` with a space, so never fewer than one.
fn spaces(out: &mut Vec<u8>, n: usize) {
    out.resize(out.len() + n.max(1), b' ');
}

/// A single-quoted PHP string literal: `'` and `\` escaped, NUL bytes as
/// `' . "\0" . '` when `nul` is set.
fn quoted(out: &mut Vec<u8>, s: &[u8], nul: bool) {
    out.push(b'\'');
    for &c in s {
        match c {
            b'\'' | b'\\' => out.extend_from_slice(&[b'\\', c]),
            0 if nul => out.extend_from_slice(b"' . \"\\0\" . '"),
            _ => out.push(c),
        }
    }
    out.push(b'\'');
}

/// `php_var_export_ex`.
fn export<X: Extension>(out: &mut Vec<u8>, value: &Value<X>, level: usize) {
    match value {
        Value::Null => out.extend_from_slice(b"NULL"),
        Value::Bool(b) => out.extend_from_slice(if *b { b"true" } else { b"false" }),
        Value::Int(i64::MIN) => out.extend_from_slice(b"-9223372036854775807-1"),
        Value::Int(i) => out.extend_from_slice(i.to_string().as_bytes()),
        Value::Float(f) => {
            let f = *f;
            let s = number::gcvt(f, -1, 'E');
            out.extend_from_slice(s.as_bytes());
            if f.is_finite() && !s.contains('.') {
                out.extend_from_slice(b".0");
            }
        }
        Value::Str(s) => quoted(out, s, true),
        Value::Ext(x) => export(out, &Value::Array(x.to_array()), level),
        Value::Array(entries) => {
            if level > 1 {
                out.push(b'\n');
                spaces(out, level - 1);
            }
            out.extend_from_slice(b"array (\n");
            for (key, v) in entries.iter() {
                spaces(out, level + 1);
                match key {
                    KeyRef::Int(i) => out.extend_from_slice(i.to_string().as_bytes()),
                    KeyRef::Str(k) => quoted(out, k, true),
                }
                out.extend_from_slice(b" => ");
                export(out, v, level + 2);
                out.extend_from_slice(b",\n");
            }
            if level > 1 {
                spaces(out, level - 1);
            }
            out.push(b')');
        }
        Value::Object(entries) => {
            if level > 1 {
                out.push(b'\n');
                spaces(out, level - 1);
            }
            out.extend_from_slice(b"(object) array(\n");
            for (key, v) in entries.iter() {
                spaces(out, level + 2);
                match key {
                    KeyRef::Int(i) => out.extend_from_slice(i.to_string().as_bytes()),
                    KeyRef::Str(k) => quoted(out, unmangle(k), false),
                }
                out.extend_from_slice(b" => ");
                export(out, v, level + 2);
                out.extend_from_slice(b",\n");
            }
            if level > 1 {
                spaces(out, level - 1);
            }
            out.push(b')');
        }
    }
}

/// `zend_unmangle_property_name_ex`: the name after `"\0Class\0"` (or
/// `"\0*\0"`); the whole name when it is not mangled.
fn unmangle(name: &[u8]) -> &[u8] {
    if name.len() < 2 || name[0] != 0 {
        return name;
    }
    match name[1..].iter().position(|&c| c == 0) {
        Some(i) => &name[i + 2..],
        // A malformed mangled name: PHP keeps it whole.
        None => name,
    }
}

// ---------------------------------------------------------------------------
// unserialize (ext/standard/var_unserializer.re)
// ---------------------------------------------------------------------------

/// `unserialize()` options.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Options {
    /// `max_depth`: arrays and objects nested deeper fail. `0` is unlimited;
    /// the default is the `unserialize_max_depth` ini default, 4096.
    pub max_depth: i64,
}

impl Default for Options {
    /// The defaults: `max_depth` 4096.
    fn default() -> Self {
        Options { max_depth: 4096 }
    }
}

/// A successful `unserialize()`: the value and the warnings PHP emitted
/// (for example `unserialize(): Extra data starting at offset 4 of 5 bytes`).
#[derive(Debug, Clone, PartialEq)]
pub struct Unserialized {
    /// The unserialized value.
    pub value: Value,
    /// The warnings PHP emitted, in order.
    pub warnings: Vec<String>,
}

/// Why `unserialize()` failed.
#[derive(Debug, Clone, PartialEq)]
pub enum Error {
    /// PHP returns `false` after emitting `warnings` (the last one is
    /// `unserialize(): Error at offset X of Y bytes`, except for empty input,
    /// which fails silently). `offset` is X.
    Failed {
        /// The byte offset PHP reports, if any.
        offset: Option<usize>,
        /// The warnings PHP emitted, in order.
        warnings: Vec<String>,
    },
    /// An invalid option: PHP throws `ValueError` with this message.
    Value(String),
    /// Data PHP reads into something [`Value`] cannot hold: objects of other
    /// classes (or `__PHP_Incomplete_Class`), enums, or a back-reference to
    /// a container still being read (a recursive structure).
    Unsupported(&'static str),
}

impl Error {
    /// The PHP class of a thrown error (`ValueError`); `unserialize` reports
    /// the other failures as warnings and `false`.
    pub fn php_class(&self) -> &'static str {
        match self {
            Error::Value(_) => "ValueError",
            Error::Failed { .. } | Error::Unsupported(_) => "Error",
        }
    }
}

impl fmt::Display for Error {
    /// Writes the last warning, or the error message.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Failed { warnings, .. } => {
                f.write_str(warnings.last().map(String::as_str).unwrap_or("unserialize() failed"))
            }
            Error::Value(message) => f.write_str(message),
            Error::Unsupported(what) => write!(f, "unserialize(): unsupported data: {what}"),
        }
    }
}

impl std::error::Error for Error {}

/// `unserialize($data, $options)`.
pub fn unserialize(data: &[u8], options: &Options) -> Result<Unserialized, Error> {
    if data.is_empty() {
        return Err(Error::Failed { offset: None, warnings: Vec::new() });
    }
    if options.max_depth < 0 {
        return Err(Error::Value("unserialize(): Option \"max_depth\" must be greater than or equal to 0".into()));
    }
    let fresh = || Unserializer {
        buf: data,
        max_depth: options.max_depth,
        cur_depth: 0,
        slots: Vec::new(),
        cells: Vec::new(),
        warnings: Vec::new(),
        opened: None,
        unsupported: None,
        built: RefCell::new(HashMap::new()),
    };
    // Data without back-references (what `serialize` writes for these
    // values) is built directly; anything else, including every failure,
    // is read again into locations, which back-references point at.
    let mut u = fresh();
    let mut p = 0;
    if let Some(value) = u.direct(&mut p) {
        if p < data.len() {
            u.warn(format!("unserialize(): Extra data starting at offset {p} of {} bytes", data.len()));
        }
        if let Some(what) = u.unsupported {
            return Err(Error::Unsupported(what));
        }
        return Ok(Unserialized { value, warnings: u.warnings });
    }
    let mut u = fresh();
    // The root location.
    u.cells.push(Cell::Null);
    let mut p = 0;
    match u.run(&mut p) {
        Ok(true) => {}
        Ok(false) => {
            u.warn(format!("unserialize(): Error at offset {p} of {} bytes", data.len()));
            return Err(Error::Failed { offset: Some(p), warnings: u.warnings });
        }
        Err(e) => return Err(e),
    }
    if p < data.len() {
        u.warn(format!("unserialize(): Extra data starting at offset {p} of {} bytes", data.len()));
    }
    if let Some(what) = u.unsupported {
        return Err(Error::Unsupported(what));
    }
    let value = u.materialize(0)?;
    Ok(Unserialized { value, warnings: u.warnings })
}

/// A location values are read into (PHP's `zval *` slots): back-references
/// point at locations, and a duplicate key reuses its location.
type CellId = usize;

enum Cell {
    Null,
    Value(Value),
    Array {
        entries: IndexMap<ArrayKey, CellId>,
        done: bool,
    },
    Object {
        props: IndexMap<Str, CellId>,
        done: bool,
    },
    /// A back-reference that makes the value recursive (PHP shares the
    /// referenced container): reading goes on, the result is unsupported.
    Recursive(CellId),
}

struct Unserializer<'a> {
    buf: &'a [u8],
    max_depth: i64,
    cur_depth: i64,
    /// `var_hash`: the location of every value read so far, in order.
    slots: Vec<CellId>,
    cells: Vec<Cell>,
    warnings: Vec<String>,
    /// Set by [`Unserializer::value`] when it opened an array or object:
    /// its element count and whether it is an object.
    opened: Option<(i64, bool)>,
    /// Why the value, once read, cannot be returned (an object of another class).
    unsupported: Option<&'static str>,
    /// The value each finished container materialized to, so that every back-reference
    /// to it costs one clone (constant time: arrays are copy-on-write) rather than a
    /// rebuild. A finished container never changes again, except when a duplicate key
    /// reuses its location, which [`Unserializer::reset`] forgets here.
    built: RefCell<HashMap<CellId, Value>>,
}

/// `HT_MAX_SIZE` on 64-bit platforms.
const HT_MAX_SIZE: i64 = 0x4000_0000;

/// What a key read produced (`php_var_unserialize_internal` without `var_hash`).
enum KeyValue {
    Int(i64),
    Str(Str),
    /// A value that cannot be a key (`N;`, `b:..;`, `d:..;`).
    Other,
}

type Step = Result<bool, Error>;

/// What [`Unserializer::read`] found at the cursor.
enum Read {
    /// A complete value.
    Value(Value),
    /// `R:` or `r:`, not read yet (the cursor has not moved).
    Reference,
    /// An array (or object) of this many elements, opened.
    Open { elements: i64, object: bool },
}

impl Unserializer<'_> {
    fn warn(&mut self, message: String) {
        self.warnings.push(message);
    }

    /// The byte at `i`, or the NUL terminator after the data.
    fn at(&self, i: usize) -> u8 {
        self.buf.get(i).copied().unwrap_or(0)
    }

    fn digits_end(&self, mut i: usize) -> usize {
        while self.at(i).is_ascii_digit() {
            i += 1;
        }
        i
    }

    /// `parse_uiv`: `size_t` arithmetic, wrapping like C.
    fn parse_uiv(&self, mut i: usize) -> u64 {
        let mut result: u64 = 0;
        while self.at(i).is_ascii_digit() {
            result = result.wrapping_mul(10).wrapping_add(u64::from(self.at(i) - b'0'));
            i += 1;
        }
        result
    }

    /// `parse_iv2`: an optional sign, leading zeros, digits; out of range
    /// clamps with a warning. Returns the value and where the digits end.
    fn parse_iv2(&mut self, mut i: usize) -> (i64, usize) {
        let mut neg = false;
        if self.at(i) == b'-' {
            neg = true;
            i += 1;
        } else if self.at(i) == b'+' {
            i += 1;
        }
        while self.at(i) == b'0' {
            i += 1;
        }
        let start = i;
        let mut result: u64 = 0;
        while self.at(i).is_ascii_digit() {
            result = result.wrapping_mul(10).wrapping_add(u64::from(self.at(i) - b'0'));
            i += 1;
        }
        if i - start > 19 || result > i64::MAX as u64 + u64::from(neg) {
            self.warn("unserialize(): Numerical result out of range".into());
            return (if neg { i64::MIN } else { i64::MAX }, i);
        }
        (if neg { (result as i64).wrapping_neg() } else { result as i64 }, i)
    }

    /// Matches `uiv ";"` (or another terminator) at `i`: the end, after the terminator.
    fn uiv_then(&self, i: usize, term: u8) -> Option<usize> {
        let end = self.digits_end(i);
        (end > i && self.at(end) == term).then_some(end + 1)
    }

    /// `iv = [+-]? [0-9]+` at `i`: where it ends.
    fn iv(&self, mut i: usize) -> Option<usize> {
        if matches!(self.at(i), b'+' | b'-') {
            i += 1;
        }
        let end = self.digits_end(i);
        (end > i).then_some(end)
    }

    /// `(iv | nv | nvexp)` at `i`: where the longest match ends.
    fn number(&self, i: usize) -> Option<usize> {
        let mut j = i;
        if matches!(self.at(j), b'+' | b'-') {
            j += 1;
        }
        let int_end = self.digits_end(j);
        let mut end = None;
        if int_end > j {
            end = Some(int_end);
        }
        if self.at(int_end) == b'.' {
            let frac_end = self.digits_end(int_end + 1);
            // nv: digits* "." digits+ | digits+ "." digits*
            if frac_end > int_end + 1 || int_end > j {
                end = Some(frac_end);
            }
        }
        let mantissa_end = end?;
        if matches!(self.at(mantissa_end), b'e' | b'E')
            && let Some(exp_end) = self.iv(mantissa_end + 1)
        {
            return Some(exp_end);
        }
        Some(mantissa_end)
    }

    fn set(&mut self, cell: CellId, value: Value) {
        self.reset(cell, Cell::Value(value));
    }

    /// Replaces what a location holds, and forgets what it materialized to.
    fn reset(&mut self, cell: CellId, to: Cell) {
        self.built.get_mut().remove(&cell);
        self.cells[cell] = to;
    }

    /// `php_var_unserialize_internal` with `var_hash`: reads a value into `cell`.
    fn value(&mut self, p: &mut usize, cell: CellId) -> Step {
        let start = *p;
        if start >= self.buf.len() {
            return Ok(false);
        }
        let c0 = self.at(start);
        if c0 != b'R' {
            self.slots.push(cell);
        }
        match self.read(p)? {
            None => Ok(false),
            Some(Read::Value(v)) => {
                self.set(cell, v);
                Ok(true)
            }
            Some(Read::Open { object, elements }) => {
                let open = if object {
                    Cell::Object { props: IndexMap::new(), done: false }
                } else {
                    Cell::Array { entries: IndexMap::new(), done: false }
                };
                self.reset(cell, open);
                self.opened = Some((elements, object));
                Ok(true)
            }
            Some(Read::Reference) => {
                let Some(end) = self.uiv_then(start + 2, b';') else { return Ok(false) };
                *p = end;
                let id = self.parse_uiv(start + 2).wrapping_sub(1);
                let Some(&target) = usize::try_from(id).ok().and_then(|id| self.slots.get(id)) else {
                    return Ok(false);
                };
                if target == cell {
                    return Ok(false);
                }
                if c0 == b'r' && !self.is_object(target) {
                    return Ok(false);
                }
                match self.materialize(target) {
                    Ok(snapshot) => self.set(cell, snapshot),
                    Err(Error::Unsupported(what)) => {
                        self.unsupported.get_or_insert(what);
                        self.reset(cell, Cell::Recursive(target));
                    }
                    Err(e) => return Err(e),
                }
                Ok(true)
            }
        }
    }

    /// `php_var_unserialize_internal` at the cursor, without `var_hash`:
    /// the value, a back-reference to resolve, or an opened container;
    /// `None` after setting `p` where PHP reports the error.
    fn read(&mut self, p: &mut usize) -> Result<Option<Read>, Error> {
        let start = *p;
        if start >= self.buf.len() {
            return Ok(None);
        }
        let c0 = self.at(start);
        let c1 = self.at(start + 1);
        let value = match (c0, c1) {
            (b'R' | b'r', b':') => return Ok(Some(Read::Reference)),
            (b'N', b';') => {
                *p = start + 2;
                Value::Null
            }
            (b'b', b':') if matches!(self.at(start + 2), b'0' | b'1') && self.at(start + 3) == b';' => {
                *p = start + 4;
                Value::Bool(self.at(start + 2) == b'1')
            }
            (b'i', b':') => {
                let Some(end) = self.iv(start + 2).filter(|&e| self.at(e) == b';') else { return Ok(None) };
                *p = end + 1;
                Value::Int(self.parse_iv2(start + 2).0)
            }
            (b'd', b':') => {
                let rest = &self.buf[(start + 2).min(self.buf.len())..];
                for (text, value) in [(&b"NAN;"[..], f64::NAN), (b"INF;", f64::INFINITY), (b"-INF;", f64::NEG_INFINITY)]
                {
                    if rest.starts_with(text) {
                        *p = start + 2 + text.len();
                        return Ok(Some(Read::Value(Value::Float(value))));
                    }
                }
                let Some(end) = self.number(start + 2).filter(|&e| self.at(e) == b';') else { return Ok(None) };
                *p = end + 1;
                let text = std::str::from_utf8(&self.buf[start + 2..end]).unwrap_or("0");
                Value::Float(strtod(text))
            }
            (b's' | b'S', b':') => match self.string(p, start)? {
                Some(s) => Value::Str(s),
                None => return Ok(None),
            },
            (b'a', b':') => {
                let Some(cursor) = self.uiv_then(start + 2, b':').filter(|&e| self.at(e) == b'{').map(|e| e + 1) else {
                    return Ok(None);
                };
                let (elements, _) = self.parse_iv2(start + 2);
                *p = cursor;
                if !(0..HT_MAX_SIZE).contains(&elements) || fake_count(elements, self.buf.len() - cursor) {
                    return Ok(None);
                }
                if elements == 0 {
                    // No nested data, so no depth check.
                    if !self.finish(p) {
                        return Ok(None);
                    }
                    Value::Array(Array::new())
                } else {
                    return Ok(Some(Read::Open { elements, object: false }));
                }
            }
            (b'O' | b'C', b':') => return self.object(p, start),
            (b'E', b':') => {
                self.enumeration(p, start)?;
                return Ok(None);
            }
            (b'}', _) => {
                self.warn("unserialize(): Unexpected end of serialized data".into());
                return Ok(None);
            }
            _ => return Ok(None),
        };
        Ok(Some(Read::Value(value)))
    }

    /// `"s:" uiv ":" ["]` and `"S:" uiv ":" ["]` at `start`: the string, or
    /// `None` after setting `p` where PHP reports the error.
    fn string(&mut self, p: &mut usize, start: usize) -> Result<Option<Str>, Error> {
        let escaped = self.at(start) == b'S';
        let Some(cursor) = self.uiv_then(start + 2, b':').filter(|&e| self.at(e) == b'"').map(|e| e + 1) else {
            return Ok(None);
        };
        let len = self.parse_uiv(start + 2);
        let maxlen = (self.buf.len() - cursor) as u64;
        if maxlen < len {
            *p = start + 2;
            return Ok(None);
        }
        let len = len as usize;
        let (s, mut cursor) = if escaped {
            // `unserialize_str`: `\xx` hex escapes; the cursor is local, so a
            // failure here reports the value's start.
            let mut out = Vec::with_capacity(len);
            let mut i = cursor;
            for _ in 0..len {
                if i >= self.buf.len() {
                    return Ok(None);
                }
                if self.at(i) != b'\\' {
                    out.push(self.at(i));
                } else {
                    let mut ch: u8 = 0;
                    for _ in 0..2 {
                        i += 1;
                        let Some(d) = char::from(self.at(i)).to_digit(16) else { return Ok(None) };
                        ch = (ch << 4).wrapping_add(d as u8);
                    }
                    out.push(ch);
                }
                i += 1;
            }
            (Str::from(out), i)
        } else {
            (Str::copy_from(&self.buf[cursor..cursor + len]), cursor + len)
        };
        if self.at(cursor) != b'"' {
            *p = cursor;
            return Ok(None);
        }
        if self.at(cursor + 1) != b';' {
            *p = cursor + 1;
            return Ok(None);
        }
        cursor += 2;
        *p = cursor;
        if escaped {
            self.warn("unserialize(): Unserializing the 'S' format is deprecated".into());
        }
        Ok(Some(s))
    }

    /// `"E:" uiv ":" ["]`: an enum case. No PHP class exists on this side,
    /// so this is PHP's behaviour for an enum class that is not defined.
    fn enumeration(&mut self, p: &mut usize, start: usize) -> Step {
        let Some(cursor) = self.uiv_then(start + 2, b':').filter(|&e| self.at(e) == b'"').map(|e| e + 1) else {
            return Ok(false);
        };
        let len = self.parse_uiv(start + 2);
        let maxlen = (self.buf.len() - cursor) as u64;
        if maxlen < len || len == 0 {
            *p = start + 2;
            return Ok(false);
        }
        let end = cursor + len as usize;
        if self.at(end) != b'"' {
            *p = end;
            return Ok(false);
        }
        if self.at(end + 1) != b';' {
            *p = end + 1;
            return Ok(false);
        }
        let name = &self.buf[cursor..end];
        let Some(colon) = name.iter().position(|&c| c == b':') else {
            let message =
                format!("unserialize(): Invalid enum name '{}' (missing colon)", String::from_utf8_lossy(name));
            self.warn(message);
            return Ok(false);
        };
        let class = &name[..colon];
        if !valid_class_name(class) {
            return Ok(false);
        }
        let message = format!("unserialize(): Class '{}' not found", String::from_utf8_lossy(class));
        self.warn(message);
        Ok(false)
    }

    /// `object ":" uiv ":" ["]`: `O:` and `C:` of `stdClass`.
    fn object(&mut self, p: &mut usize, start: usize) -> Result<Option<Read>, Error> {
        let custom = self.at(start) == b'C';
        let Some(mut cursor) = self.uiv_then(start + 2, b':').filter(|&e| self.at(e) == b'"').map(|e| e + 1) else {
            return Ok(None);
        };
        let len = self.parse_uiv(start + 2);
        let maxlen = (self.buf.len() - cursor) as u64;
        if maxlen < len || len == 0 {
            *p = start + 2;
            return Ok(None);
        }
        let name = &self.buf[cursor..cursor + len as usize];
        cursor += len as usize;
        if self.at(cursor) != b'"' {
            *p = cursor;
            return Ok(None);
        }
        if self.at(cursor + 1) != b':' {
            *p = cursor + 1;
            return Ok(None);
        }
        if name[0] == 0 || name[0] == b'\\' {
            return Ok(None);
        }
        let incomplete = !name.eq_ignore_ascii_case(b"stdClass");
        if incomplete {
            if !valid_class_name(name) {
                return Ok(None);
            }
            // No PHP class exists here: PHP reads such an object as
            // __PHP_Incomplete_Class, parsing on exactly like stdClass. Read
            // on, so failures match, and refuse the value if it is complete.
            self.unsupported.get_or_insert("object of a class other than stdClass");
        }
        *p = cursor;
        if custom {
            // `object_custom`: stdClass has no unserializer.
            let (datalen, q) = self.parse_iv2(*p + 2);
            *p = q;
            if self.buf.len().saturating_sub(*p) < 2 || self.at(*p) != b':' {
                return Ok(None);
            }
            if self.at(*p + 1) != b'{' {
                *p += 1;
                return Ok(None);
            }
            *p += 2;
            let present = (self.buf.len() - *p) as i64;
            if datalen < 0 || present <= datalen {
                self.warn(format!("Insufficient data for unserializing - {datalen} required, {present} present"));
                return Ok(None);
            }
            if self.at(*p + datalen as usize) != b'}' {
                *p += datalen as usize;
                return Ok(None);
            }
            let class = if incomplete { "__PHP_Incomplete_Class" } else { "stdClass" };
            self.warn(format!("Class {class} has no unserializer"));
            *p += datalen as usize + 1;
            return Ok(Some(Read::Value(Value::Object(Array::new()))));
        }
        if *p + 2 >= self.buf.len() {
            self.warn("Bad unserialize data".into());
            return Ok(None);
        }
        let (elements, q) = self.parse_iv2(*p + 2);
        *p = q;
        if elements < 0 || fake_count(elements, self.buf.len() - cursor) {
            return Ok(None);
        }
        if self.at(*p) != b':' {
            return Ok(None);
        }
        if self.at(*p + 1) != b'{' {
            *p += 1;
            return Ok(None);
        }
        *p += 2;
        if elements >= HT_MAX_SIZE {
            return Ok(None);
        }
        Ok(Some(Read::Open { elements, object: true }))
    }

    /// `finish_nested_data`.
    fn finish(&self, p: &mut usize) -> bool {
        if *p >= self.buf.len() || self.at(*p) != b'}' {
            return false;
        }
        *p += 1;
        true
    }

    /// `php_var_unserialize_internal` without `var_hash`: an array key or property name.
    fn key(&mut self, p: &mut usize) -> Result<Option<KeyValue>, Error> {
        let start = *p;
        if start >= self.buf.len() {
            return Ok(None);
        }
        let (c0, c1) = (self.at(start), self.at(start + 1));
        Ok(match (c0, c1) {
            (b'R' | b'r', b':') => {
                // The rule matches (and moves the cursor) before refusing a key.
                if let Some(end) = self.uiv_then(start + 2, b';') {
                    *p = end;
                }
                None
            }
            (b'N', b';') => {
                *p = start + 2;
                Some(KeyValue::Other)
            }
            (b'b', b':') if matches!(self.at(start + 2), b'0' | b'1') && self.at(start + 3) == b';' => {
                *p = start + 4;
                Some(KeyValue::Other)
            }
            (b'i', b':') => match self.iv(start + 2).filter(|&e| self.at(e) == b';') {
                Some(end) => {
                    *p = end + 1;
                    Some(KeyValue::Int(self.parse_iv2(start + 2).0))
                }
                None => None,
            },
            (b'd', b':') => {
                let rest = &self.buf[(start + 2).min(self.buf.len())..];
                if let Some(text) = [&b"NAN;"[..], b"INF;", b"-INF;"].into_iter().find(|t| rest.starts_with(t)) {
                    *p = start + 2 + text.len();
                    Some(KeyValue::Other)
                } else if let Some(end) = self.number(start + 2).filter(|&e| self.at(e) == b';') {
                    *p = end + 1;
                    Some(KeyValue::Other)
                } else {
                    None
                }
            }
            (b's' | b'S', b':') => self.string(p, start)?.map(KeyValue::Str),
            (b'a', b':') => {
                if let Some(cursor) = self.uiv_then(start + 2, b':').filter(|&e| self.at(e) == b'{') {
                    self.parse_iv2(start + 2);
                    *p = cursor + 1;
                }
                None
            }
            (b'}', _) => {
                self.warn("unserialize(): Unexpected end of serialized data".into());
                None
            }
            _ => None,
        })
    }

    /// Reads the whole value into the root location: `php_var_unserialize_internal`
    /// with `process_nested_array_data` / `process_nested_object_data` and
    /// `finish_nested_data`, without recursion.
    fn run(&mut self, p: &mut usize) -> Step {
        struct Frame {
            cell: CellId,
            remaining: i64,
            object: bool,
            started: bool,
        }
        let mut frames: Vec<Frame> = Vec::new();
        let mut target = 0;
        loop {
            if !self.value(p, target)? {
                return Ok(false);
            }
            if let Some((elements, object)) = self.opened.take() {
                if self.max_depth > 0 && self.cur_depth >= self.max_depth {
                    self.warn(format!(
                        "unserialize(): Maximum depth of {} exceeded. The depth limit can be changed using the max_depth unserialize() option or the unserialize_max_depth ini setting",
                        self.max_depth
                    ));
                    return Ok(false);
                }
                self.cur_depth += 1;
                frames.push(Frame { cell: target, remaining: elements, object, started: false });
            }
            // The value is complete (or a container opened): find the next one.
            loop {
                let Some(frame) = frames.last_mut() else { return Ok(true) };
                if frame.started && frame.remaining > 0 && !matches!(self.at(p.wrapping_sub(1)), b';' | b'}') {
                    *p -= 1;
                    return Ok(false);
                }
                frame.started = true;
                if frame.remaining > 0 {
                    frame.remaining -= 1;
                    let (cell, object) = (frame.cell, frame.object);
                    let Some(key) = self.key(p)? else { return Ok(false) };
                    target = match (key, object) {
                        (KeyValue::Other, _) => return Ok(false),
                        (KeyValue::Int(i), false) => self.child(cell, ArrayKey::Int(i)),
                        (KeyValue::Str(s), false) => self.child(cell, ArrayKey::normalize(s)),
                        (KeyValue::Int(i), true) => self.prop(cell, Str::from(i.to_string())),
                        (KeyValue::Str(s), true) => self.prop(cell, s),
                    };
                    break;
                }
                let Some(frame) = frames.pop() else { return Ok(true) };
                self.cur_depth -= 1;
                match &mut self.cells[frame.cell] {
                    Cell::Array { done, .. } | Cell::Object { done, .. } => *done = true,
                    _ => {}
                }
                if !self.finish(p) {
                    return Ok(false);
                }
            }
        }
    }

    /// Reads the whole value, building it directly: [`Unserializer::run`]
    /// without locations, for what `serialize` writes (`N`, `b`, `i`, `d`,
    /// `s`, `a`, and `O` of `stdClass`). `None` for anything else (a
    /// back-reference, another class, `S`, data that warns) and on failure:
    /// then `run` reads it again and reports what PHP reports.
    fn direct(&mut self, p: &mut usize) -> Option<Value> {
        let buf = self.buf;
        let mut pos = *p;
        let mut open = match *buf.get(pos)? {
            b'a' | b'O' => match self.container(&mut pos)? {
                Ok(open) => open,
                Err(empty) => {
                    *p = pos;
                    return Some(empty);
                }
            },
            _ => {
                let value = self.scalar(&mut pos)?;
                *p = pos;
                return Some(value);
            }
        };
        // The containers `open` is nested in, each with the key it goes to.
        let mut parents: Vec<(Open, ArrayKey)> = Vec::new();
        loop {
            if open.remaining == 0 {
                if buf.get(pos) != Some(&b'}') {
                    return None;
                }
                pos += 1;
                self.cur_depth -= 1;
                let array = open.array.finish();
                let value = if open.object { Value::Object(array) } else { Value::Array(array) };
                let Some((parent, key)) = parents.pop() else {
                    *p = pos;
                    return Some(value);
                };
                open = parent;
                open.array.set(key, value);
                continue;
            }
            open.remaining -= 1;
            // Every value read here ends with `;` or `}`, which a key may follow.
            let (key, end) = key(buf, pos, open.object)?;
            pos = end;
            match *buf.get(pos)? {
                b'a' | b'O' => match self.container(&mut pos)? {
                    Ok(nested) => parents.push((std::mem::replace(&mut open, nested), key)),
                    Err(empty) => open.array.set(key, empty),
                },
                _ => {
                    let value = self.scalar(&mut pos)?;
                    open.array.set(key, value);
                }
            }
        }
    }

    /// A scalar at the cursor for [`Unserializer::direct`].
    #[inline]
    fn scalar(&mut self, pos: &mut usize) -> Option<Value> {
        if self.buf.get(*pos) == Some(&b'd') {
            // Rare: `read` has the float grammar.
            return match self.read(pos).ok()?? {
                Read::Value(v) => Some(v),
                _ => None,
            };
        }
        let (value, end) = scalar(self.buf, *pos)?;
        *pos = end;
        Some(value)
    }

    /// An `a:` or `O:` (of `stdClass`) at the cursor for
    /// [`Unserializer::direct`]: the container opened, within the depth
    /// limit, or the empty array `a:0:{}`.
    fn container(&mut self, pos: &mut usize) -> Option<Result<Open, Value>> {
        let buf = self.buf;
        let i = *pos;
        if buf.get(i + 1) != Some(&b':') {
            return None;
        }
        let object = buf[i] == b'O';
        let (elements, brace, cursor) = if object {
            let (len, quote) = uiv(buf, i + 2, b':')?;
            if buf.get(quote) != Some(&b'"') {
                return None;
            }
            let cursor = quote + 1 + len;
            let name = buf.get(quote + 1..cursor)?;
            // Other classes (and an empty name) are left to `run`.
            if !name.eq_ignore_ascii_case(b"stdClass") || buf.get(cursor..cursor + 2) != Some(b"\":") {
                return None;
            }
            let (elements, brace) = uiv(buf, cursor + 2, b':')?;
            // PHP counts the bytes after the name.
            (elements, brace, cursor)
        } else {
            let (elements, brace) = uiv(buf, i + 2, b':')?;
            (elements, brace, brace + 1)
        };
        if buf.get(brace) != Some(&b'{')
            || elements as i64 >= HT_MAX_SIZE
            || fake_count(elements as i64, buf.len() - cursor)
        {
            return None;
        }
        *pos = brace + 1;
        if elements == 0 && !object {
            // No nested data, so no depth check.
            if buf.get(*pos) != Some(&b'}') {
                return None;
            }
            *pos += 1;
            return Some(Err(Value::Array(Array::new())));
        }
        if self.max_depth > 0 && self.cur_depth >= self.max_depth {
            return None;
        }
        self.cur_depth += 1;
        // Each entry takes at least 6 bytes (`i:0;N;`): no more room than that.
        let array = Builder::new(elements.min((buf.len() - *pos) / 6));
        Some(Ok(Open { array, remaining: elements, object }))
    }

    /// The location of `key` in the array at `cell` (reused when the key repeats).
    fn child(&mut self, cell: CellId, key: ArrayKey) -> CellId {
        let next = self.cells.len();
        let Cell::Array { entries, .. } = &mut self.cells[cell] else { unreachable!() };
        let id = *entries.entry(key).or_insert(next);
        if id == next {
            self.cells.push(Cell::Null);
        } else {
            self.reset(id, Cell::Null);
        }
        id
    }

    fn prop(&mut self, cell: CellId, name: Str) -> CellId {
        let next = self.cells.len();
        let Cell::Object { props, .. } = &mut self.cells[cell] else { unreachable!() };
        let id = *props.entry(name).or_insert(next);
        if id == next {
            self.cells.push(Cell::Null);
        } else {
            self.reset(id, Cell::Null);
        }
        id
    }

    /// Whether the value at a location is an object (`ZVAL_DEREF` + `IS_OBJECT`).
    fn is_object(&self, mut cell: CellId) -> bool {
        loop {
            match &self.cells[cell] {
                Cell::Recursive(target) => cell = *target,
                Cell::Object { .. } | Cell::Value(Value::Object(_)) => return true,
                _ => return false,
            }
        }
    }

    /// The value at a location now (without recursion).
    fn materialize(&self, root: CellId) -> Result<Value, Error> {
        enum Slot<'c> {
            Key(&'c ArrayKey),
            Prop(&'c Str),
        }
        enum Partial {
            Array(Array),
            Object(Array),
        }
        struct Frame<'c> {
            cell: CellId,
            partial: Partial,
            children: Vec<(Slot<'c>, CellId)>,
            next: usize,
        }
        let mut stack: Vec<Frame<'_>> = Vec::new();
        let mut visit = Some(root);
        let mut done: Option<Value> = None;
        loop {
            if let Some(cell) = visit.take() {
                if let Some(value) = self.built.borrow().get(&cell) {
                    done = Some(value.clone());
                } else {
                    match &self.cells[cell] {
                        Cell::Null => done = Some(Value::Null),
                        Cell::Value(v) => done = Some(v.clone()),
                        Cell::Array { done: false, .. } | Cell::Object { done: false, .. } | Cell::Recursive(_) => {
                            return Err(Error::Unsupported("reference to a container that is still being read"));
                        }
                        Cell::Array { entries, .. } => stack.push(Frame {
                            cell,
                            partial: Partial::Array(Array::with_capacity(entries.len())),
                            children: entries.iter().map(|(k, &c)| (Slot::Key(k), c)).collect(),
                            next: 0,
                        }),
                        Cell::Object { props, .. } => stack.push(Frame {
                            cell,
                            partial: Partial::Object(Array::new()),
                            children: props.iter().map(|(k, &c)| (Slot::Prop(k), c)).collect(),
                            next: 0,
                        }),
                    }
                }
            }
            let Some(frame) = stack.last_mut() else { return Ok(done.unwrap_or_default()) };
            if let Some(value) = done.take() {
                match (&mut frame.partial, &frame.children[frame.next - 1].0) {
                    (Partial::Array(a), Slot::Key(k)) => {
                        a.set((*k).clone(), value);
                    }
                    (Partial::Object(o), Slot::Prop(name)) => {
                        o.set(ArrayKey::Str((*name).clone()), value);
                    }
                    _ => unreachable!(),
                }
            }
            if frame.next < frame.children.len() {
                visit = Some(frame.children[frame.next].1);
                frame.next += 1;
            } else if let Some(frame) = stack.pop() {
                let value = match frame.partial {
                    Partial::Array(a) => Value::Array(a),
                    Partial::Object(o) => Value::Object(o),
                };
                // Only finished containers get here: an open one is refused above.
                self.built.borrow_mut().insert(frame.cell, value.clone());
                done = Some(value);
            }
        }
    }
}

/// A container [`Unserializer::direct`] is reading.
struct Open {
    array: Builder,
    /// Entries still to read.
    remaining: usize,
    object: bool,
}

/// `uiv` at `i` followed by `term`: the number and where the terminator
/// ends. At most 18 digits, so it cannot wrap (longer ones are left to
/// [`Unserializer::run`]).
#[inline]
fn uiv(buf: &[u8], mut i: usize, term: u8) -> Option<(usize, usize)> {
    let start = i;
    let mut n = 0usize;
    while let Some(&c) = buf.get(i)
        && c.is_ascii_digit()
    {
        n = n * 10 + usize::from(c - b'0');
        i += 1;
        if i - start > 18 {
            return None;
        }
    }
    (i > start && buf.get(i) == Some(&term)).then_some((n, i + 1))
}

/// `iv ";"` at `i` (`[+-]? [0-9]+`): the integer and where it ends. At most
/// 18 significant digits, so it cannot be out of range (larger ones warn,
/// which [`Unserializer::run`] reports).
#[inline]
fn int(buf: &[u8], mut i: usize) -> Option<(i64, usize)> {
    let negative = buf.get(i) == Some(&b'-');
    if matches!(buf.get(i), Some(b'-' | b'+')) {
        i += 1;
    }
    let start = i;
    while buf.get(i) == Some(&b'0') {
        i += 1;
    }
    let digits = i;
    let mut n = 0i64;
    while let Some(&c) = buf.get(i)
        && c.is_ascii_digit()
    {
        if i - digits == 18 {
            return None;
        }
        n = n * 10 + i64::from(c - b'0');
        i += 1;
    }
    (i > start && buf.get(i) == Some(&b';')).then_some((if negative { -n } else { n }, i + 1))
}

/// The bytes of `uiv ":" ["] ... ["] ";"` at `i` (after `s:`), and where it ends.
#[inline]
fn bytes(buf: &[u8], i: usize) -> Option<(&[u8], usize)> {
    let (len, quote) = uiv(buf, i, b':')?;
    if buf.get(quote) != Some(&b'"') {
        return None;
    }
    let end = quote + 1 + len;
    let s = buf.get(quote + 1..end)?;
    (buf.get(end..end + 2) == Some(b"\";")).then_some((s, end + 2))
}

/// `N;`, `b:0;`, `b:1;`, `i:..;` or `s:..;` at `i`: the value and where it ends.
#[inline]
fn scalar(buf: &[u8], i: usize) -> Option<(Value, usize)> {
    let tag = buf.get(i..i + 2)?;
    Some(match tag {
        b"N;" => (Value::Null, i + 2),
        b"s:" => {
            let (s, end) = bytes(buf, i + 2)?;
            (Value::Str(Str::copy_from(s)), end)
        }
        b"i:" => {
            let (n, end) = int(buf, i + 2)?;
            (Value::Int(n), end)
        }
        b"b:" => match buf.get(i + 2..i + 4)? {
            b"0;" => (Value::Bool(false), i + 4),
            b"1;" => (Value::Bool(true), i + 4),
            _ => return None,
        },
        _ => return None,
    })
}

/// An array key (`i:` or `s:`, normalised) or property name at `i`, and where it ends.
#[inline]
fn key(buf: &[u8], i: usize, object: bool) -> Option<(ArrayKey, usize)> {
    match buf.get(i..i + 2)? {
        b"s:" => {
            let (s, end) = bytes(buf, i + 2)?;
            Some((if object { ArrayKey::Str(Str::copy_from(s)) } else { ArrayKey::from_bytes(s) }, end))
        }
        b"i:" => {
            let (n, end) = int(buf, i + 2)?;
            Some((if object { ArrayKey::Str(Str::from(n.to_string())) } else { ArrayKey::Int(n) }, end))
        }
        _ => None,
    }
}

/// `zend_is_valid_class_name`: `0-9 a-z A-Z _ \` and bytes from 0x80.
fn valid_class_name(name: &[u8]) -> bool {
    name.iter().all(|&c| c.is_ascii_alphanumeric() || c == b'_' || c == b'\\' || c >= 0x80)
}

/// `IS_FAKE_ELEM_COUNT`: each element takes at least two bytes.
fn fake_count(elements: i64, remaining: usize) -> bool {
    elements > (remaining / 2) as i64
}

/// `zend_strtod` of a matched `iv | nv | nvexp`: Rust's parser accepts the
/// same forms (`+1`, `5.`, `.5e1`) and rounds the same way.
fn strtod(text: &str) -> f64 {
    text.parse().unwrap_or(0.0)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    type V = Value<crate::types::Never>;

    fn u(s: &str) -> Result<Unserialized, Error> {
        unserialize(s.as_bytes(), &Options::default())
    }

    #[test]
    fn serializes_like_php() {
        let v = json!([1.0, 0.1, 1e25, -0.0, "a", {"x": true, "5": null}, {}]);
        assert_eq!(
            String::from_utf8(serialize(&V::from_json(&v))).unwrap(),
            r#"a:7:{i:0;d:1;i:1;d:0.1;i:2;d:1.0E+25;i:3;d:-0;i:4;s:1:"a";i:5;a:2:{s:1:"x";b:1;i:5;N;}i:6;O:8:"stdClass":0:{}}"#
        );
    }

    #[test]
    fn exports_like_php() {
        let v = json!({"a": [1, {}], "k'": "x\u{0}y"});
        assert_eq!(
            String::from_utf8(var_export(&V::from_json(&v))).unwrap(),
            "array (\n  'a' => \n  array (\n    0 => 1,\n    1 => \n    (object) array(\n    ),\n  ),\n  'k\\'' => 'x' . \"\\0\" . 'y',\n)"
        );
        assert_eq!(String::from_utf8(var_export(&V::from_json(&json!(1.0)))).unwrap(), "1.0");
        assert_eq!(String::from_utf8(var_export(&V::from_json(&json!(i64::MIN)))).unwrap(), "-9223372036854775807-1");
    }

    #[test]
    fn unserializes_like_php() {
        assert_eq!(u("i:+0005;").unwrap().value, Value::Int(5));
        assert_eq!(u("d:5.;").unwrap().value, Value::Float(5.0));
        assert_eq!(u("d:.5e1;").unwrap().value, Value::Float(5.0));
        let r = u("a:3:{i:0;i:1;i:0;i:2;i:1;R:2;}").unwrap().value;
        assert_eq!(r.to_json(), json!([2, 2]));
        assert_eq!(
            u("i:5;x").unwrap().warnings,
            vec!["unserialize(): Extra data starting at offset 4 of 5 bytes".to_string()]
        );
        for (s, offset) in [
            ("i:5", 0),
            ("s:3:\"ab\";", 8),
            ("s:2:\"abc\";", 7),
            ("a:1:{i:0;i:1;", 13),
            ("a:1:{d:1;i:1;}", 9),
            ("a:2:{i:0;i:5;i:1;r:2;}", 21),
            ("R:1;", 4),
        ] {
            match u(s) {
                Err(Error::Failed { offset: o, .. }) => assert_eq!(o, Some(offset), "{s}"),
                other => panic!("{s}: {other:?}"),
            }
        }
        assert!(matches!(u("a:1:{i:0;R:1;}"), Err(Error::Unsupported(_))));
    }

    #[test]
    fn back_references_read_the_container_once() {
        // One container of 20,000 entries referenced 20,000 times: rebuilt on every
        // reference, this is 400 million element copies; reused, it is 20,000 clones.
        let n = 20_000;
        let mut s = format!("a:{}:{{i:0;a:{n}:{{", n + 1);
        for i in 0..n {
            s.push_str(&format!("i:{i};i:{i};"));
        }
        s.push('}');
        for i in 1..=n {
            s.push_str(&format!("i:{i};R:2;"));
        }
        s.push('}');

        let started = std::time::Instant::now();
        let Value::Array(outer) = u(&s).unwrap().value else { panic!() };
        assert!(started.elapsed() < std::time::Duration::from_secs(5), "took {:?}", started.elapsed());
        assert_eq!(outer.len(), n + 1);
        let Some(Value::Array(last)) = outer.get(&ArrayKey::Int(n as i64)) else { panic!() };
        assert_eq!(last.len(), n);
    }

    #[test]
    fn back_references_follow_a_location_a_duplicate_key_reused() {
        // The first R:2 reads [1]; the duplicate key 0 then puts [9] in that location,
        // which the second R:2 reads.
        let r = u("a:4:{i:0;a:1:{i:0;i:1;}i:1;R:2;i:0;a:1:{i:0;i:9;}i:2;R:2;}").unwrap().value;
        assert_eq!(r.to_json(), json!([[9], [1], [9]]));

        let r = u(
            r#"a:3:{i:0;O:8:"stdClass":3:{s:1:"p";a:1:{i:0;i:1;}s:1:"q";R:3;s:1:"p";a:1:{i:0;i:9;}}i:1;R:3;i:2;R:2;}"#,
        )
        .unwrap()
        .value;
        assert_eq!(r.to_json(), json!([{"p": [9], "q": [1]}, [9], {"p": [9], "q": [1]}]));

        let r = u(r#"a:2:{i:0;O:8:"stdClass":2:{s:1:"p";a:1:{i:0;i:1;}s:1:"q";R:3;}i:1;R:2;}"#).unwrap().value;
        assert_eq!(r.to_json(), json!([{"p": [1], "q": [1]}, {"p": [1], "q": [1]}]));
    }
}