robinxx_map 0.1.0

High-performance, thread-safe open-addressing hash map using Robin Hood displacement & xxHash3.
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
//! Safe public API surface for `RobinHoodMap<K, V>`.
//!
//! Wraps `RawTable` with `SpinMutex`, exposing ergonomic thread-safe methods.
//! All operations acquire an internal spinlock to guarantee `Send + Sync` without
//! exposing mutable state directly. Iterator and Entry variants retain lock guards
//! to maintain isolation during traversal and conditional insertion.

use crate::entry::{Entry, OccupiedEntry, VacantEntry};
use crate::hash::RobinHoodKey;
use crate::iter::{Drain, Iter, IterMut, Keys, Values};
use crate::sync::{MutexGuard, SpinMutex};
use crate::table::RawTable;

/// Thread-safe Robin Hood hash map with xxHash3 and `SoA` layout.
///
/// # Summary
/// High-performance concurrent hash map wrapping `RawTable` with atomic spinlock.
///
/// # Description
/// `RobinHoodMap` provides a safe, public API over the low-level `RawTable`.
/// All mutations and lookups acquire an internal `SpinMutex` to guarantee
/// thread-safety (`Send + Sync`) without requiring external synchronization.
/// The map uses Robin Hood displacement to bound probe chains and triggers
/// automatic resizing at 80% load factor.
///
/// # Examples
/// ```
/// use robinxx_map::RobinHoodMap;
///
/// let map = RobinHoodMap::new();
/// map.insert("rust", 2024);
/// map.insert("c++", 2011);
///
/// assert_eq!(map.with_key(&"rust", |v| *v), Some(2024));
/// assert_eq!(map.len(), 2);
/// ```
///
/// # Panics
/// Panics on allocation failure (OOM) during initial construction or resize.
///
/// # Errors
/// Not applicable. Public methods use infallible return types (`bool`, `Option`).
///
/// # Safety
/// Public API is 100% safe. Internal `unsafe` is confined to `RawTable` and
/// strictly guarded by documented invariants. Thread-safety relies on atomic
/// CAS loop with `Acquire`/`Release` ordering.
///
/// # See Also
/// - [`RawTable`] for the underlying data structure.
/// - [`SpinMutex`] for the concurrency primitive.
pub struct RobinHoodMap<K, V> {
    table: SpinMutex<RawTable<K, V>>,
}

