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
//! Entry API for in-place modification and conditional insertion.
//!
//! Provides `Entry`, `OccupiedEntry`, and `VacantEntry` matching `std::collections` ergonomics.
//! Entry variants retain the internal spinlock guard to ensure atomicity during
//! complex insertion or modification patterns.
//!
//! # Lifetime Semantics
//! References returned by Entry methods (e.g., `into_mut`, `insert`) are tied to the
//! original `&RobinHoodMap` borrow that created the Entry, not to the Entry itself.
//! The `MutexGuard` ensures exclusive access while obtaining the reference; once
//! returned, the lock is released but the reference remains valid for lifetime `'a`.
//! Callers must uphold aliasing rules: no other mutable references to the same key
//! may exist while the returned reference is held.

use crate::hash::RobinHoodKey;
use crate::sync::MutexGuard;
use crate::table::RawTable;
use core::marker::PhantomData;

/// View into a single entry in a map, which may be occupied or vacant.
///
/// # Summary
/// Enumerates possible states for a map key during conditional operations.
///
/// # Description
/// Returned by `RobinHoodMap::entry()`. Holds the internal spinlock guard
/// until the variant is consumed or dropped. Enables `or_insert`, `and_modify`,
/// and `or_default` patterns without double lookups.
///
/// # Examples
/// ```
/// use robinxx_map::RobinHoodMap;
/// let map = RobinHoodMap::new();
/// map.entry("key").or_insert(0);
/// ```
///
/// # Panics
/// None.
///
/// # Errors
/// Not applicable.
///
/// # Safety
/// Not applicable. This is a safe function, thread-safety is guaranteed
/// internally by `SpinMutex` acquisition.
///
/// # See Also
/// - [`OccupiedEntry`]
/// - [`VacantEntry`]
pub enum Entry<'a, K, V> {
    /// Key exists in the map.
    Occupied(OccupiedEntry<'a, K, V>),
    /// Key does not exist.
    Vacant(VacantEntry<'a, K, V>),
}

impl<'a, K: RobinHoodKey + PartialEq + Clone, V> Entry<'a, K, V> {
    /// Inserts value if vacant, otherwise returns occupied reference.
    ///
    /// # Summary
    /// Returns mutable reference to the value at the entry.
    ///
    /// # Description
    /// If `Vacant`, inserts `default` and returns `&mut V`. If `Occupied`,
    /// returns reference to existing value.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// let v = map.entry("a").or_insert(1);
    /// *v = 2;
    /// ```
    ///
    /// # Panics
    /// Panics on allocation failure if vacant and insert triggers resize.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`or_insert`](Self::or_insert)
    #[inline]
    pub fn or_insert(self, default: V) -> &'a mut V
    where
        K: Clone,
    {
        match self {
            Entry::Occupied(e) => e.into_mut(),
            Entry::Vacant(e) => e.insert(default),
        }
    }

    /// Inserts value computed by closure if vacant.
    ///
    /// # Summary
    /// Evaluates `f()` and inserts result if key absent.
    ///
    /// # Description
    /// Lazy evaluation avoids unnecessary allocation or computation when key exists.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.entry("x").or_insert_with(|| 42);
    /// ```
    ///
    /// # Panics
    /// Panics if `f()` panics or allocation fails during insert.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`or_insert`](Self::or_insert)
    #[inline]
    pub fn or_insert_with<F: FnOnce() -> V>(self, f: F) -> &'a mut V
    where
        K: Clone,
    {
        match self {
            Entry::Occupied(e) => e.into_mut(),
            Entry::Vacant(e) => e.insert(f()),
        }
    }

    /// Modifies occupied value, or returns vacant entry.
    ///
    /// # Summary
    /// Applies closure to occupied value, leaves vacant untouched.
    ///
    /// # Description
    /// Useful for updating counters or aggregating without replacing.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert("c", 0);
    /// map.entry("c").and_modify(|e| *e += 1);
    /// ```
    ///
    /// # 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
    /// - [`or_insert`](Self::or_insert)
    #[inline]
    #[must_use]
    pub fn and_modify<F: FnOnce(&mut V)>(mut self, f: F) -> Self {
        if let Entry::Occupied(ref mut e) = self {
            f(e.get_mut());
        }
        self
    }
}

/// An occupied entry in a `RobinHoodMap`.
///
/// # Summary
/// View into an existing key-value pair.
///
/// # Description
/// Allows reading, mutating, or removing the value without re-probing.
///
/// # Examples
/// ```
/// use robinxx_map::RobinHoodMap;
/// let map = RobinHoodMap::new();
/// map.insert(1, "a");
/// if let robinxx_map::entry::Entry::Occupied(e) = map.entry(1) {
///     assert_eq!(e.get(), &"a");
/// }
/// ```
///
/// # Panics
/// None.
///
/// # Errors
/// Not applicable.
///
/// # Safety
/// Not applicable. This is a safe function, thread-safety is guaranteed
/// internally by `SpinMutex` acquisition.
///
/// # See Also
/// - [`Entry`]
pub struct OccupiedEntry<'a, K, V> {
    guard: MutexGuard<'a, RawTable<K, V>>,
    key: K,
    _marker: PhantomData<&'a V>,
}

