1use 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#[derive(Clone, PartialEq, Eq)]
20pub enum ArrayKey {
21 Int(i64),
23 Str(Str),
25}
26
27#[derive(Clone, Copy, PartialEq, Eq, Debug)]
30pub enum KeyRef<'a> {
31 Int(i64),
33 Str(&'a [u8]),
35}
36
37pub 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 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 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 fn hash<H: Hasher>(&self, state: &mut H) {
85 self.as_ref().hash(state);
86 }
87}
88
89impl Hash for KeyRef<'_> {
90 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 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 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 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 fn from(i: i64) -> Self {
131 ArrayKey::Int(i)
132 }
133}
134
135impl From<&str> for ArrayKey {
137 fn from(s: &str) -> Self {
139 ArrayKey::normalize(Str::from(s))
140 }
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub struct ArrayFull;
147
148impl fmt::Display for ArrayFull {
149 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
157pub struct Array<X: Extension = Never> {
176 repr: Option<Arc<Repr<X>>>,
178}
179
180impl<X: Extension> Drop for Array<X> {
181 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 fn clone(&self) -> Self {
211 Array { repr: self.repr.clone() }
212 }
213}
214
215const SMALL: usize = 8;
218
219const LAZY: usize = 64;
224
225const SCANS: u8 = 8;
227
228struct Table<X: Extension> {
235 entries: Vec<(ArrayKey, Value<X>)>,
236 index: OnceLock<Index>,
238 scans: AtomicU8,
241}
242
243impl<X: Extension> Clone for Table<X> {
244 fn clone(&self) -> Self {
246 Table { entries: self.entries.clone(), index: self.index.clone(), scans: AtomicU8::new(0) }
247 }
248}
249
250#[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#[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 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 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
322fn distinct<X: Extension>(entries: &[(ArrayKey, Value<X>)]) -> bool {
326 let n = entries.len();
327 debug_assert!(n <= LAZY);
328 if n <= 4 {
329 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 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 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 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 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 #[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 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 #[inline]
418 fn insert(&mut self, k: ArrayKey, value: Value<X>) -> Option<Value<X>> {
419 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 #[cold]
439 fn reindex(&mut self) {
440 self.index = OnceLock::from(Index::build(&self.entries, self.entries.capacity().max(SMALL * 2)));
441 }
442
443 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 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 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 next: Option<i64>,
495 packed: Option<Packed>,
497 },
498}
499
500impl<X: Extension> Repr<X> {
501 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 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 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 *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 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
569enum View<'a, X: Extension> {
571 Packed(&'a [Value<X>]),
572 Hash(&'a Table<X>),
573}
574
575#[derive(Clone, Copy)]
577struct Packed {
578 used: u64,
581 table: u64,
583}
584
585fn 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 fn default() -> Self {
593 Self::new()
594 }
595}
596
597impl<X: Extension> Array<X> {
598 pub const fn new() -> Self {
600 Array { repr: None }
601 }
602
603 pub fn with_capacity(n: usize) -> Self {
605 if n == 0 { Self::new() } else { Self::from_list(Vec::with_capacity(n)) }
606 }
607
608 pub fn from_list(v: Vec<Value<X>>) -> Self {
610 Array { repr: Some(Arc::new(Repr::Packed(v))) }
611 }
612
613 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 pub fn id(&self) -> Option<usize> {
635 self.repr.as_ref().map(|r| Arc::as_ptr(r) as usize)
636 }
637
638 fn repr_mut(&mut self) -> &mut Repr<X> {
640 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 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 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 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 pub fn is_empty(&self) -> bool {
684 self.len() == 0
685 }
686
687 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 pub fn get(&self, k: &ArrayKey) -> Option<&Value<X>> {
699 self.get_ref(k.as_ref())
700 }
701
702 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 pub fn get_str(&self, k: &str) -> Option<&Value<X>> {
715 self.get_ref(KeyRef::normalize(k.as_bytes()))
716 }
717
718 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 pub fn contains_key(&self, k: &ArrayKey) -> bool {
734 self.get(k).is_some()
735 }
736
737 fn hash(&mut self) -> (&mut Table<X>, &mut Option<i64>, &mut Option<Packed>) {
739 self.repr_mut().hash()
740 }
741
742 pub fn set(&mut self, k: ArrayKey, v: Value<X>) -> Option<Value<X>> {
745 self.repr_mut().set(k, v)
746 }
747
748 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 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 p.used = match map.last_key() {
773 Some(ArrayKey::Int(last)) => *last as u64 + 1,
774 _ => 0,
775 };
776 }
777 old
778 }
779
780 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 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 pub fn values(&self) -> impl ExactSizeIterator<Item = &Value<X>> + DoubleEndedIterator {
811 self.iter().map(|(_, v)| v)
812 }
813
814 pub fn keys(&self) -> impl ExactSizeIterator<Item = KeyRef<'_>> {
816 self.iter().map(|(k, _)| k)
817 }
818
819 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
837pub enum Iter<'a, X: Extension> {
839 Packed(std::iter::Enumerate<std::slice::Iter<'a, Value<X>>>),
841 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 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 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 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 fn into_iter(self) -> Self::IntoIter {
883 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 fn into_iter(self) -> Self::IntoIter {
899 self.iter()
900 }
901}
902
903impl<X: Extension> FromIterator<(ArrayKey, Value<X>)> for Array<X> {
905 fn from_iter<T: IntoIterator<Item = (ArrayKey, Value<X>)>>(iter: T) -> Self {
910 Self::from_pairs(iter.into_iter().collect())
913 }
914}
915
916impl<X: Extension> Array<X> {
917 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 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 (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
955pub(crate) struct Builder<X: Extension = Never> {
959 repr: Repr<X>,
961 capacity: usize,
963}
964
965impl<X: Extension> Builder<X> {
966 pub(crate) fn new(capacity: usize) -> Self {
968 Builder { repr: Repr::Packed(Vec::new()), capacity }
969 }
970
971 #[inline]
973 pub(crate) fn set(&mut self, k: ArrayKey, v: Value<X>) {
974 match (&mut self.repr, k) {
975 (Repr::Hash { map, packed, .. }, k @ ArrayKey::Str(_)) => {
977 *packed = None;
978 map.insert(k, v);
979 }
980 (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 (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 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
1008impl<X: Extension> FromIterator<Value<X>> for Array<X> {
1010 fn from_iter<T: IntoIterator<Item = Value<X>>>(iter: T) -> Self {
1012 Array::from_list(iter.into_iter().collect())
1013 }
1014}
1015
1016impl<X: Extension> PartialEq for Array<X> {
1018 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 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1027 f.debug_map().entries(self.iter()).finish()
1028 }
1029}
1030
1031impl ArrayKey {
1032 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 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 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 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 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}