impl<K: RobinHoodKey + PartialEq, V> RobinHoodMap<K, V> {
    /// Creates an empty `RobinHoodMap` with default capacity.
    ///
    /// # Summary
    /// Constructs a new map with initial capacity of 16 slots.
    ///
    /// # Description
    /// Convenience constructor delegating to `RawTable::new()`. Suitable for
    /// small maps or when exact capacity is unknown.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map: RobinHoodMap<u32, String> = RobinHoodMap::new();
    /// assert_eq!(map.capacity(), 16);
    /// ```
    ///
    /// # Panics
    /// Panics if allocation fails (OOM).
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. Pure safe constructor.
    ///
    /// # See Also
    /// - [`with_capacity`](Self::with_capacity)
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self {
            table: SpinMutex::new(RawTable::new()),
        }
    }

    /// Creates an empty `RobinHoodMap` with specified minimum capacity.
    ///
    /// # Summary
    /// Constructs a new map rounded up to the nearest power-of-two capacity.
    ///
    /// # Description
    /// Pre-allocates sufficient slots to avoid immediate resize. Capacity is
    /// rounded up to the next power of two for bitwise masking optimization.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::<String, Vec<u8>>::with_capacity(100);
    /// assert!(map.capacity() >= 100);
    /// ```
    ///
    /// # Panics
    /// Panics if allocation fails (OOM).
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable.
    ///
    /// # See Also
    /// - [`new`](Self::new)
    #[inline]
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            table: SpinMutex::new(RawTable::with_capacity(capacity)),
        }
    }

    /// Returns the number of elements in the map.
    ///
    /// # Summary
    /// Retrieves the current element count in O(1) time.
    ///
    /// # Description
    /// Acquires spinlock briefly to read the internal size counter.
    /// Constant-time operation regardless of map size.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert(1, "a");
    /// assert_eq!(map.len(), 1);
    /// ```
    ///
    /// # Panics
    /// Never panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`capacity`](Self::capacity)
    /// - [`is_empty`](Self::is_empty)
    #[inline]
    pub fn len(&self) -> usize {
        self.table.lock().size()
    }

    /// Returns the total allocated capacity of the map.
    ///
    /// # Summary
    /// Retrieves the power-of-two slot count in O(1) time.
    ///
    /// # Description
    /// Returns the maximum number of elements before the next resize triggers.
    /// Capacity is always a power of two due to internal alignment requirements.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map: RobinHoodMap<&str, i32> = RobinHoodMap::with_capacity(50);
    /// assert_eq!(map.capacity(), 64);
    /// ```
    ///
    /// # Panics
    /// Never panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`len`](Self::len)
    /// - [`reserve`](Self::reserve)
    #[inline]
    pub fn capacity(&self) -> usize {
        self.table.lock().capacity()
    }

    /// Checks if the map contains zero elements.
    ///
    /// # Summary
    /// Returns `true` if the map is empty.
    ///
    /// # Description
    /// Equivalent to `len() == 0` but may skip unnecessary atomic operations
    /// depending on internal state visibility.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map: RobinHoodMap<u32, u32> = RobinHoodMap::new();
    /// assert!(map.is_empty());
    /// ```
    ///
    /// # Panics
    /// Never panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`len`](Self::len)
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.table.lock().is_empty()
    }

    /// Executes a read-only operation on the value associated with `key`.
    ///
    /// # Summary
    /// Applies closure `f` to the value if key exists, while holding the lock.
    ///
    /// # Description
    /// Acquires spinlock, probes for key, and if found, calls `f(&V)`.
    /// Lock is held for the duration of `f`. Returns `Some(f(&V))` or `None`.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert("key", 42);
    /// let result = map.with_key(&"key", |v| *v + 1);
    /// assert_eq!(result, Some(43));
    /// ```
    ///
    /// # Panics
    /// Panics if closure `f` panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`with_key_mut`](Self::with_key_mut)
    #[inline]
    pub fn with_key<F, R>(&self, key: &K, f: F) -> Option<R>
    where
        F: FnOnce(&V) -> R,
    {
        let guard = self.table.lock();
        guard.get(key).map(f)
    }

    /// Executes a mutable operation on the value associated with `key`.
    ///
    /// # Summary
    /// Applies closure `f` mutably to the value if key exists.
    ///
    /// # Description
    /// Acquires exclusive lock, probes for key, and calls `f(&mut V)`.
    /// Returns `Some(f(&mut V))` or `None`. Lock held during closure.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert("key", 42);
    /// let result = map.with_key_mut(&"key", |v| { *v += 10; *v });
    /// assert_eq!(result, Some(52));
    /// ```
    ///
    /// # Panics
    /// Panics if closure `f` panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`with_key`](Self::with_key)
    #[inline]
    pub fn with_key_mut<F, R>(&self, key: &K, f: F) -> Option<R>
    where
        F: FnOnce(&mut V) -> R,
    {
        let mut guard = self.table.lock();
        guard.get_mut(key).map(f)
    }

    /// Acquires a read lock and returns a guard for direct `RawTable` access.
    ///
    /// # Summary
    /// Returns `MutexGuard` for advanced operations on the internal table.
    ///
    /// # Description
    /// Provides escape hatch for users who need the full `RawTable` API
    /// (e.g., batch operations, custom probing). The guard holds the spinlock
    /// until dropped.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert(1, "a");
    /// {
    ///     let guard = map.read();
    ///     assert_eq!(guard.get(&1), Some(&"a"));
    /// } // Lock released here
    /// ```
    ///
    /// # Panics
    /// Never panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`insert`](Self::insert) for mutation operations.
    #[inline]
    pub fn read(&self) -> MutexGuard<'_, RawTable<K, V>> {
        self.table.lock()
    }

    /// Inserts a key-value pair.
    ///
    /// # Summary
    /// Stores a pair; returns `true` if newly inserted, `false` if duplicate.
    ///
    /// # Description
    /// Acquires exclusive lock, computes hash, probes with Robin Hood displacement.
    /// Triggers resize at 80% load factor. Duplicate keys preserve existing values.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// assert!(map.insert(1, "a"));
    /// assert!(!map.insert(1, "b")); // Duplicate
    /// assert_eq!(map.with_key(&1, |v| *v), Some("a"));
    /// ```
    ///
    /// # Panics
    /// Panics if allocation fails during resize (OOM).
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`with_key`](Self::with_key)
    /// - [`remove`](Self::remove)
    #[inline]
    #[must_use]
    pub fn insert(&self, key: K, value: V) -> bool {
        self.table.lock().insert(key, value)
    }

    /// Removes a key-value pair.
    ///
    /// # Summary
    /// Deletes a key; returns `true` on success, `false` if absent.
    ///
    /// # Description
    /// Acquires lock, probes, and applies backward shift deletion. Eliminates
    /// tombstones and maintains probe continuity.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert(1, "a");
    /// assert!(map.remove(&1));
    /// assert!(!map.remove(&1));
    /// ```
    ///
    /// # Panics
    /// Never panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`insert`](Self::insert)
    /// - [`clear`](Self::clear)
    #[inline]
    #[must_use]
    pub fn remove(&self, key: &K) -> bool {
        self.table.lock().remove(key)
    }

    /// Clears all elements, retaining allocated capacity.
    ///
    /// # Summary
    /// Removes all entries and resets size to zero.
    ///
    /// # Description
    /// Drops all keys/values, zeroes metadata. Allocation preserved for reuse.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert(1, "a");
    /// map.clear();
    /// assert_eq!(map.len(), 0);
    /// assert_eq!(map.capacity(), 16);
    /// ```
    ///
    /// # Panics
    /// Never panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`remove`](Self::remove)
    #[inline]
    pub fn clear(&self) {
        self.table.lock().clear();
    }

    /// Reserves capacity for at least `additional` more elements.
    ///
    /// # Summary
    /// Ensures map can hold `len() + additional` without resize.
    ///
    /// # Description
    /// No-op if sufficient capacity exists. Otherwise rounds up to power of two
    /// and triggers rehash.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::<i32, bool>::new();
    /// map.reserve(100);
    /// assert!(map.capacity() >= 100);
    /// ```
    ///
    /// # Panics
    /// Panics if allocation fails (OOM).
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`with_capacity`](Self::with_capacity)
    #[inline]
    pub fn reserve(&self, additional: usize) {
        self.table.lock().reserve(additional);
    }

    /// Returns an `Entry` for the given key.
    ///
    /// # Summary
    /// Provides in-place modification and conditional insertion API.
    ///
    /// # Description
    /// Acquires lock and returns `Occupied` or `Vacant` variant. Entry holds
    /// the lock guard until dropped, ensuring atomicity during operations.
    /// Requires `K: Clone` to allow safe key duplication during vacant entry creation.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// let v = map.entry("key").or_insert(42);
    /// *v += 1;
    /// assert_eq!(map.with_key(&"key", |v| *v), Some(43));
    /// ```
    ///
    /// # Panics
    /// Never panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`Entry`]
    #[inline]
    pub fn entry(&self, key: K) -> Entry<'_, K, V>
    where
        K: Clone,
    {
        let guard = self.table.lock();
        if guard.get(&key).is_some() {
            Entry::Occupied(OccupiedEntry::new(guard, key))
        } else {
            Entry::Vacant(VacantEntry::new(guard, key))
        }
    }

    /// Returns an iterator over immutable key-value pairs.
    ///
    /// # Summary
    /// Yields `(&K, &V)` for all occupied slots.
    ///
    /// # Description
    /// Acquires lock and returns iterator holding the guard. Order is
    /// undefined and may change on resize.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert(1, "a");
    /// let mut pairs: Vec<_> = map.iter().collect();
    /// assert_eq!(pairs.len(), 1);
    /// ```
    ///
    /// # Panics
    /// Never panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Iterator borrows lock. Concurrent mutation blocked during iteration.
    ///
    /// # See Also
    /// - [`iter_mut`](Self::iter_mut)
    #[inline]
    pub fn iter(&self) -> Iter<'_, K, V> {
        Iter::new(self.table.lock())
    }

    /// Returns an iterator over mutable values.
    ///
    /// # Summary
    /// Yields `&mut V` for all occupied slots.
    ///
    /// # Description
    /// Acquires exclusive lock. Allows in-place mutation while preserving key stability.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert(1, 0);
    /// for v in map.iter_mut() { *v += 10; }
    /// assert_eq!(map.with_key(&1, |v| *v), Some(10));
    /// ```
    ///
    /// # Panics
    /// Never panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`iter`](Self::iter)
    #[inline]
    pub fn iter_mut(&self) -> IterMut<'_, K, V> {
        IterMut::new(self.table.lock())
    }

    /// Returns an iterator over immutable keys.
    ///
    /// # Summary
    /// Yields `&K` for all occupied slots.
    ///
    /// # Description
    /// Wrapper over `iter()` that projects only the key component.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert("k1", 1);
    /// let keys: Vec<_> = map.keys().collect();
    /// assert_eq!(keys.len(), 1);
    /// ```
    ///
    /// # Panics
    /// Never panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Same as `iter()`.
    ///
    /// # See Also
    /// - [`iter`](Self::iter)
    #[inline]
    pub fn keys(&self) -> Keys<'_, K, V> {
        Keys::new(self.table.lock())
    }

    /// Returns an iterator over immutable values.
    ///
    /// # Summary
    /// Yields `&V` for all occupied slots.
    ///
    /// # Description
    /// Wrapper over `iter()` that projects only the value component.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert(1, "val");
    /// let vals: Vec<_> = map.values().collect();
    /// assert_eq!(vals.len(), 1);
    /// ```
    ///
    /// # Panics
    /// Never panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Same as `iter()`.
    ///
    /// # See Also
    /// - [`iter`](Self::iter)
    #[inline]
    pub fn values(&self) -> Values<'_, K, V> {
        Values::new(self.table.lock())
    }

    /// Clears the map, returning all elements in an iterator.
    ///
    /// # Summary
    /// Yields `(K, V)` pairs while dropping them from the map.
    ///
    /// # Description
    /// Acquires lock and returns draining iterator. Elements are dropped
    /// immediately after yielding. Capacity is retained.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert(1, "a");
    /// let drained: Vec<_> = map.drain().collect();
    /// assert!(map.is_empty());
    /// ```
    ///
    /// # Panics
    /// Never panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Iterator holds lock. Drops elements safely.
    ///
    /// # See Also
    /// - [`clear`](Self::clear)
    #[inline]
    pub fn drain(&self) -> Drain<'_, K, V> {
        Drain::new(self.table.lock())
    }
}

impl<'a, K: RobinHoodKey + PartialEq, V> IntoIterator for &'a RobinHoodMap<K, V> {
    type Item = (&'a K, &'a V);
    type IntoIter = crate::iter::Iter<'a, K, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}