impl<'a, K: RobinHoodKey + PartialEq, V> OccupiedEntry<'a, K, V> {
    /// Internal constructor for crate use only.
    ///
    /// # Summary
    /// Builds an `OccupiedEntry` from a locked guard and existing key.
    ///
    /// # Description
    /// Used internally by `RobinHoodMap::entry()`. Not intended for direct public use.
    ///
    /// # Examples
    /// Internal use only.
    ///
    /// # Panics
    /// Never panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Caller must guarantee the key actually exists in the guarded table.
    ///
    /// # See Also
    /// - [`RobinHoodMap::entry`](crate::map::RobinHoodMap::entry)
    #[inline]
    pub(crate) fn new(guard: MutexGuard<'a, RawTable<K, V>>, key: K) -> Self {
        Self {
            guard,
            key,
            _marker: PhantomData,
        }
    }

    /// Returns immutable reference to the stored value.
    ///
    /// # Summary
    /// Retrieves `&V` for the occupied key.
    ///
    /// # Description
    /// Direct access without additional lookup cost.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert(1, "x");
    /// if let robinxx_map::entry::Entry::Occupied(e) = map.entry(1) {
    ///     assert_eq!(*e.get(), "x");
    /// }
    /// ```
    ///
    /// # Panics
    /// Panics if the occupied invariant is violated. This indicates an internal bug
    /// in `robinxx_map` and should never occur under correct usage.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`get_mut`](Self::get_mut)
    #[inline]
    pub fn get(&self) -> &V {
        self.guard
            .get(&self.key)
            .expect("occupied invariant violated")
    }

    /// Returns mutable reference to the stored value.
    ///
    /// # Summary
    /// Retrieves `&mut V` for the occupied key.
    ///
    /// # Description
    /// Allows in-place mutation while preserving entry ownership.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert(1, 0);
    /// if let robinxx_map::entry::Entry::Occupied(mut e) = map.entry(1) {
    ///     *e.get_mut() += 5;
    /// }
    /// ```
    ///
    /// # Panics
    /// Panics if the occupied invariant is violated. This indicates an internal bug
    /// in `robinxx_map` and should never occur under correct usage.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`get`](Self::get)
    #[inline]
    pub fn get_mut(&mut self) -> &mut V {
        self.guard
            .get_mut(&self.key)
            .expect("occupied invariant violated")
    }

    /// Replaces value and returns old value.
    ///
    /// # Summary
    /// Swaps existing value with new one.
    ///
    /// # Description
    /// Useful when old value must be consumed or inspected.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert(1, "old");
    /// if let robinxx_map::entry::Entry::Occupied(mut e) = map.entry(1) {
    ///     assert_eq!(e.insert("new"), "old");
    /// }
    /// ```
    ///
    /// # Panics
    /// Never panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`get_mut`](Self::get_mut)
    #[inline]
    pub fn insert(&mut self, value: V) -> V {
        let old = self.get_mut();
        core::mem::replace(old, value)
    }

    /// Removes entry and returns owned value.
    ///
    /// # Summary
    /// Deletes key and yields `V`.
    ///
    /// # Description
    /// Applies backward shift deletion internally.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert(1, "val");
    /// if let robinxx_map::entry::Entry::Occupied(e) = map.entry(1) {
    ///     assert_eq!(e.remove(), "val");
    /// }
    /// 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
    /// - [`get`](Self::get)
    #[inline]
    pub fn remove(self) -> V
    where
        V: Clone,
    {
        let value = self.get().clone();
        let mut guard = self.guard;
        guard.remove(&self.key);
        value
    }

    /// Consumes entry and returns mutable reference to value.
    ///
    /// # Summary
    /// Yields `&mut V` with entry lifetime.
    ///
    /// # Description
    /// Finalizes entry access for mutation without removing.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// map.insert(1, 10);
    /// if let robinxx_map::entry::Entry::Occupied(e) = map.entry(1) {
    ///     *e.into_mut() *= 2;
    /// }
    /// ```
    ///
    /// # Panics
    /// Panics if the occupied invariant is violated. This indicates an internal bug
    /// in `robinxx_map` and should never occur under correct usage.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Not applicable. This is a safe function, thread-safety is guaranteed
    /// internally by `SpinMutex` acquisition.
    ///
    /// # See Also
    /// - [`get_mut`](Self::get_mut)
    #[inline]
    pub fn into_mut(mut self) -> &'a mut V {
        let ptr = core::ptr::from_mut::<V>(
            self.guard
                .get_mut(&self.key)
                .expect("occupied invariant violated"),
        );
        // SAFETY:
        // 1. `ptr` points to a valid `V` inside the `RawTable` owned by `RobinHoodMap`.
        // 2. The lifetime `'a` is tied to the original `&RobinHoodMap` borrow that
        //    created the Entry, not to the Entry or guard itself.
        // 3. The guard ensures exclusive access while obtaining the pointer; once
        //    returned, the lock is released but the reference remains sound.
        // 4. Caller must uphold aliasing rules: no other mutable references to the
        //    same key may exist while this reference is held.
        unsafe { &mut *ptr }
    }
}

