Skip to main content

php_std/types/
array.rs

1//! [`Array`]: a PHP array (an ordered map with integer and string keys).
2
3use std::fmt;
4use std::hash::{BuildHasher, Hash, Hasher};
5use std::sync::atomic::{AtomicU8, Ordering};
6use std::sync::{Arc, OnceLock};
7
8use hashbrown::{HashTable, hash_table};
9
10use super::{Extension, Never, Str, Value};
11
12/// A PHP array key: an integer or a byte string.
13///
14/// PHP turns canonical decimal integer strings into integer keys
15/// (`$a["7"]` is `$a[7]`, `"07"` and `"-0"` stay strings):
16/// [`ArrayKey::normalize`] applies that rule. [`Array`] stores keys as
17/// given, because some producers (igbinary, object property tables) keep
18/// numeric strings as string keys.
19#[derive(Clone, PartialEq, Eq)]
20pub enum ArrayKey {
21    /// An integer key.
22    Int(i64),
23    /// A string key, as bytes.
24    Str(Str),
25}
26
27/// A borrowed [`ArrayKey`], used to look keys up and to iterate packed
28/// arrays (which store no keys).
29#[derive(Clone, Copy, PartialEq, Eq, Debug)]
30pub enum KeyRef<'a> {
31    /// An integer key.
32    Int(i64),
33    /// A string key, as bytes.
34    Str(&'a [u8]),
35}
36
37/// `ZEND_HANDLE_NUMERIC_STR`: the integer a string array key becomes, if any.
38///
39/// An optional `-` and decimal digits without leading zeros (`"0"` itself is
40/// allowed, `"-0"` is not), within the `i64` range.
41pub fn numeric_key(key: &[u8]) -> Option<i64> {
42    let (negative, digits) = match key.split_first() {
43        Some((b'-', rest)) => (true, rest),
44        _ => (false, key),
45    };
46    if digits.is_empty() || digits.len() > 19 || !digits.iter().all(u8::is_ascii_digit) {
47        return None;
48    }
49    if digits[0] == b'0' && (digits.len() > 1 || negative) {
50        return None;
51    }
52    let mut magnitude: u64 = 0;
53    for d in digits {
54        magnitude = magnitude.checked_mul(10)?.checked_add(u64::from(d - b'0'))?;
55    }
56    if negative {
57        if magnitude <= i64::MAX as u64 + 1 { Some((magnitude as i64).wrapping_neg()) } else { None }
58    } else {
59        i64::try_from(magnitude).ok()
60    }
61}
62
63impl ArrayKey {
64    /// The key PHP uses for a string offset: `"12"` is `Int(12)`; `"012"`,
65    /// `"-0"`, `"1.5"` and `" 1"` stay strings.
66    pub fn normalize(s: Str) -> Self {
67        match numeric_key(&s) {
68            Some(i) => ArrayKey::Int(i),
69            None => ArrayKey::Str(s),
70        }
71    }
72
73    /// The key, borrowed.
74    pub fn as_ref(&self) -> KeyRef<'_> {
75        match self {
76            ArrayKey::Int(i) => KeyRef::Int(*i),
77            ArrayKey::Str(s) => KeyRef::Str(s),
78        }
79    }
80}
81
82impl Hash for ArrayKey {
83    /// Hashes the key as its [`KeyRef`], so borrowed lookups find it.
84    fn hash<H: Hasher>(&self, state: &mut H) {
85        self.as_ref().hash(state);
86    }
87}
88
89impl Hash for KeyRef<'_> {
90    /// Hashes the key in one write (an integer and a string may collide,
91    /// which equality tells apart).
92    fn hash<H: Hasher>(&self, state: &mut H) {
93        match self {
94            KeyRef::Int(i) => state.write_u64(*i as u64),
95            KeyRef::Str(s) => state.write(s),
96        }
97    }
98}
99
100impl<'a> KeyRef<'a> {
101    /// The key PHP uses for a string offset (see [`ArrayKey::normalize`]).
102    pub fn normalize(s: &'a [u8]) -> Self {
103        match numeric_key(s) {
104            Some(i) => KeyRef::Int(i),
105            None => KeyRef::Str(s),
106        }
107    }
108
109    /// The key, owned.
110    pub fn to_owned(self) -> ArrayKey {
111        match self {
112            KeyRef::Int(i) => ArrayKey::Int(i),
113            KeyRef::Str(s) => ArrayKey::Str(Str::copy_from(s)),
114        }
115    }
116}
117
118impl fmt::Debug for ArrayKey {
119    /// Writes the integer, or the string quoted.
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        match self {
122            ArrayKey::Int(i) => write!(f, "{i}"),
123            ArrayKey::Str(s) => write!(f, "{s:?}"),
124        }
125    }
126}
127
128impl From<i64> for ArrayKey {
129    /// The integer key `i`.
130    fn from(i: i64) -> Self {
131        ArrayKey::Int(i)
132    }
133}
134
135/// A string key, normalised like `$a["..."]`.
136impl From<&str> for ArrayKey {
137    /// The key `$a["..."]` uses: canonical integer strings become integer keys.
138    fn from(s: &str) -> Self {
139        ArrayKey::normalize(Str::from(s))
140    }
141}
142
143/// `$a[] = $v` failed: the next integer key would be past `PHP_INT_MAX`
144/// ("Cannot add element to the array as the next element is already occupied").
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub struct ArrayFull;
147
148impl fmt::Display for ArrayFull {
149    /// Writes PHP's error message.
150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151        f.write_str("Cannot add element to the array as the next element is already occupied")
152    }
153}
154
155impl std::error::Error for ArrayFull {}
156
157/// A PHP array: an ordered map from [`ArrayKey`] to [`Value`].
158///
159/// Packed (a `Vec`, no stored keys) while it is a list `0, 1, 2, ...` whose
160/// next free index is its length; an ordered hash otherwise. The switch is
161/// invisible. Semantics follow the engine: assigning an existing key keeps
162/// its position, a removed key assigned again goes to the end, and `push`
163/// uses the next free integer key (`nNextFreeElement`): one past the largest
164/// integer key inserted, except that the engine's packed arrays (integer keys
165/// in ascending order, possibly with holes) set it to one past the key they
166/// append, which lowers it after trailing elements were removed
167/// (`[0, 1, 2]`, unset 1 and 2, `$a[1] = x`, then `$a[]` uses 2). That
168/// state is tracked as the engine does (`nNumUsed`, `nTableSize`), with the
169/// table size an array of `n` elements is created with (`max(8, 2^k >= n)`).
170///
171/// Copy-on-write, like the engine's arrays: a clone shares the elements
172/// (an atomic reference count, so values can cross threads) and the first
173/// mutation of a shared array copies it. Mutating a clone never changes the
174/// original. A new empty array allocates nothing.
175pub struct Array<X: Extension = Never> {
176    /// `None`: a new empty array (an empty packed list).
177    repr: Option<Arc<Repr<X>>>,
178}
179
180impl<X: Extension> Drop for Array<X> {
181    /// Frees the elements without recursion, so arrays nested thousands of
182    /// levels deep (which the decoders accept) do not exhaust the stack.
183    fn drop(&mut self) {
184        let Some(repr) = self.repr.take().and_then(Arc::into_inner) else { return };
185        let mut pending: Vec<Repr<X>> = Vec::new();
186        let mut current = repr;
187        loop {
188            let mut detach = |v: &mut Value<X>| {
189                if let Value::Array(a) | Value::Object(a) = v
190                    && let Some(inner) = a.repr.take().and_then(Arc::into_inner)
191                {
192                    pending.push(inner);
193                }
194            };
195            match &mut current {
196                Repr::Packed(v) => v.iter_mut().for_each(&mut detach),
197                Repr::Hash { map, .. } => map.for_each_value(&mut detach),
198            }
199            drop(current);
200            match pending.pop() {
201                Some(next) => current = next,
202                None => return,
203            }
204        }
205    }
206}
207
208impl<X: Extension> Clone for Array<X> {
209    /// Shares the elements (copied on the first mutation of either side).
210    fn clone(&self) -> Self {
211        Array { repr: self.repr.clone() }
212    }
213}
214
215/// Up to this many entries, a hash array's table is a list searched in
216/// order: no index to allocate and no keys to hash.
217const SMALL: usize = 8;
218
219/// Up to this many entries, a table taken as it is (a decoded object) is
220/// checked for repeated keys without hashing them, and only indexed once
221/// it has been searched [`SCANS`] times: most decoded objects are read a
222/// few times, or only iterated.
223const LAZY: usize = 64;
224
225/// How many lookups scan an unindexed table before it is indexed.
226const SCANS: u8 = 8;
227
228/// The hash representation's entries, in order, and past [`SMALL`] entries
229/// an index of their positions by key (made on demand for a table taken
230/// as it is, see [`LAZY`]).
231///
232/// The entries are kept as they were added (an object decoded with its
233/// members in order is taken as it is), and the index only holds positions.
234struct Table<X: Extension> {
235    entries: Vec<(ArrayKey, Value<X>)>,
236    /// When set, it holds every entry.
237    index: OnceLock<Index>,
238    /// Lookups that scanned the entries while unindexed: a hint (readers on
239    /// several threads may lose counts), never a correctness concern.
240    scans: AtomicU8,
241}
242
243impl<X: Extension> Clone for Table<X> {
244    /// The same entries, and the index when it is made.
245    fn clone(&self) -> Self {
246        Table { entries: self.entries.clone(), index: self.index.clone(), scans: AtomicU8::new(0) }
247    }
248}
249
250/// A summary of a key that equal keys share: its length and its first and
251/// last eight bytes (an integer key is its value), read in at most two
252/// loads, so most different keys are told apart without comparing them.
253#[inline]
254fn fingerprint(k: KeyRef<'_>) -> u64 {
255    let s = match k {
256        KeyRef::Int(i) => return i as u64,
257        KeyRef::Str(s) => s,
258    };
259    let n = s.len();
260    let word = |at: usize| u64::from_le_bytes(s[at..at + 8].try_into().unwrap_or_default());
261    let half = |at: usize| u64::from(u32::from_le_bytes(s[at..at + 4].try_into().unwrap_or_default()));
262    let (head, tail) = if n >= 8 {
263        (word(0), word(n - 8))
264    } else if n >= 4 {
265        (half(0), half(n - 4))
266    } else if n > 0 {
267        (u64::from(s[0]) | u64::from(s[n / 2]) << 8, u64::from(s[n - 1]))
268    } else {
269        (0, 0)
270    };
271    head ^ tail.rotate_left(29) ^ (n as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15)
272}
273
274/// Positions of a table's entries by key, with a fast hasher seeded randomly
275/// (keys come from requests).
276#[derive(Clone)]
277struct Index {
278    positions: HashTable<usize>,
279    hasher: foldhash::fast::RandomState,
280}
281
282impl Index {
283    fn with_capacity(n: usize) -> Self {
284        Index { positions: HashTable::with_capacity(n), hasher: Default::default() }
285    }
286
287    fn hash(&self, k: KeyRef<'_>) -> u64 {
288        self.hasher.hash_one(k)
289    }
290
291    /// The index of `entries`, or `None` when two have the same key.
292    fn of<X: Extension>(entries: &[(ArrayKey, Value<X>)], capacity: usize) -> Option<Index> {
293        let mut index = Index::with_capacity(capacity);
294        for (i, (k, _)) in entries.iter().enumerate() {
295            let hash = index.hash(k.as_ref());
296            match index.positions.entry(
297                hash,
298                |&j| entries[j].0 == *k,
299                |&j| index.hasher.hash_one(entries[j].0.as_ref()),
300            ) {
301                hash_table::Entry::Occupied(_) => return None,
302                hash_table::Entry::Vacant(slot) => {
303                    slot.insert(i);
304                }
305            }
306        }
307        Some(index)
308    }
309
310    /// The index of `entries`, whose keys are all different.
311    fn build<X: Extension>(entries: &[(ArrayKey, Value<X>)], capacity: usize) -> Index {
312        let mut index = Index::with_capacity(capacity.max(entries.len()));
313        for (i, (k, _)) in entries.iter().enumerate() {
314            let hash = index.hash(k.as_ref());
315            let hasher = &index.hasher;
316            index.positions.insert_unique(hash, i, |&j| hasher.hash_one(entries[j].0.as_ref()));
317        }
318        index
319    }
320}
321
322/// Whether no two of `entries` (at most [`LAZY`]) have the same key, telling
323/// them apart by [`fingerprint`]; `false` may also mean that two
324/// fingerprints are alike, past [`SMALL`] entries.
325fn distinct<X: Extension>(entries: &[(ArrayKey, Value<X>)]) -> bool {
326    let n = entries.len();
327    debug_assert!(n <= LAZY);
328    if n <= 4 {
329        // A few keys: compared directly (most differ in length).
330        return (1..n).all(|i| (0..i).all(|j| entries[i].0 != entries[j].0));
331    }
332    if n <= SMALL {
333        let mut prints = [0u64; SMALL];
334        for (print, (k, _)) in prints.iter_mut().zip(entries) {
335            *print = fingerprint(k.as_ref());
336        }
337        // Pairs compared by fingerprint first: only equal fingerprints (equal
338        // keys, or rarely keys alike at both ends) compare bytes.
339        return (1..n).all(|i| (0..i).all(|j| prints[i] != prints[j] || entries[i].0 != entries[j].0));
340    }
341    let mut prints = [0u64; LAZY];
342    for (print, (k, _)) in prints.iter_mut().zip(entries) {
343        *print = fingerprint(k.as_ref());
344    }
345    // Sorted, equal fingerprints are neighbours.
346    let prints = &mut prints[..n];
347    prints.sort_unstable();
348    prints.windows(2).all(|w| w[0] != w[1])
349}
350
351impl<X: Extension> Table<X> {
352    fn with_capacity(n: usize) -> Self {
353        let index = if n > SMALL { OnceLock::from(Index::with_capacity(n)) } else { OnceLock::new() };
354        Table { entries: Vec::with_capacity(n), index, scans: AtomicU8::new(0) }
355    }
356
357    /// A table of `entries` as they are, when their keys are all different
358    /// (`entries` back otherwise).
359    fn of(entries: Vec<(ArrayKey, Value<X>)>) -> Result<Self, Vec<(ArrayKey, Value<X>)>> {
360        let n = entries.len();
361        if n <= LAZY && distinct(&entries) {
362            return Ok(Table { entries, index: OnceLock::new(), scans: AtomicU8::new(0) });
363        }
364        if n <= SMALL {
365            return Err(entries);
366        }
367        // Many entries, or fingerprints alike: hashed, and indexed.
368        match Index::of(&entries, n) {
369            Some(index) => Ok(Table { entries, index: OnceLock::from(index), scans: AtomicU8::new(0) }),
370            None => Err(entries),
371        }
372    }
373
374    fn len(&self) -> usize {
375        self.entries.len()
376    }
377
378    /// The index: `None` for a small table, and for one not indexed yet
379    /// that was searched fewer than [`SCANS`] times (made now otherwise).
380    #[inline]
381    fn index(&self) -> Option<&Index> {
382        if let Some(index) = self.index.get() {
383            return Some(index);
384        }
385        if self.entries.len() <= SMALL {
386            return None;
387        }
388        let scans = self.scans.load(Ordering::Relaxed);
389        if scans < SCANS {
390            self.scans.store(scans + 1, Ordering::Relaxed);
391            return None;
392        }
393        Some(self.index.get_or_init(|| Index::build(&self.entries, 0)))
394    }
395
396    /// Where `k` is in the entries.
397    fn position(&self, k: KeyRef<'_>) -> Option<usize> {
398        match self.index() {
399            None => self.entries.iter().position(|(key, _)| key.as_ref() == k),
400            Some(index) => index.positions.find(index.hash(k), |&i| self.entries[i].0.as_ref() == k).copied(),
401        }
402    }
403
404    fn get(&self, k: KeyRef<'_>) -> Option<&Value<X>> {
405        self.position(k).map(|i| &self.entries[i].1)
406    }
407
408    fn get_mut(&mut self, k: KeyRef<'_>) -> Option<&mut Value<X>> {
409        self.position(k).map(|i| &mut self.entries[i].1)
410    }
411
412    fn contains_key(&self, k: KeyRef<'_>) -> bool {
413        self.position(k).is_some()
414    }
415
416    /// Sets `k` (in place when it exists, at the end otherwise); returns the previous value.
417    #[inline]
418    fn insert(&mut self, k: ArrayKey, value: Value<X>) -> Option<Value<X>> {
419        // A table that grows is indexed from [`SMALL`] entries on.
420        if self.entries.len() >= SMALL && self.index.get().is_none() {
421            self.reindex();
422        }
423        if let Some(i) = self.position(k.as_ref()) {
424            return Some(std::mem::replace(&mut self.entries[i].1, value));
425        }
426        let i = self.entries.len();
427        self.entries.push((k, value));
428        if let Some(index) = self.index.get_mut() {
429            let entries = &self.entries;
430            let hash = index.hash(entries[i].0.as_ref());
431            let hasher = &index.hasher;
432            index.positions.insert_unique(hash, i, |&j| hasher.hash_one(entries[j].0.as_ref()));
433        }
434        None
435    }
436
437    /// Indexes the entries (their keys are different).
438    #[cold]
439    fn reindex(&mut self) {
440        self.index = OnceLock::from(Index::build(&self.entries, self.entries.capacity().max(SMALL * 2)));
441    }
442
443    /// Removes `k`, shifting the entries after it.
444    fn shift_remove(&mut self, k: &ArrayKey) -> Option<Value<X>> {
445        let i = self.position(k.as_ref())?;
446        if let Some(index) = self.index.get_mut() {
447            if let Ok(slot) = index.positions.find_entry(index.hasher.hash_one(k.as_ref()), |&j| j == i) {
448                slot.remove();
449            }
450            if i + 1 < self.entries.len() {
451                index.positions.iter_mut().filter(|j| **j > i).for_each(|j| *j -= 1);
452            }
453        }
454        Some(self.entries.remove(i).1)
455    }
456
457    fn last_key(&self) -> Option<&ArrayKey> {
458        self.entries.last().map(|(k, _)| k)
459    }
460
461    fn reserve(&mut self, additional: usize) {
462        self.entries.reserve(additional);
463        match self.index.get_mut() {
464            Some(index) => {
465                let entries = &self.entries;
466                let hasher = &index.hasher;
467                index.positions.reserve(additional, |&j| hasher.hash_one(entries[j].0.as_ref()));
468            }
469            None if self.entries.len() + additional > SMALL => self.reindex(),
470            None => {}
471        }
472    }
473
474    /// Keeps the entries `keep` accepts, in order.
475    fn retain(&mut self, mut keep: impl FnMut() -> bool) {
476        self.entries.retain(|_| keep());
477        if self.index.get().is_some() {
478            self.reindex();
479        }
480    }
481
482    /// Calls `f` with each value.
483    fn for_each_value(&mut self, f: impl FnMut(&mut Value<X>)) {
484        self.entries.iter_mut().map(|(_, v)| v).for_each(f);
485    }
486}
487
488#[derive(Clone)]
489enum Repr<X: Extension> {
490    Packed(Vec<Value<X>>),
491    Hash {
492        map: Table<X>,
493        /// `nNextFreeElement`: `None` until an integer key is used.
494        next: Option<i64>,
495        /// Set while the engine would keep the array packed.
496        packed: Option<Packed>,
497    },
498}
499
500impl<X: Extension> Repr<X> {
501    /// The hash representation (a packed `Vec` becomes an engine-packed hash).
502    fn hash(&mut self) -> (&mut Table<X>, &mut Option<i64>, &mut Option<Packed>) {
503        let repr = self;
504        if let Repr::Packed(v) = repr {
505            let next = if v.is_empty() { None } else { Some(v.len() as i64) };
506            let packed = Some(Packed { used: v.len() as u64, table: table_size(v.len()) });
507            // The room the list had, and at least room for the entry being added.
508            let mut map = Table::with_capacity(v.capacity().max(v.len() + 1));
509            for (i, v) in std::mem::take(v).into_iter().enumerate() {
510                map.insert(ArrayKey::Int(i as i64), v);
511            }
512            *repr = Repr::Hash { map, next, packed };
513        }
514        match repr {
515            Repr::Hash { map, next, packed } => (map, next, packed),
516            Repr::Packed(_) => unreachable!(),
517        }
518    }
519
520    /// `$a[$k] = $v` (the key as given, see [`ArrayKey::normalize`]): an
521    /// existing key keeps its position. Returns the previous value.
522    fn set(&mut self, k: ArrayKey, v: Value<X>) -> Option<Value<X>> {
523        if let (Repr::Packed(list), ArrayKey::Int(i)) = (&mut *self, &k)
524            && let Ok(i) = usize::try_from(*i)
525        {
526            if i < list.len() {
527                return Some(std::mem::replace(&mut list[i], v));
528            }
529            if i == list.len() {
530                list.push(v);
531                return None;
532            }
533        }
534        let (map, next, packed) = self.hash();
535        let ArrayKey::Int(h) = k else {
536            *packed = None;
537            return map.insert(k, v);
538        };
539        if let Some(p) = packed {
540            let hu = h as u64;
541            if hu < p.used {
542                if let Some(old) = map.get_mut(KeyRef::Int(h)) {
543                    return Some(std::mem::replace(old, v));
544                }
545                // Filling a hole keeps the order: the engine converts to a hash.
546                *packed = None;
547            } else {
548                if hu >= p.table && (hu >> 1) < p.table && (p.table >> 1) < map.len() as u64 {
549                    p.table *= 2;
550                }
551                if hu < p.table {
552                    // `add_to_packed`: the next free index is set, not raised.
553                    p.used = hu + 1;
554                    *next = Some(h + 1);
555                    map.insert(k, v);
556                    return None;
557                }
558                *packed = None;
559            }
560        }
561        match *next {
562            Some(n) if n > h => {}
563            _ => *next = Some(if h < i64::MAX { h + 1 } else { i64::MAX }),
564        }
565        map.insert(k, v)
566    }
567}
568
569/// The elements, borrowed.
570enum View<'a, X: Extension> {
571    Packed(&'a [Value<X>]),
572    Hash(&'a Table<X>),
573}
574
575/// The engine's packed-array bookkeeping.
576#[derive(Clone, Copy)]
577struct Packed {
578    /// `nNumUsed`: one past the last slot in use (removing trailing
579    /// elements lowers it).
580    used: u64,
581    /// `nTableSize`.
582    table: u64,
583}
584
585/// `zend_hash_check_size`: the table size of an array created for `n` elements.
586fn table_size(n: usize) -> u64 {
587    (n as u64).max(8).next_power_of_two()
588}
589
590impl<X: Extension> Default for Array<X> {
591    /// An empty array.
592    fn default() -> Self {
593        Self::new()
594    }
595}
596
597impl<X: Extension> Array<X> {
598    /// An empty array.
599    pub const fn new() -> Self {
600        Array { repr: None }
601    }
602
603    /// An empty array with room for `n` list elements.
604    pub fn with_capacity(n: usize) -> Self {
605        if n == 0 { Self::new() } else { Self::from_list(Vec::with_capacity(n)) }
606    }
607
608    /// `[$v0, $v1, ...]`.
609    pub fn from_list(v: Vec<Value<X>>) -> Self {
610        Array { repr: Some(Arc::new(Repr::Packed(v))) }
611    }
612
613    /// An array with these entries (in order, keys as given) and this next free index.
614    pub fn from_entries(entries: impl IntoIterator<Item = (ArrayKey, Value<X>)>, next: Option<i64>) -> Self {
615        let iter = entries.into_iter();
616        let mut map = Table::with_capacity(iter.size_hint().0);
617        for (k, v) in iter {
618            map.insert(k, v);
619        }
620        Array { repr: Some(Arc::new(Repr::Hash { map, next, packed: None })) }
621    }
622
623    fn view(&self) -> View<'_, X> {
624        match self.repr.as_deref() {
625            None => View::Packed(&[]),
626            Some(Repr::Packed(v)) => View::Packed(v),
627            Some(Repr::Hash { map, .. }) => View::Hash(map),
628        }
629    }
630
631    /// An identity for the elements: the same for clones that share them
632    /// and never reused while one of them is alive (a write to a shared
633    /// array copies it first). `None` for a new empty array.
634    pub fn id(&self) -> Option<usize> {
635        self.repr.as_ref().map(|r| Arc::as_ptr(r) as usize)
636    }
637
638    /// The elements, unshared (copied first when a clone shares them).
639    fn repr_mut(&mut self) -> &mut Repr<X> {
640        // `zend_array_dup()` of an empty array makes an uninitialized one
641        // that keeps the next free index: its first integer key below the
642        // minimum table size makes it packed again, setting that index.
643        if let Some(r) = &self.repr
644            && Arc::strong_count(r) > 1
645            && let Repr::Hash { map, next, .. } = &**r
646            && map.len() == 0
647        {
648            let next = *next;
649            let packed = Some(Packed { used: 0, table: table_size(0) });
650            self.repr = Some(Arc::new(Repr::Hash { map: Table::with_capacity(0), next, packed }));
651        }
652        Arc::make_mut(self.repr.get_or_insert_with(|| Arc::new(Repr::Packed(Vec::new()))))
653    }
654
655    /// Reserves room for `additional` more elements (nothing observable changes).
656    pub fn reserve(&mut self, additional: usize) {
657        if additional == 0 {
658            return;
659        }
660        match self.repr_mut() {
661            Repr::Packed(v) => v.reserve(additional),
662            Repr::Hash { map, .. } => map.reserve(additional),
663        }
664    }
665
666    /// `array_is_list()`: keys are exactly `0, 1, 2, ...` in order.
667    pub fn is_list(&self) -> bool {
668        match self.view() {
669            View::Packed(_) => true,
670            View::Hash(_) => self.keys().enumerate().all(|(i, k)| k == KeyRef::Int(i as i64)),
671        }
672    }
673
674    /// The number of elements.
675    pub fn len(&self) -> usize {
676        match self.view() {
677            View::Packed(v) => v.len(),
678            View::Hash(map) => map.len(),
679        }
680    }
681
682    /// Whether the array has no elements.
683    pub fn is_empty(&self) -> bool {
684        self.len() == 0
685    }
686
687    /// The key `push` would use, as PHP tracks it (`None`: no integer key yet, so `0`).
688    pub fn next_index(&self) -> Option<i64> {
689        match self.repr.as_deref() {
690            None => None,
691            Some(Repr::Packed(v)) if v.is_empty() => None,
692            Some(Repr::Packed(v)) => Some(v.len() as i64),
693            Some(Repr::Hash { next, .. }) => *next,
694        }
695    }
696
697    /// The value at `k`, if any (the key as given, not normalised).
698    pub fn get(&self, k: &ArrayKey) -> Option<&Value<X>> {
699        self.get_ref(k.as_ref())
700    }
701
702    /// The value at a borrowed key, if any (the key as given, not normalised).
703    pub fn get_ref(&self, k: KeyRef<'_>) -> Option<&Value<X>> {
704        match self.view() {
705            View::Packed(v) => match k {
706                KeyRef::Int(i) => usize::try_from(i).ok().and_then(|i| v.get(i)),
707                KeyRef::Str(_) => None,
708            },
709            View::Hash(map) => map.get(k),
710        }
711    }
712
713    /// `$a["..."]`: the key is normalised (`"7"` finds `7`).
714    pub fn get_str(&self, k: &str) -> Option<&Value<X>> {
715        self.get_ref(KeyRef::normalize(k.as_bytes()))
716    }
717
718    /// The value at `k`, mutably, if any (a shared array is copied first).
719    pub fn get_mut(&mut self, k: &ArrayKey) -> Option<&mut Value<X>> {
720        if !self.contains_key(k) {
721            return None;
722        }
723        match self.repr_mut() {
724            Repr::Packed(v) => match k {
725                ArrayKey::Int(i) => usize::try_from(*i).ok().and_then(|i| v.get_mut(i)),
726                ArrayKey::Str(_) => None,
727            },
728            Repr::Hash { map, .. } => map.get_mut(k.as_ref()),
729        }
730    }
731
732    /// Whether `k` is set.
733    pub fn contains_key(&self, k: &ArrayKey) -> bool {
734        self.get(k).is_some()
735    }
736
737    /// The hash representation (a packed `Vec` becomes an engine-packed hash).
738    fn hash(&mut self) -> (&mut Table<X>, &mut Option<i64>, &mut Option<Packed>) {
739        self.repr_mut().hash()
740    }
741
742    /// `$a[$k] = $v` (the key as given, see [`ArrayKey::normalize`]): an
743    /// existing key keeps its position. Returns the previous value.
744    pub fn set(&mut self, k: ArrayKey, v: Value<X>) -> Option<Value<X>> {
745        self.repr_mut().set(k, v)
746    }
747
748    /// `$a[] = $v`.
749    pub fn push(&mut self, v: Value<X>) -> Result<(), ArrayFull> {
750        if let Repr::Packed(list) = self.repr_mut() {
751            list.push(v);
752            return Ok(());
753        }
754        let (map, next, _) = self.hash();
755        let key = next.unwrap_or(0);
756        if map.contains_key(KeyRef::Int(key)) {
757            return Err(ArrayFull);
758        }
759        self.set(ArrayKey::Int(key), v);
760        Ok(())
761    }
762
763    /// `unset($a[$k])`: the key, if set again, goes to the end.
764    pub fn remove(&mut self, k: &ArrayKey) -> Option<Value<X>> {
765        self.get(k)?;
766        let (map, _, packed) = self.hash();
767        let old = map.shift_remove(k);
768        if let (Some(p), ArrayKey::Int(h)) = (packed, k)
769            && *h as u64 == p.used.wrapping_sub(1)
770        {
771            // Trailing slots are released.
772            p.used = match map.last_key() {
773                Some(ArrayKey::Int(last)) => *last as u64 + 1,
774                _ => 0,
775            };
776        }
777        old
778    }
779
780    /// A new array with the same keys, in the same order, and the value `f`
781    /// makes of each entry (`array_map()` with one array, which keeps the
782    /// keys): the same array in every other respect, next free index
783    /// included. No key is copied into a new table or looked up again.
784    pub fn map_values(&self, mut f: impl FnMut(KeyRef<'_>, &Value<X>) -> Value<X>) -> Array<X> {
785        let Some(repr) = self.repr.as_deref() else { return Array::new() };
786        let repr = match repr {
787            Repr::Packed(v) => Repr::Packed(v.iter().enumerate().map(|(i, v)| f(KeyRef::Int(i as i64), v)).collect()),
788            Repr::Hash { map, next, packed } => Repr::Hash {
789                map: Table {
790                    entries: map.entries.iter().map(|(k, v)| (k.clone(), f(k.as_ref(), v))).collect(),
791                    index: map.index.clone(),
792                    scans: AtomicU8::new(0),
793                },
794                next: *next,
795                packed: *packed,
796            },
797        };
798        Array { repr: Some(Arc::new(repr)) }
799    }
800
801    /// The entries in order, with borrowed keys.
802    pub fn iter(&self) -> Iter<'_, X> {
803        match self.view() {
804            View::Packed(v) => Iter::Packed(v.iter().enumerate()),
805            View::Hash(map) => Iter::Hash(map.entries.iter()),
806        }
807    }
808
809    /// The values in order.
810    pub fn values(&self) -> impl ExactSizeIterator<Item = &Value<X>> + DoubleEndedIterator {
811        self.iter().map(|(_, v)| v)
812    }
813
814    /// The keys in order.
815    pub fn keys(&self) -> impl ExactSizeIterator<Item = KeyRef<'_>> {
816        self.iter().map(|(k, _)| k)
817    }
818
819    /// Keeps the entries `f` accepts (in order); the next free index is unchanged.
820    pub fn retain(&mut self, mut f: impl FnMut(KeyRef<'_>, &Value<X>) -> bool) {
821        let keep: Vec<bool> = self.iter().map(|(k, v)| f(k, v)).collect();
822        if keep.iter().all(|&k| k) {
823            return;
824        }
825        let mut keep = keep.into_iter();
826        let (map, _, packed) = self.hash();
827        map.retain(|| keep.next().unwrap_or(true));
828        if let Some(p) = packed {
829            p.used = match map.last_key() {
830                Some(ArrayKey::Int(last)) => *last as u64 + 1,
831                _ => 0,
832            };
833        }
834    }
835}
836
837/// Entries of an [`Array`] in order.
838pub enum Iter<'a, X: Extension> {
839    /// Over a packed array: the keys are the positions.
840    Packed(std::iter::Enumerate<std::slice::Iter<'a, Value<X>>>),
841    /// Over a hash array.
842    Hash(std::slice::Iter<'a, (ArrayKey, Value<X>)>),
843}
844
845impl<'a, X: Extension> Iterator for Iter<'a, X> {
846    type Item = (KeyRef<'a>, &'a Value<X>);
847
848    /// The next entry.
849    fn next(&mut self) -> Option<Self::Item> {
850        match self {
851            Iter::Packed(it) => it.next().map(|(i, v)| (KeyRef::Int(i as i64), v)),
852            Iter::Hash(it) => it.next().map(|(k, v)| (k.as_ref(), v)),
853        }
854    }
855
856    /// The exact number of entries left.
857    fn size_hint(&self) -> (usize, Option<usize>) {
858        match self {
859            Iter::Packed(it) => it.size_hint(),
860            Iter::Hash(it) => it.size_hint(),
861        }
862    }
863}
864
865impl<X: Extension> DoubleEndedIterator for Iter<'_, X> {
866    /// The last entry left.
867    fn next_back(&mut self) -> Option<Self::Item> {
868        match self {
869            Iter::Packed(it) => it.next_back().map(|(i, v)| (KeyRef::Int(i as i64), v)),
870            Iter::Hash(it) => it.next_back().map(|(k, v)| (k.as_ref(), v)),
871        }
872    }
873}
874
875impl<X: Extension> ExactSizeIterator for Iter<'_, X> {}
876
877impl<X: Extension> IntoIterator for Array<X> {
878    type Item = (ArrayKey, Value<X>);
879    type IntoIter = Box<dyn Iterator<Item = (ArrayKey, Value<X>)>>;
880
881    /// The entries in order, with owned keys.
882    fn into_iter(self) -> Self::IntoIter {
883        // A shared array is copied.
884        let mut this = self;
885        match this.repr.take().map(Arc::unwrap_or_clone) {
886            None => Box::new(std::iter::empty()),
887            Some(Repr::Packed(v)) => Box::new(v.into_iter().enumerate().map(|(i, v)| (ArrayKey::Int(i as i64), v))),
888            Some(Repr::Hash { map, .. }) => Box::new(map.entries.into_iter()),
889        }
890    }
891}
892
893impl<'a, X: Extension> IntoIterator for &'a Array<X> {
894    type Item = (KeyRef<'a>, &'a Value<X>);
895    type IntoIter = Iter<'a, X>;
896
897    /// The entries in order, with borrowed keys.
898    fn into_iter(self) -> Self::IntoIter {
899        self.iter()
900    }
901}
902
903/// `$a[$k] = $v` for each pair.
904impl<X: Extension> FromIterator<(ArrayKey, Value<X>)> for Array<X> {
905    /// An array with each pair assigned in order, as `$a[$k] = $v`.
906    ///
907    /// Built unshared and presized: a list for an integer first key, a hash
908    /// for a string one (what assigning to an empty array leads to).
909    fn from_iter<T: IntoIterator<Item = (ArrayKey, Value<X>)>>(iter: T) -> Self {
910        // Taken as they come, and indexed once (or not at all) when the keys
911        // are strings and all different; assigned one by one otherwise.
912        Self::from_pairs(iter.into_iter().collect())
913    }
914}
915
916impl<X: Extension> Array<X> {
917    /// Each pair assigned in order to a new array, as `$a[$k] = $v`
918    /// ([`FromIterator`]). String keys, all different (a decoded object),
919    /// make the table as they are, with no copy.
920    pub(crate) fn from_pairs(entries: Vec<(ArrayKey, Value<X>)>) -> Self {
921        if entries.is_empty() || !entries.iter().all(|(k, _)| matches!(k, ArrayKey::Str(_))) {
922            return Self::assign(entries.into_iter());
923        }
924        match Table::of(entries) {
925            Ok(map) => Array { repr: Some(Arc::new(Repr::Hash { map, next: None, packed: None })) },
926            Err(entries) => Self::assign(entries.into_iter()),
927        }
928    }
929
930    /// Each pair assigned in order to a new array, as `$a[$k] = $v`.
931    fn assign(mut iter: impl Iterator<Item = (ArrayKey, Value<X>)>) -> Self {
932        let Some((k, v)) = iter.next() else { return Array::new() };
933        let n = iter.size_hint().0 + 1;
934        let mut repr = match k {
935            ArrayKey::Int(_) => Repr::Packed(Vec::with_capacity(n)),
936            ArrayKey::Str(_) => Repr::Hash { map: Table::with_capacity(n), next: None, packed: None },
937        };
938        repr.set(k, v);
939        for (k, v) in iter {
940            match (&mut repr, k) {
941                // A string key on a hash only goes into its table.
942                (Repr::Hash { map, packed, .. }, k @ ArrayKey::Str(_)) => {
943                    *packed = None;
944                    map.insert(k, v);
945                }
946                (repr, k) => {
947                    repr.set(k, v);
948                }
949            }
950        }
951        Array { repr: Some(Arc::new(repr)) }
952    }
953}
954
955/// An array assigned entry by entry, as [`FromIterator`] builds it, for
956/// the decoders: they read the entry count first, so the table is sized
957/// once, and each entry goes straight into it.
958pub(crate) struct Builder<X: Extension = Never> {
959    /// An empty list (no allocation) until the first entry decides.
960    repr: Repr<X>,
961    /// Room to make when the first entry decides the representation.
962    capacity: usize,
963}
964
965impl<X: Extension> Builder<X> {
966    /// An empty array with room for `capacity` entries.
967    pub(crate) fn new(capacity: usize) -> Self {
968        Builder { repr: Repr::Packed(Vec::new()), capacity }
969    }
970
971    /// `$a[$k] = $v` (the key as given).
972    #[inline]
973    pub(crate) fn set(&mut self, k: ArrayKey, v: Value<X>) {
974        match (&mut self.repr, k) {
975            // A string key on a hash only goes into its table.
976            (Repr::Hash { map, packed, .. }, k @ ArrayKey::Str(_)) => {
977                *packed = None;
978                map.insert(k, v);
979            }
980            // The next element of a list.
981            (Repr::Packed(list), ArrayKey::Int(i)) if i as u64 == list.len() as u64 => {
982                if list.capacity() == 0 {
983                    list.reserve_exact(self.capacity.max(1));
984                }
985                list.push(v);
986            }
987            // A string key first: a hash.
988            (Repr::Packed(list), k @ ArrayKey::Str(_)) if list.is_empty() => {
989                let mut map = Table::with_capacity(self.capacity);
990                map.insert(k, v);
991                self.repr = Repr::Hash { map, next: None, packed: None };
992            }
993            (repr, k) => {
994                repr.set(k, v);
995            }
996        }
997    }
998
999    /// The array.
1000    pub(crate) fn finish(self) -> Array<X> {
1001        match self.repr {
1002            Repr::Packed(list) if list.capacity() == 0 => Array::new(),
1003            repr => Array { repr: Some(Arc::new(repr)) },
1004        }
1005    }
1006}
1007
1008/// A list.
1009impl<X: Extension> FromIterator<Value<X>> for Array<X> {
1010    /// A list of the values.
1011    fn from_iter<T: IntoIterator<Item = Value<X>>>(iter: T) -> Self {
1012        Array::from_list(iter.into_iter().collect())
1013    }
1014}
1015
1016/// The same entries in the same order (structural, not PHP's `==`).
1017impl<X: Extension> PartialEq for Array<X> {
1018    /// Whether both have the same entries in the same order.
1019    fn eq(&self, other: &Self) -> bool {
1020        self.len() == other.len() && self.iter().zip(other.iter()).all(|(a, b)| a == b)
1021    }
1022}
1023
1024impl<X: Extension> fmt::Debug for Array<X> {
1025    /// Writes the entries as a map.
1026    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1027        f.debug_map().entries(self.iter()).finish()
1028    }
1029}
1030
1031impl ArrayKey {
1032    /// The key PHP uses for the string offset `key` (`$a["7"]` is `$a[7]`):
1033    /// [`ArrayKey::normalize`] of a copy of `key`.
1034    ///
1035    /// ```
1036    /// use php_std::ArrayKey;
1037    ///
1038    /// assert_eq!(ArrayKey::from_bytes(b"7"), ArrayKey::Int(7));
1039    /// assert_eq!(ArrayKey::from_bytes(b"07"), ArrayKey::Str("07".into()));
1040    /// ```
1041    pub fn from_bytes(key: &[u8]) -> Self {
1042        match numeric_key(key) {
1043            Some(i) => ArrayKey::Int(i),
1044            None => ArrayKey::Str(Str::copy_from(key)),
1045        }
1046    }
1047}
1048
1049#[cfg(test)]
1050mod tests {
1051    use super::*;
1052
1053    type A = Array<Never>;
1054
1055    fn keys(a: &A) -> Vec<ArrayKey> {
1056        a.keys().map(KeyRef::to_owned).collect()
1057    }
1058
1059    #[test]
1060    fn numeric_keys_like_php() {
1061        assert_eq!(numeric_key(b"0"), Some(0));
1062        assert_eq!(numeric_key(b"-3"), Some(-3));
1063        assert_eq!(numeric_key(b"9223372036854775807"), Some(i64::MAX));
1064        assert_eq!(numeric_key(b"-9223372036854775808"), Some(i64::MIN));
1065        assert_eq!(numeric_key(b"9223372036854775808"), None);
1066        for s in ["", "-", "-0", "07", "+1", " 1", "1 ", "1.0", "1e3", "0x1"] {
1067            assert_eq!(numeric_key(s.as_bytes()), None, "{s}");
1068        }
1069    }
1070
1071    #[test]
1072    fn set_keeps_position_and_push_uses_next_free() {
1073        let mut a = A::new();
1074        a.set("a".into(), Value::Int(1));
1075        a.set(ArrayKey::Int(5), Value::Int(2));
1076        a.set("a".into(), Value::Int(3));
1077        a.push(Value::Int(4)).unwrap();
1078        assert_eq!(keys(&a), vec![ArrayKey::Str("a".into()), ArrayKey::Int(5), ArrayKey::Int(6)]);
1079        assert_eq!(a.get_str("a"), Some(&Value::Int(3)));
1080        assert_eq!(a.get_str("6"), Some(&Value::Int(4)));
1081        assert!(!a.is_list());
1082    }
1083
1084    #[test]
1085    fn unset_then_set_appends_and_keeps_next_free() {
1086        let mut a: A = [Value::Int(0), Value::Int(1), Value::Int(2)].into_iter().collect();
1087        assert!(a.is_list());
1088        a.remove(&ArrayKey::Int(2));
1089        a.push(Value::Null).unwrap();
1090        assert_eq!(keys(&a), vec![ArrayKey::Int(0), ArrayKey::Int(1), ArrayKey::Int(3)]);
1091        a.remove(&ArrayKey::Int(0));
1092        a.set(ArrayKey::Int(0), Value::Bool(true));
1093        assert_eq!(keys(&a), vec![ArrayKey::Int(1), ArrayKey::Int(3), ArrayKey::Int(0)]);
1094        let mut b = A::new();
1095        b.set(ArrayKey::Int(-5), Value::Null);
1096        b.push(Value::Null).unwrap();
1097        assert_eq!(keys(&b), vec![ArrayKey::Int(-5), ArrayKey::Int(-4)]);
1098        let mut c = A::new();
1099        c.set(ArrayKey::Int(i64::MAX), Value::Null);
1100        assert_eq!(c.push(Value::Null), Err(ArrayFull));
1101    }
1102
1103    #[test]
1104    fn large_tables_find_keys_after_removals_and_repeats() {
1105        // Past eight entries the table is indexed: lookups, repeated keys
1106        // (kept in place, as decoded objects assign them) and removals in the
1107        // middle must keep every position right.
1108        let pairs: Vec<(ArrayKey, Value)> =
1109            (0..20).map(|i| (ArrayKey::from(format!("k{i}").as_str()), Value::Int(i))).collect();
1110        let mut a = A::from_pairs(pairs.clone());
1111        assert_eq!(a.len(), 20);
1112        assert_eq!(a.get_str("k13"), Some(&Value::Int(13)));
1113        a.remove(&ArrayKey::from("k3"));
1114        a.remove(&ArrayKey::from("k19"));
1115        a.set("k3".into(), Value::Null);
1116        assert_eq!(a.get_str("k4"), Some(&Value::Int(4)));
1117        assert_eq!(a.get_str("k18"), Some(&Value::Int(18)));
1118        assert_eq!(keys(&a).last(), Some(&ArrayKey::from("k3")));
1119        assert_eq!(a.get_str("k19"), None);
1120        let mut repeated = pairs;
1121        repeated.push((ArrayKey::from("k5"), Value::Bool(true)));
1122        let b = A::from_pairs(repeated);
1123        assert_eq!(b.len(), 20);
1124        assert_eq!(keys(&b)[5], ArrayKey::from("k5"));
1125        assert_eq!(b.get_str("k5"), Some(&Value::Bool(true)));
1126        let mut grown = A::new();
1127        for i in 0..12 {
1128            grown.set(ArrayKey::from(format!("g{i}").as_str()), Value::Int(i));
1129        }
1130        grown.retain(|k, _| k != KeyRef::Str(b"g2"));
1131        assert_eq!(grown.get_str("g11"), Some(&Value::Int(11)));
1132        assert_eq!(grown.get_str("g2"), None);
1133    }
1134
1135    #[test]
1136    fn clones_never_alias() {
1137        let original: A = [Value::Int(0), Value::Int(1)].into_iter().collect();
1138        let mut copy = original.clone();
1139        copy.set("k".into(), Value::Null);
1140        copy.remove(&ArrayKey::Int(0));
1141        *copy.get_mut(&ArrayKey::Int(1)).unwrap() = Value::Bool(true);
1142        assert_eq!(keys(&original), vec![ArrayKey::Int(0), ArrayKey::Int(1)]);
1143        assert_eq!(original.get(&ArrayKey::Int(1)), Some(&Value::Int(1)));
1144        let mut again = copy.clone();
1145        again.push(Value::Null).unwrap();
1146        assert_eq!(copy.len(), 2);
1147        assert_eq!(again.len(), 3);
1148        // Deep nesting is freed without recursion.
1149        let mut deep = A::new();
1150        for _ in 0..200_000 {
1151            deep = [Value::Array(deep)].into_iter().collect();
1152        }
1153        drop(deep);
1154    }
1155
1156    #[test]
1157    fn packed_appends_set_the_next_free_index() {
1158        // [0, 1, 2], unset 1 and 2, $a[1] = x: the engine's packed array
1159        // appends at 1 and the next free index becomes 2.
1160        let mut a: A = [Value::Int(0), Value::Int(1), Value::Int(2)].into_iter().collect();
1161        a.remove(&ArrayKey::Int(2));
1162        a.remove(&ArrayKey::Int(1));
1163        a.set(ArrayKey::Int(1), Value::Null);
1164        a.push(Value::Null).unwrap();
1165        assert_eq!(keys(&a), vec![ArrayKey::Int(0), ArrayKey::Int(1), ArrayKey::Int(2)]);
1166        // A hash keeps the largest: ['x' => 1, 6 => 2], unset 6, $a[] uses 7.
1167        let mut b = A::new();
1168        b.set("x".into(), Value::Null);
1169        b.set(ArrayKey::Int(6), Value::Null);
1170        b.remove(&ArrayKey::Int(6));
1171        b.push(Value::Null).unwrap();
1172        assert_eq!(keys(&b), vec![ArrayKey::from("x"), ArrayKey::Int(7)]);
1173    }
1174}