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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
mod bucket;
mod entry;
mod error;
mod inner;
mod iter;
use self::bucket::{Bucket, BucketPtr};
pub use self::entry::{Entry, OccupiedEntry, VacantEntry};
pub use self::error::OccupiedError;
use self::inner::Core;
pub use self::iter::{Drain, Iter, IterMut};
use core::cell::UnsafeCell;
use core::fmt::{self, Debug};
use core::hash::{BuildHasher, Hash};
use equivalent::Equivalent;
use hashbrown::{HashTable, hash_table};
#[cfg(feature = "std")]
use std::hash::RandomState;
type Entries<K, V> = crate::stk::BumpStk<Bucket<K, V>>;
#[cfg(feature = "std")]
pub struct BumpMap<K, V, S = RandomState> {
core: Core<K, V>,
hasher: S,
}
#[cfg(not(feature = "std"))]
pub struct BumpMap<K, V, S> {
core: Core<K, V>,
hasher: S,
}
#[cfg(feature = "std")]
impl<K, V> BumpMap<K, V, RandomState> {
/// Creates an empty `BumpMap`.
///
/// The new map will not allocate until it is first pair inserted into.
///
/// # Examples
///
/// ```
/// # use bumpish::BumpMap;
/// let mut map: BumpMap<&str, i32> = BumpMap::new();
/// assert_eq!(map.capacity(), 0);
/// ```
#[inline]
#[must_use]
pub fn new() -> Self {
Default::default()
}
/// Creates an empty `BumpMap` with at least the specified capacity.
///
/// The hash map will be able to hold at least `capacity` elements without
/// reallocating. This method is allowed to allocate for more elements than
/// `capacity`. If `capacity` is zero, the hash map will not allocate.
///
/// # Examples
///
/// ```
/// # use bumpish::BumpMap;
/// let map: BumpMap<&str, i32> = BumpMap::with_capacity(10);
/// assert!(map.capacity() >= 10);
/// ```
#[inline]
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
BumpMap::with_capacity_and_hasher(capacity, Default::default())
}
}
impl<K, V, S> BumpMap<K, V, S> {
/// Creates an empty `BumpMap` which will use the given hash builder to hash
/// keys.
///
/// The new map will not allocate until it is first pair inserted into.
///
/// # Examples
///
/// ```
/// use bumpish::BumpMap;
/// use std::hash::RandomState;
///
/// let s = RandomState::new();
/// let mut map = BumpMap::with_hasher(s);
/// map.insert(1, 2);
/// ```
pub const fn with_hasher(hasher: S) -> Self {
BumpMap {
core: Core::new(),
hasher,
}
}
/// Creates an empty `BumpMap` with at least the specified capacity, using
/// `hasher` to hash the keys.
///
/// The map will be able to hold at least `capacity` elements without
/// reallocating. This method is allowed to allocate for more elements than
/// `capacity`. If `capacity` is zero, the hash map will not allocate.
///
/// # Examples
///
/// ```
/// use bumpish::BumpMap;
/// use std::hash::RandomState;
///
/// let s = RandomState::new();
/// let mut map = BumpMap::with_capacity_and_hasher(10, s);
/// map.insert(1, 2);
/// assert!(map.capacity() >= 10);
/// ```
pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
BumpMap {
core: Core::with_capacity(capacity),
hasher: hash_builder,
}
}
/// Returns the number of elements the map can hold without reallocating.
///
/// # Examples
///
/// ```
/// # use bumpish::BumpMap;
/// let map: BumpMap<i32, i32> = BumpMap::with_capacity(100);
/// assert!(map.capacity() >= 100);
/// ```
#[inline]
pub fn capacity(&self) -> usize {
self.core.capacity()
}
/// Returns the number of elements in the map.
///
/// # Examples
///
/// ```
/// # use bumpish::BumpMap;
/// let mut a = BumpMap::new();
/// assert_eq!(a.len(), 0);
/// a.insert(1, "a");
/// assert_eq!(a.len(), 1);
/// ```
#[inline]
pub fn len(&self) -> usize {
self.core.len()
}
/// Returns `true` if the map contains no elements.
///
/// # Examples
///
/// ```
/// # use bumpish::BumpMap;
/// let mut a = BumpMap::new();
/// assert!(a.is_empty());
/// a.insert(1, "a");
/// assert!(!a.is_empty());
/// ```
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Clears the map, removing all key-value pairs. Can keep some of the
/// allocated memory for reuse.
///
/// # Examples
///
/// ```
/// # use bumpish::BumpMap;
/// let mut a = BumpMap::new();
/// a.insert(1, "a");
/// a.clear();
/// assert!(a.is_empty());
/// ```
pub fn clear(&mut self) {
self.core.clear();
}
/// An iterator visiting all key-value pairs in insertion order. The
/// iterator element type is `(&'a K, &'a V)`.
///
/// # Examples
///
/// ```
/// use bumpish::BumpMap;
///
/// let map = BumpMap::from([
/// ("a", 1),
/// ("b", 2),
/// ("c", 3),
/// ]);
///
/// assert_eq!(
/// map.iter().collect::<Vec<(_, _)>>(),
/// [(&"a", &1), (&"b", &2), (&"c", &3)]
/// );
/// ```
pub fn iter(&self) -> Iter<'_, K, V> {
Iter::new(&self.core.entries)
}
/// An iterator visiting all key-value pairs in insertion order, with
/// mutable references to the values. The iterator element type is `(&'a K,
/// &'a mut V)`.
///
/// # Examples
///
/// ```
/// use bumpish::BumpMap;
///
/// let mut map = BumpMap::from([
/// ("a", 1),
/// ("b", 2),
/// ("c", 3),
/// ]);
///
/// // Update all values
/// for (_, val) in map.iter_mut() {
/// *val *= 2;
/// }
///
/// assert_eq!(
/// map.iter().collect::<Vec<(_, _)>>(),
/// [(&"a", &2), (&"b", &4), (&"c", &6)]
/// );
/// ```
pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
IterMut::new(&mut self.core.entries)
}
/// An iterator visiting all keys in insertion order. The iterator element
/// type is `&'a K`.
///
/// # Examples
///
/// ```
/// use bumpish::BumpMap;
///
/// let map = BumpMap::from([
/// ("a", 1),
/// ("b", 2),
/// ("c", 3),
/// ]);
///
/// for key in map.keys() {
/// println!("{key}");
/// }
/// ```
pub fn keys(&self) -> impl Iterator<Item = &K> {
self.iter().map(|(k, _)| k)
}
/// An iterator visiting all values in insertion order. The iterator element
/// type is `&'a V`.
///
/// # Examples
///
/// ```
/// use bumpish::BumpMap;
///
/// let map = BumpMap::from([
/// ("a", 1),
/// ("b", 2),
/// ("c", 3),
/// ]);
///
/// for val in map.values() {
/// println!("{val}");
/// }
/// ```
pub fn values(&self) -> impl Iterator<Item = &V> {
self.iter().map(|(_, v)| v)
}
/// An iterator visiting all values mutably in insertion order. The iterator
/// element type is `&'a mut V`.
///
/// # Examples
///
/// ```
/// use bumpish::BumpMap;
///
/// let mut map = BumpMap::from([
/// ("a", 1),
/// ("b", 2),
/// ("c", 3),
/// ]);
///
/// for val in map.values_mut() {
/// *val = *val + 10;
/// }
///
/// for val in map.values() {
/// println!("{val}");
/// }
/// ```
pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
self.iter_mut().map(|(_, v)| v)
}
}
impl<K: Eq, V, S> BumpMap<K, V, S> {
/// Clears the map, returning all key-value pairs as an iterator. Can keep
/// some of the allocated memory for reuse.
///
/// If the returned iterator is dropped before being fully consumed, it
/// drops the remaining key-value pairs.
///
/// # Examples
///
/// ```
/// use bumpish::BumpMap;
///
/// let mut a = BumpMap::new();
/// a.insert(1, "a");
/// a.insert(2, "b");
///
/// for (k, v) in a.drain().take(1) {
/// assert!(k == 1 || k == 2);
/// assert!(v == "a" || v == "b");
/// }
///
/// assert!(a.is_empty());
/// assert!(a.capacity() > 0);
/// ```
pub fn drain(&mut self) -> Drain<'_, K, V> {
Drain::new(&mut self.core)
}
}
impl<K, V, S> BumpMap<K, V, S>
where
S: BuildHasher,
{
/// Returns a reference to the map's [`BuildHasher`].
///
/// [`BuildHasher`]: https://doc.rust-lang.org/beta/std/hash/trait.BuildHasher.html
///
/// # Examples
///
/// ```
/// use bumpish::BumpMap;
/// use std::hash::RandomState;
///
/// let hasher = RandomState::new();
/// let map: BumpMap<i32, i32> = BumpMap::with_hasher(hasher);
/// let hasher: &RandomState = map.hasher();
/// ```
pub fn hasher(&self) -> &S {
&self.hasher
}
/// Returns `true` if the map contains a value with an equivalent key to `key`.
///
/// The `Q` type **must** hash like `K`.
///
/// # Examples
///
/// ```
/// # use bumpish::BumpMap;
/// let mut map = BumpMap::new();
/// map.insert("a".to_owned(), 1);
/// assert_eq!(map.contains_key("a"), true);
/// assert_eq!(map.contains_key(&"a".to_owned()), true);
/// assert_eq!(map.contains_key("b"), false);
/// ```
pub fn contains_key<Q>(&self, key: &Q) -> bool
where
Q: ?Sized + Hash + Equivalent<K>,
{
self.core.contains_key(|| self.hasher.hash_one(key), key)
}
/// Returns a reference to the value corresponding to the key.
///
/// The `Q` type **must** hash like `K`.
///
/// # Examples
///
/// ```
/// # use bumpish::BumpMap;
/// let mut map = BumpMap::new();
/// map.insert(1, "a");
/// assert_eq!(map.get(&1), Some(&"a"));
/// assert_eq!(map.get(&2), None);
/// ```
pub fn get<Q>(&self, key: &Q) -> Option<&V>
where
Q: ?Sized + Hash + Equivalent<K>,
{
let hash = self.hasher.hash_one(key);
self.core.get_key_value(hash, key).map(|(_, value)| value)
}
/// Returns the key-value pair corresponding to the supplied key. This is
/// potentially useful:
/// - for key types where non-identical keys can be considered equal;
/// - for getting the `&K` stored key value from an equivalent `&Q` lookup key; or
/// - for getting a reference to a key with the same lifetime as the collection.
///
/// The `Q` type **must** hash like `K`.
///
/// # Examples
///
/// ```
/// use bumpish::BumpMap;
/// use std::hash::{Hash, Hasher};
///
/// #[derive(Clone, Copy, Debug)]
/// struct S {
/// id: u32,
/// # #[allow(unused)]
/// name: &'static str, // ignored by equality and hashing operations
/// }
///
/// impl PartialEq for S {
/// fn eq(&self, other: &S) -> bool {
/// self.id == other.id
/// }
/// }
///
/// impl Eq for S {}
///
/// impl Hash for S {
/// fn hash<H: Hasher>(&self, state: &mut H) {
/// self.id.hash(state);
/// }
/// }
///
/// let j_a = S { id: 1, name: "Jessica" };
/// let j_b = S { id: 1, name: "Jess" };
/// let p = S { id: 2, name: "Paul" };
/// assert_eq!(j_a, j_b);
///
/// let mut map = BumpMap::new();
/// map.insert(j_a, "Paris");
/// assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris")));
/// assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case
/// assert_eq!(map.get_key_value(&p), None);
/// ```
pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
where
Q: ?Sized + Hash + Equivalent<K>,
{
let hash = self.hasher.hash_one(key);
self.core.get_key_value(hash, key)
}
/// Returns a mutable reference to the value corresponding to the key.
///
/// The `Q` type **must** hash like `K`.
///
/// # Examples
///
/// ```
/// # use bumpish::BumpMap;
///
/// let mut map = BumpMap::new();
/// map.insert(1, "a");
/// if let Some(x) = map.get_mut(&1) {
/// *x = "b";
/// }
/// assert_eq!(map[&1], "b");
/// ```
pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
where
Q: ?Sized + Hash + Equivalent<K>,
{
let hash = self.hasher.hash_one(key);
self.core.get_mut(hash, key)
}
}
impl<K, V, S> BumpMap<K, V, S>
where
K: Hash + Eq,
S: BuildHasher,
{
/// Inserts a key-value pair into the map.
///
/// If the map did not have this key present, [`None`] is returned.
///
/// If the map did have an equivalent key present, the value is updated, and
/// the old value is returned. The key is not updated in any case.
///
/// # Examples
///
/// ```
/// # use bumpish::BumpMap;
/// let mut map = BumpMap::new();
/// assert_eq!(map.insert(37, "a"), None);
///
/// map.insert(37, "b");
/// assert_eq!(map.insert(37, "c"), Some("b"));
/// assert_eq!(map[&37], "c");
/// ```
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
let hash = self.hasher.hash_one(&key);
self.core.insert(hash, key, value)
}
/// Tries to insert a key-value pair into the map, and returns a mutable
/// reference to the value in the entry.
///
/// If the map already has this key present, nothing is updated, and an
/// error containing the occupied entry and the value is returned.
///
/// Because of there is bump allocation under the hood, this method doesn't
/// require a mutable reference to self.
///
/// # Examples
///
/// ```
/// # use bumpish::BumpMap;
/// let map = BumpMap::new();
/// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
///
/// let err = map.try_insert(37, "b").unwrap_err();
/// assert_eq!(err.entry.key(), &37);
/// assert_eq!(err.entry.get(), &"a");
/// assert_eq!(err.value, "b");
/// ```
pub fn try_insert(&self, key: K, value: V) -> Result<&V, OccupiedError<'_, K, V>> {
let hash = self.hasher.hash_one(&key);
self.core.try_insert(hash, key, value)
}
/// Gets the given key's corresponding entry in the map.
///
/// As distinct from standard `HashMap::entry`, this method returns an
/// `Entry` that can't be used to modify the value associated with the key.
/// That allows to call `entry` method with a shared reference to the map.
///
/// But this still allows to insert a new key-value pair into the vacant
/// entry.
///
/// # Examples
///
/// ```
/// use bumpish::BumpMap;
///
/// let mut letters = BumpMap::new();
///
/// for ch in "a short treatise on fungi".chars() {
/// letters.entry(ch).or_insert(true);
/// }
///
/// assert_eq!(letters[&'s'], true);
/// assert_eq!(letters[&'t'], true);
/// assert_eq!(letters[&'u'], true);
/// assert_eq!(letters.get(&'y'), None);
/// ```
pub fn entry(&self, key: K) -> Entry<'_, K, V> {
let hash = self.hasher.hash_one(&key);
self.core.entry(hash, key)
}
}
impl<K, V, S> BumpMap<K, V, S>
where
K: Eq + Hash,
S: BuildHasher,
{
/// Extends the map with the contents of an iterator. If a key already
/// exists in this map, the key and corresponding value are dropped.
pub fn extend_absent<I>(&self, iter: I)
where
I: IntoIterator<Item = (K, V)>,
{
for (k, v) in iter {
let hash = self.hasher.hash_one(&k);
_ = self.core.try_insert(hash, k, v);
}
}
}
impl<K, V, S> core::clone::Clone for BumpMap<K, V, S>
where
K: Clone,
V: Clone,
S: Clone,
{
fn clone(&self) -> Self {
Self {
core: self.core.clone(),
hasher: self.hasher.clone(),
}
}
}
impl<K, V, S> Debug for BumpMap<K, V, S>
where
K: Debug,
V: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
impl<K, V, S> Default for BumpMap<K, V, S>
where
S: Default,
{
/// Creates an empty `BumpMap<K, V, S>`, with the `Default` value for the hasher.
#[inline]
fn default() -> Self {
Self::with_hasher(Default::default())
}
}
impl<K, V, S> Eq for BumpMap<K, V, S>
where
K: Eq + Hash,
V: Eq,
S: BuildHasher,
{
}
impl<K, V, S> PartialEq for BumpMap<K, V, S>
where
K: Eq + Hash,
V: PartialEq,
S: BuildHasher,
{
fn eq(&self, other: &Self) -> bool {
if self.len() != other.len() {
return false;
}
self.iter().all(|(k, v)| other.get(k) == Some(v))
}
}
#[cfg(feature = "std")]
impl<K, V, const N: usize> From<[(K, V); N]> for BumpMap<K, V, RandomState>
where
K: Eq + Hash,
{
/// Converts a `[(K, V); N]` into a `BumpMap<K, V>`.
///
/// If any entries in the array have equal keys, all but one of the
/// corresponding values will be dropped.
///
/// # Examples
///
/// ```
/// # use bumpish::BumpMap;
/// let map1 = BumpMap::from([(1, 2), (3, 4)]);
/// let map2: BumpMap<_, _> = [(1, 2), (3, 4)].into();
/// assert_eq!(map1, map2);
/// ```
fn from(arr: [(K, V); N]) -> Self {
Self::from_iter(arr)
}
}
impl<K, V, S> FromIterator<(K, V)> for BumpMap<K, V, S>
where
K: Eq + Hash,
S: BuildHasher + Default,
{
/// Constructs a `BumpMap<K, V>` from an iterator of key-value pairs.
///
/// If the iterator produces any pairs with equal keys, all but one of the
/// corresponding values will be dropped.
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
let map = Self::with_hasher(Default::default());
for (k, v) in iter {
_ = map.try_insert(k, v);
}
map
}
}
impl<'a, K, V, S> Extend<(&'a K, &'a V)> for BumpMap<K, V, S>
where
K: Eq + Hash + Copy,
V: Copy,
S: BuildHasher,
{
fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
self.extend(iter.into_iter().map(|(k, v)| (*k, *v)));
}
}
impl<K, V, S> Extend<(K, V)> for BumpMap<K, V, S>
where
K: Eq + Hash,
S: BuildHasher,
{
fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
for (k, v) in iter {
self.insert(k, v);
}
}
}
impl<K, Q: ?Sized, V, S> core::ops::Index<&Q> for BumpMap<K, V, S>
where
K: Eq + Hash,
Q: Eq + Hash + Equivalent<K>,
S: BuildHasher,
{
type Output = V;
/// Returns a reference to the value corresponding to the supplied key.
///
/// # Panics
///
/// Panics if the key is not present in the `BumpMap`.
#[inline]
fn index(&self, key: &Q) -> &Self::Output {
self.get(key).expect("no entry found for key")
}
}
impl<'a, K, V, S> IntoIterator for &'a BumpMap<K, V, S> {
type Item = (&'a K, &'a V);
type IntoIter = Iter<'a, K, V>;
#[inline]
fn into_iter(self) -> Iter<'a, K, V> {
self.iter()
}
}
impl<'a, K, V, S> IntoIterator for &'a mut BumpMap<K, V, S> {
type Item = (&'a K, &'a mut V);
type IntoIter = IterMut<'a, K, V>;
#[inline]
fn into_iter(self) -> IterMut<'a, K, V> {
self.iter_mut()
}
}