/// A vacant entry in a `RobinHoodMap`.
///
/// # Summary
/// View into a missing key, ready for insertion.
///
/// # Description
/// Holds lock and key. Calling `insert()` resolves to `Occupied` state.
///
/// # Examples
/// ```
/// use robinxx_map::RobinHoodMap;
/// let map = RobinHoodMap::new();
/// if let robinxx_map::entry::Entry::Vacant(e) = map.entry("new") {
///     e.insert(42);
/// }
/// ```
///
/// # Panics
/// None.
///
/// # Errors
/// Not applicable.
///
/// # Safety
/// Not applicable. This is a safe function, thread-safety is guaranteed
/// internally by `SpinMutex` acquisition.
///
/// # See Also
/// - [`Entry`]
pub struct VacantEntry<'a, K, V> {
    guard: MutexGuard<'a, RawTable<K, V>>,
    key: K,
    _marker: PhantomData<&'a V>,
}

impl<'a, K: RobinHoodKey + PartialEq + Clone, V> VacantEntry<'a, K, V> {
    /// Internal constructor for crate use only.
    ///
    /// # Summary
    /// Builds a `VacantEntry` from a locked guard and missing key.
    ///
    /// # Description
    /// Used internally by `RobinHoodMap::entry()`. Not intended for direct public use.
    ///
    /// # Examples
    /// Internal use only.
    ///
    /// # Panics
    /// Never panics.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// Caller must guarantee the key does not exist in the guarded table.
    ///
    /// # See Also
    /// - [`RobinHoodMap::entry`](crate::map::RobinHoodMap::entry)
    #[inline]
    pub(crate) fn new(guard: MutexGuard<'a, RawTable<K, V>>, key: K) -> Self {
        Self {
            guard,
            key,
            _marker: PhantomData,
        }
    }

    /// Inserts value and returns mutable reference.
    ///
    /// # Summary
    /// Stores `value` at vacant key.
    ///
    /// # Description
    /// Triggers resize if 80% LF reached. Returns `&mut V`.
    /// The returned reference is valid for lifetime `'a`, tied to the original
    /// `&RobinHoodMap` borrow.
    ///
    /// # Examples
    /// ```
    /// use robinxx_map::RobinHoodMap;
    /// let map = RobinHoodMap::new();
    /// if let robinxx_map::entry::Entry::Vacant(e) = map.entry("k") {
    ///     *e.insert(1) += 1;
    /// }
    /// ```
    ///
    /// # Panics
    /// Panics on allocation failure during resize.
    ///
    /// # Errors
    /// Not applicable.
    ///
    /// # Safety
    /// - The returned reference is valid for lifetime `'a`, tied to the original
    ///   `&RobinHoodMap` borrow, not to the Entry or guard.
    /// - Caller must not create aliasing mutable references to the same key.
    /// - This method requires `K: Clone` to clone the key before moving it into
    ///   the table, enabling safe re-probing for the mutable reference.
    ///
    /// # See Also
    /// - [`Entry::or_insert`]
    #[inline]
    pub fn insert(mut self, value: V) -> &'a mut V {
        // Clone the key before moving it into insert()
        let key_clone = self.key.clone();
        // Insert the key-value pair into the table
        let inserted = self.guard.insert(self.key, value);
        debug_assert!(inserted, "VacantEntry::insert called on occupied key");
        // Re-probe to get mutable reference to the newly inserted value.
        // We use the cloned key since the original was moved.
        let ptr = core::ptr::from_mut::<V>(
            self.guard
                .get_mut(&key_clone)
                .expect("insert failed to place value at expected location"),
        );
        // SAFETY:
        // 1. `ptr` points to a valid `V` inside the `RawTable` owned by `RobinHoodMap`.
        // 2. The lifetime `'a` is tied to the original `&RobinHoodMap` borrow that
        //    created the Entry, not to the Entry or guard itself.
        // 3. The guard ensures exclusive access while obtaining the pointer; once
        //    returned, the lock is released but the reference remains sound.
        // 4. Caller must uphold aliasing rules: no other mutable references to the
        //    same key may exist while this reference is held.
        unsafe { &mut *ptr }
    }
}