1use crate::{Ident, RuntimeValue};
4use hashbrown::HashTable;
5use rustc_hash::FxBuildHasher;
6use std::hash::BuildHasher;
7
8type Slot = Option<(Ident, RuntimeValue)>;
9
10const COMPACT_MIN_SLOTS: usize = 32;
12
13#[derive(Default)]
21pub struct DictMap {
22 slots: Vec<Slot>,
23 index: HashTable<usize>,
25}
26
27impl Clone for DictMap {
29 fn clone(&self) -> Self {
30 let mut slots = Vec::with_capacity(self.slots.capacity());
31 slots.extend_from_slice(&self.slots);
32 Self {
33 slots,
34 index: self.index.clone(),
35 }
36 }
37}
38
39impl std::fmt::Debug for DictMap {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 f.debug_map().entries(self.iter()).finish()
42 }
43}
44
45impl PartialEq for DictMap {
47 fn eq(&self, other: &Self) -> bool {
48 self.len() == other.len() && self.iter().all(|(k, v)| other.get(k) == Some(v))
49 }
50}
51
52mod sealed {
53 pub trait Sealed {
54 fn to_ident(&self) -> Option<crate::Ident>;
55 }
56}
57
58pub trait DictKey: sealed::Sealed {}
62
63impl sealed::Sealed for str {
64 #[inline]
65 fn to_ident(&self) -> Option<Ident> {
66 Ident::lookup(self)
67 }
68}
69impl DictKey for str {}
70
71impl sealed::Sealed for String {
72 #[inline]
73 fn to_ident(&self) -> Option<Ident> {
74 Ident::lookup(self)
75 }
76}
77impl DictKey for String {}
78
79impl sealed::Sealed for Ident {
80 #[inline]
81 fn to_ident(&self) -> Option<Ident> {
82 Some(*self)
83 }
84}
85impl DictKey for Ident {}
86
87impl<T: sealed::Sealed + ?Sized> sealed::Sealed for &T {
88 #[inline]
89 fn to_ident(&self) -> Option<Ident> {
90 (**self).to_ident()
91 }
92}
93impl<T: DictKey + ?Sized> DictKey for &T {}
94
95#[inline]
96fn hash_key(key: &Ident) -> u64 {
97 FxBuildHasher.hash_one(key)
98}
99
100#[inline]
101fn slot_hash(slots: &[Slot], slot: usize) -> u64 {
102 slots[slot].as_ref().map_or(0, |(k, _)| hash_key(k))
103}
104
105impl DictMap {
106 pub fn new() -> Self {
108 Self::default()
109 }
110
111 pub fn with_capacity(capacity: usize) -> Self {
113 Self {
114 slots: Vec::with_capacity(capacity),
115 index: HashTable::with_capacity(capacity),
116 }
117 }
118
119 pub fn len(&self) -> usize {
121 self.index.len()
122 }
123
124 pub fn is_empty(&self) -> bool {
126 self.index.is_empty()
127 }
128
129 #[inline]
131 pub fn get<K: DictKey + ?Sized>(&self, key: &K) -> Option<&RuntimeValue> {
132 let slot = self.find(&key.to_ident()?)?;
133 self.slots[slot].as_ref().map(|(_, v)| v)
134 }
135
136 #[inline]
138 pub fn get_mut<K: DictKey + ?Sized>(&mut self, key: &K) -> Option<&mut RuntimeValue> {
139 let slot = self.find(&key.to_ident()?)?;
140 self.slots[slot].as_mut().map(|(_, v)| v)
141 }
142
143 #[inline]
145 pub fn contains_key<K: DictKey + ?Sized>(&self, key: &K) -> bool {
146 key.to_ident().is_some_and(|key| self.find(&key).is_some())
147 }
148
149 #[inline]
152 pub fn insert(&mut self, key: impl Into<Ident>, value: RuntimeValue) -> Option<RuntimeValue> {
153 let key = key.into();
154 if let Some(slot) = self.find(&key) {
155 return self.slots[slot].as_mut().map(|(_, v)| std::mem::replace(v, value));
156 }
157 let slots = &self.slots;
158 self.index
159 .insert_unique(hash_key(&key), slots.len(), |&slot| slot_hash(slots, slot));
160 self.slots.push(Some((key, value)));
161 None
162 }
163
164 pub fn remove<K: DictKey + ?Sized>(&mut self, key: &K) -> Option<RuntimeValue> {
167 let key = key.to_ident()?;
168 let slots = &self.slots;
169 let slot = self
170 .index
171 .find_entry(
172 hash_key(&key),
173 |&slot| matches!(&slots[slot], Some((k, _)) if *k == key),
174 )
175 .ok()?
176 .remove()
177 .0;
178 let (_, value) = self.slots[slot].take()?;
179
180 if slot + 1 == self.slots.len() {
181 while matches!(self.slots.last(), Some(None)) {
182 self.slots.pop();
183 }
184 } else if self.slots.len() >= COMPACT_MIN_SLOTS && self.slots.len() > self.index.len() * 2 {
185 self.compact();
186 }
187 Some(value)
188 }
189
190 fn compact(&mut self) {
192 self.slots.retain(Option::is_some);
193 self.index.clear();
194 let slots = &self.slots;
195
196 for (position, slot) in slots.iter().enumerate() {
197 if let Some((key, _)) = slot {
198 self.index
199 .insert_unique(hash_key(key), position, |&slot| slot_hash(slots, slot));
200 }
201 }
202 }
203
204 #[inline]
205 fn find(&self, key: &Ident) -> Option<usize> {
206 self.index
207 .find(
208 hash_key(key),
209 |&slot| matches!(&self.slots[slot], Some((k, _)) if k == key),
210 )
211 .copied()
212 }
213
214 pub fn iter(&self) -> DictIter<'_> {
216 DictIter {
217 remaining: self.len(),
218 inner: self.slots.iter(),
219 }
220 }
221
222 pub fn iter_mut(&mut self) -> DictIterMut<'_> {
224 DictIterMut {
225 remaining: self.index.len(),
226 inner: self.slots.iter_mut(),
227 }
228 }
229
230 pub fn keys(&self) -> impl DoubleEndedIterator<Item = &Ident> + ExactSizeIterator {
232 self.iter().map(|(k, _)| k)
233 }
234
235 pub fn values(&self) -> impl DoubleEndedIterator<Item = &RuntimeValue> + ExactSizeIterator {
237 self.iter().map(|(_, v)| v)
238 }
239
240 pub fn values_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut RuntimeValue> + ExactSizeIterator {
242 self.iter_mut().map(|(_, v)| v)
243 }
244}
245
246impl<K: DictKey + ?Sized> std::ops::Index<&K> for DictMap {
247 type Output = RuntimeValue;
248
249 fn index(&self, key: &K) -> &RuntimeValue {
251 self.get(key).expect("DictMap: key not found")
252 }
253}
254
255impl<K: Into<Ident>> FromIterator<(K, RuntimeValue)> for DictMap {
256 fn from_iter<I: IntoIterator<Item = (K, RuntimeValue)>>(iter: I) -> Self {
257 let mut map = Self::new();
258 map.extend(iter);
259 map
260 }
261}
262
263impl<K: Into<Ident>> Extend<(K, RuntimeValue)> for DictMap {
264 fn extend<I: IntoIterator<Item = (K, RuntimeValue)>>(&mut self, iter: I) {
265 for (key, value) in iter {
266 self.insert(key, value);
267 }
268 }
269}
270
271pub struct DictIntoIter {
273 inner: std::vec::IntoIter<Slot>,
274 remaining: usize,
275}
276
277pub struct DictIter<'a> {
279 inner: std::slice::Iter<'a, Slot>,
280 remaining: usize,
281}
282
283pub struct DictIterMut<'a> {
285 inner: std::slice::IterMut<'a, Slot>,
286 remaining: usize,
287}
288
289macro_rules! slot_iterator {
290 ($ty:ty, $item:ty, $slot:ident => $conv:expr) => {
291 impl<'a> Iterator for $ty {
292 type Item = $item;
293
294 #[inline]
295 fn next(&mut self) -> Option<Self::Item> {
296 for $slot in self.inner.by_ref() {
297 if let Some(item) = $conv {
298 debug_assert!(self.remaining > 0, "iterator count is out of sync");
299 self.remaining = self.remaining.saturating_sub(1);
300 return Some(item);
301 }
302 }
303 None
304 }
305
306 #[inline]
307 fn size_hint(&self) -> (usize, Option<usize>) {
308 (self.remaining, Some(self.remaining))
309 }
310 }
311
312 impl<'a> DoubleEndedIterator for $ty {
313 #[inline]
314 fn next_back(&mut self) -> Option<Self::Item> {
315 while let Some($slot) = self.inner.next_back() {
316 if let Some(item) = $conv {
317 debug_assert!(self.remaining > 0, "iterator count is out of sync");
318 self.remaining = self.remaining.saturating_sub(1);
319 return Some(item);
320 }
321 }
322 None
323 }
324 }
325
326 impl<'a> ExactSizeIterator for $ty {}
327 };
328}
329
330slot_iterator!(DictIntoIter, (Ident, RuntimeValue), slot => slot);
331slot_iterator!(DictIter<'a>, (&'a Ident, &'a RuntimeValue), slot => slot.as_ref().map(|(k, v)| (k, v)));
332slot_iterator!(DictIterMut<'a>, (&'a Ident, &'a mut RuntimeValue), slot => slot.as_mut().map(|(k, v)| (&*k, v)));
333
334impl IntoIterator for DictMap {
335 type Item = (Ident, RuntimeValue);
336 type IntoIter = DictIntoIter;
337
338 fn into_iter(self) -> Self::IntoIter {
339 DictIntoIter {
340 remaining: self.index.len(),
341 inner: self.slots.into_iter(),
342 }
343 }
344}
345
346impl<'a> IntoIterator for &'a DictMap {
347 type Item = (&'a Ident, &'a RuntimeValue);
348 type IntoIter = DictIter<'a>;
349
350 fn into_iter(self) -> Self::IntoIter {
351 self.iter()
352 }
353}
354
355impl<'a> IntoIterator for &'a mut DictMap {
356 type Item = (&'a Ident, &'a mut RuntimeValue);
357 type IntoIter = DictIterMut<'a>;
358
359 fn into_iter(self) -> Self::IntoIter {
360 self.iter_mut()
361 }
362}
363
364#[cfg(test)]
365mod tests {
366 use super::*;
367
368 fn sample() -> DictMap {
369 DictMap::from_iter([
370 ("a", RuntimeValue::Number(1.into())),
371 ("b", RuntimeValue::Number(2.into())),
372 ])
373 }
374
375 #[test]
376 fn test_lookup_by_str_string_and_ident() {
377 let dict = sample();
378 let expected = Some(&RuntimeValue::Number(1.into()));
379
380 assert_eq!(dict.get("a"), expected);
381 assert_eq!(dict.get(&"a".to_string()), expected);
382 assert_eq!(dict.get(&Ident::new("a")), expected);
383 assert!(dict.contains_key("b"));
384 }
385
386 #[test]
387 fn test_str_lookup_does_not_intern_missing_key() {
388 let mut dict = sample();
389
390 assert!(dict.get("dict_key_only_used_by_this_test").is_none());
391 assert!(!dict.contains_key("dict_key_only_used_by_this_test"));
392 assert!(dict.get_mut("dict_key_only_used_by_this_test").is_none());
393 assert!(dict.remove("dict_key_only_used_by_this_test").is_none());
394 assert!(Ident::lookup("dict_key_only_used_by_this_test").is_none());
395 }
396
397 #[test]
398 fn test_remove_keeps_insertion_order() {
399 let mut dict = sample();
400 dict.insert("c", RuntimeValue::Number(3.into()));
401
402 assert_eq!(dict.remove("a"), Some(RuntimeValue::Number(1.into())));
403 assert_eq!(dict.keys().map(Ident::to_string).collect::<Vec<_>>(), vec!["b", "c"]);
404 }
405
406 #[test]
407 fn test_insert_existing_key_keeps_position() {
408 let mut dict = sample();
409
410 assert_eq!(
411 dict.insert("a", RuntimeValue::Number(10.into())),
412 Some(RuntimeValue::Number(1.into()))
413 );
414 assert_eq!(
415 dict.iter().map(|(k, v)| (k.to_string(), v.clone())).collect::<Vec<_>>(),
416 vec![
417 ("a".to_string(), RuntimeValue::Number(10.into())),
418 ("b".to_string(), RuntimeValue::Number(2.into())),
419 ]
420 );
421 }
422
423 #[test]
424 fn test_remove_then_reinsert_moves_to_end() {
425 let mut dict = sample();
426 dict.remove("a");
427 dict.insert("a", RuntimeValue::Number(1.into()));
428
429 assert_eq!(dict.keys().map(Ident::to_string).collect::<Vec<_>>(), vec!["b", "a"]);
430 assert_eq!(dict.len(), 2);
431 }
432
433 #[test]
434 fn test_eq_ignores_order() {
435 let mut other = DictMap::new();
436 other.insert("b", RuntimeValue::Number(2.into()));
437 other.insert("a", RuntimeValue::Number(1.into()));
438
439 assert_eq!(sample(), other);
440 }
441
442 #[test]
443 fn test_fifo_eviction_compacts_and_keeps_order() {
444 let mut dict = DictMap::new();
445 for i in 0..200 {
446 dict.insert(format!("k{i}"), RuntimeValue::Number(i.into()));
447 if i >= 10 {
448 assert!(dict.remove(&format!("k{}", i - 10)).is_some());
449 }
450 }
451
452 assert_eq!(dict.len(), 10);
453 assert!(dict.slots.len() <= 32.max(dict.len() * 2 + 1));
454 let expected: Vec<_> = (190..200).map(|i| format!("k{i}")).collect();
455 assert_eq!(dict.keys().map(Ident::to_string).collect::<Vec<_>>(), expected);
456 assert_eq!(dict.iter().rev().count(), 10);
457 assert_eq!(dict.get("k195"), Some(&RuntimeValue::Number(195.into())));
458 }
459
460 #[rstest::rstest]
461 #[case::empty(&[], &[])]
462 #[case::remove_missing(&["-x"], &[])]
463 #[case::remove_only(&["a", "-a"], &[])]
464 #[case::remove_first(&["a", "b", "c", "-a"], &["b", "c"])]
465 #[case::remove_middle(&["a", "b", "c", "-b"], &["a", "c"])]
466 #[case::remove_last_then_push(&["a", "b", "-b", "c"], &["a", "c"])]
467 #[case::reinsert_moves_to_end(&["a", "b", "-a", "a"], &["b", "a"])]
468 #[case::duplicate_insert_keeps_position(&["a", "b", "a"], &["a", "b"])]
469 #[case::remove_all(&["a", "b", "-a", "-b"], &[])]
470 fn test_ops_yield_keys(#[case] ops: &[&str], #[case] expected: &[&str]) {
471 let mut dict = DictMap::new();
472 for (n, op) in ops.iter().enumerate() {
473 match op.strip_prefix('-') {
474 Some(key) => {
475 dict.remove(key);
476 }
477 None => {
478 dict.insert(*op, RuntimeValue::Number((n as i64).into()));
479 }
480 }
481 }
482
483 let forward: Vec<_> = dict.keys().map(Ident::to_string).collect();
484 let mut backward: Vec<_> = dict.keys().rev().map(Ident::to_string).collect();
485 backward.reverse();
486
487 assert_eq!(forward, expected);
488 assert_eq!(backward, expected);
489 assert_eq!(dict.len(), expected.len());
490 assert_eq!(dict.is_empty(), expected.is_empty());
491 }
492
493 #[test]
494 fn test_mixed_front_and_back_iteration_skips_holes() {
495 let mut dict = DictMap::new();
496 for i in 0..6 {
497 dict.insert(format!("h{i}"), RuntimeValue::Number(i.into()));
498 }
499 dict.remove("h0");
500 dict.remove("h3");
501 dict.remove("h5");
502
503 let mut iter = dict.iter();
504 assert_eq!(iter.len(), 3);
505 assert_eq!(iter.next().map(|(k, _)| k.to_string()), Some("h1".to_string()));
506 assert_eq!(iter.next_back().map(|(k, _)| k.to_string()), Some("h4".to_string()));
507 assert_eq!(iter.len(), 1);
508 assert_eq!(iter.next().map(|(k, _)| k.to_string()), Some("h2".to_string()));
509 assert!(iter.next().is_none());
510 assert!(iter.next_back().is_none());
511 }
512
513 #[test]
514 fn test_iter_mut_and_into_iter_skip_holes() {
515 let mut dict = sample();
516 dict.insert("c", RuntimeValue::Number(3.into()));
517 dict.remove("a");
518 for (_, v) in dict.iter_mut() {
519 *v = RuntimeValue::Number(0.into());
520 }
521 dict.values_mut().for_each(|v| *v = RuntimeValue::Number(7.into()));
522
523 let owned: Vec<_> = dict.into_iter().map(|(k, v)| (k.to_string(), v)).collect();
524 assert_eq!(
525 owned,
526 vec![
527 ("b".to_string(), RuntimeValue::Number(7.into())),
528 ("c".to_string(), RuntimeValue::Number(7.into())),
529 ]
530 );
531 }
532
533 #[test]
534 fn test_clone_and_get_mut_after_compaction() {
535 let mut dict = DictMap::new();
536 for i in 0..100 {
537 dict.insert(format!("c{i}"), RuntimeValue::Number(i.into()));
538 }
539 for i in 0..90 {
540 dict.remove(&format!("c{i}"));
541 }
542 let cloned = dict.clone();
543 *dict.get_mut("c95").unwrap() = RuntimeValue::Number(0.into());
544
545 assert_eq!(cloned.get("c95"), Some(&RuntimeValue::Number(95.into())));
546 assert_eq!(dict.get("c95"), Some(&RuntimeValue::Number(0.into())));
547 assert_ne!(cloned, dict);
548 assert!(dict.get("c0").is_none());
549 }
550
551 mod model {
552 use super::*;
553 use proptest::prelude::*;
554
555 #[derive(Clone, Debug)]
556 enum Op {
557 Insert(u8, i64),
558 Remove(u8),
559 Get(u8),
560 }
561
562 fn op() -> impl Strategy<Value = Op> {
563 prop_oneof![
564 (0u8..24, any::<i64>()).prop_map(|(k, v)| Op::Insert(k, v)),
565 (0u8..24).prop_map(Op::Remove),
566 (0u8..24).prop_map(Op::Get),
567 ]
568 }
569
570 proptest! {
571 #[test]
573 fn matches_ordered_list_model(ops in proptest::collection::vec(op(), 0..400)) {
574 let mut dict = DictMap::new();
575 let mut model: Vec<(String, i64)> = Vec::new();
576
577 for op in ops {
578 match op {
579 Op::Insert(k, v) => {
580 let key = format!("pk{k}");
581 let prev = dict.insert(key.as_str(), RuntimeValue::Number(v.into()));
582 match model.iter_mut().find(|(mk, _)| *mk == key) {
583 Some(entry) => {
584 prop_assert_eq!(prev, Some(RuntimeValue::Number(entry.1.into())));
585 entry.1 = v;
586 }
587 None => {
588 prop_assert_eq!(prev, None);
589 model.push((key, v));
590 }
591 }
592 }
593 Op::Remove(k) => {
594 let key = format!("pk{k}");
595 let removed = dict.remove(key.as_str());
596 let expected = model.iter().position(|(mk, _)| *mk == key).map(|i| model.remove(i).1);
597 prop_assert_eq!(removed, expected.map(|v| RuntimeValue::Number(v.into())));
598 }
599 Op::Get(k) => {
600 let key = format!("pk{k}");
601 let expected = model.iter().find(|(mk, _)| *mk == key).map(|(_, v)| RuntimeValue::Number((*v).into()));
602 prop_assert_eq!(dict.get(key.as_str()).cloned(), expected);
603 }
604 }
605
606 prop_assert_eq!(dict.len(), model.len());
607 }
608
609 let entries: Vec<_> = dict.iter().map(|(k, v)| (k.to_string(), v.clone())).collect();
610 let expected: Vec<_> = model.iter().map(|(k, v)| (k.clone(), RuntimeValue::Number((*v).into()))).collect();
611 prop_assert_eq!(&entries, &expected);
612 prop_assert_eq!(dict.iter().rev().count(), model.len());
613 prop_assert_eq!(dict.iter().len(), model.len());
614 prop_assert_eq!(dict.keys().len(), model.len());
615 prop_assert_eq!(dict.values().len(), model.len());
616 prop_assert_eq!(dict.clone().into_iter().len(), model.len());
617 prop_assert_eq!(dict.clone().into_iter().count(), model.len());
618 }
619 }
620 }
621}