forked from rust-lang/hashbrown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtable.rs
2122 lines (2032 loc) · 64.4 KB
/
table.rs
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use core::{fmt, iter::FusedIterator, marker::PhantomData};
use crate::{
raw::{
Allocator, Bucket, Global, InsertSlot, RawDrain, RawExtractIf, RawIntoIter, RawIter,
RawTable,
},
TryReserveError,
};
/// Low-level hash table with explicit hashing.
///
/// The primary use case for this type over [`HashMap`] or [`HashSet`] is to
/// support types that do not implement the [`Hash`] and [`Eq`] traits, but
/// instead require additional data not contained in the key itself to compute a
/// hash and compare two elements for equality.
///
/// Examples of when this can be useful include:
/// - An `IndexMap` implementation where indices into a `Vec` are stored as
/// elements in a `HashTable<usize>`. Hashing and comparing the elements
/// requires indexing the associated `Vec` to get the actual value referred to
/// by the index.
/// - Avoiding re-computing a hash when it is already known.
/// - Mutating the key of an element in a way that doesn't affect its hash.
///
/// To achieve this, `HashTable` methods that search for an element in the table
/// require a hash value and equality function to be explicitly passed in as
/// arguments. The method will then iterate over the elements with the given
/// hash and call the equality function on each of them, until a match is found.
///
/// In most cases, a `HashTable` will not be exposed directly in an API. It will
/// instead be wrapped in a helper type which handles the work of calculating
/// hash values and comparing elements.
///
/// Due to its low-level nature, this type provides fewer guarantees than
/// [`HashMap`] and [`HashSet`]. Specifically, the API allows you to shoot
/// yourself in the foot by having multiple elements with identical keys in the
/// table. The table itself will still function correctly and lookups will
/// arbitrarily return one of the matching elements. However you should avoid
/// doing this because it changes the runtime of hash table operations from
/// `O(1)` to `O(k)` where `k` is the number of duplicate entries.
///
/// [`HashMap`]: super::HashMap
/// [`HashSet`]: super::HashSet
/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
pub struct HashTable<T, A = Global>
where
A: Allocator,
{
pub(crate) raw: RawTable<T, A>,
}
impl<T> HashTable<T, Global> {
/// Creates an empty `HashTable`.
///
/// The hash table is initially created with a capacity of 0, so it will not allocate until it
/// is first inserted into.
///
/// # Examples
///
/// ```
/// use hashbrown::HashTable;
/// let mut table: HashTable<&str> = HashTable::new();
/// assert_eq!(table.len(), 0);
/// assert_eq!(table.capacity(), 0);
/// ```
pub const fn new() -> Self {
Self {
raw: RawTable::new(),
}
}
/// Creates an empty `HashTable` with the specified capacity.
///
/// The hash table will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash table will not allocate.
///
/// # Examples
///
/// ```
/// use hashbrown::HashTable;
/// let mut table: HashTable<&str> = HashTable::with_capacity(10);
/// assert_eq!(table.len(), 0);
/// assert!(table.capacity() >= 10);
/// ```
pub fn with_capacity(capacity: usize) -> Self {
Self {
raw: RawTable::with_capacity(capacity),
}
}
}
impl<T, A> HashTable<T, A>
where
A: Allocator,
{
/// Creates an empty `HashTable` using the given allocator.
///
/// The hash table is initially created with a capacity of 0, so it will not allocate until it
/// is first inserted into.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use bumpalo::Bump;
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let bump = Bump::new();
/// let mut table = HashTable::new_in(&bump);
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
///
/// // The created HashTable holds none elements
/// assert_eq!(table.len(), 0);
///
/// // The created HashTable also doesn't allocate memory
/// assert_eq!(table.capacity(), 0);
///
/// // Now we insert element inside created HashTable
/// table.insert_unique(hasher(&"One"), "One", hasher);
/// // We can see that the HashTable holds 1 element
/// assert_eq!(table.len(), 1);
/// // And it also allocates some capacity
/// assert!(table.capacity() > 1);
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub const fn new_in(alloc: A) -> Self {
Self {
raw: RawTable::new_in(alloc),
}
}
/// Creates an empty `HashTable` with the specified capacity using the given allocator.
///
/// The hash table will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash table will not allocate.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use bumpalo::Bump;
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let bump = Bump::new();
/// let mut table = HashTable::with_capacity_in(5, &bump);
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
///
/// // The created HashTable holds none elements
/// assert_eq!(table.len(), 0);
/// // But it can hold at least 5 elements without reallocating
/// let empty_map_capacity = table.capacity();
/// assert!(empty_map_capacity >= 5);
///
/// // Now we insert some 5 elements inside created HashTable
/// table.insert_unique(hasher(&"One"), "One", hasher);
/// table.insert_unique(hasher(&"Two"), "Two", hasher);
/// table.insert_unique(hasher(&"Three"), "Three", hasher);
/// table.insert_unique(hasher(&"Four"), "Four", hasher);
/// table.insert_unique(hasher(&"Five"), "Five", hasher);
///
/// // We can see that the HashTable holds 5 elements
/// assert_eq!(table.len(), 5);
/// // But its capacity isn't changed
/// assert_eq!(table.capacity(), empty_map_capacity)
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
Self {
raw: RawTable::with_capacity_in(capacity, alloc),
}
}
/// Returns a reference to the underlying allocator.
pub fn allocator(&self) -> &A {
self.raw.allocator()
}
/// Returns a reference to an entry in the table with the given hash and
/// which satisfies the equality function passed.
///
/// This method will call `eq` for all entries with the given hash, but may
/// also call it for entries with a different hash. `eq` should only return
/// true for the desired entry, at which point the search is stopped.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut table = HashTable::new();
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// table.insert_unique(hasher(&1), 1, hasher);
/// table.insert_unique(hasher(&2), 2, hasher);
/// table.insert_unique(hasher(&3), 3, hasher);
/// assert_eq!(table.find(hasher(&2), |&val| val == 2), Some(&2));
/// assert_eq!(table.find(hasher(&4), |&val| val == 4), None);
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn find(&self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&T> {
self.raw.get(hash, eq)
}
/// Returns a mutable reference to an entry in the table with the given hash
/// and which satisfies the equality function passed.
///
/// This method will call `eq` for all entries with the given hash, but may
/// also call it for entries with a different hash. `eq` should only return
/// true for the desired entry, at which point the search is stopped.
///
/// When mutating an entry, you should ensure that it still retains the same
/// hash value as when it was inserted, otherwise lookups of that entry may
/// fail to find it.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut table = HashTable::new();
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// table.insert_unique(hasher(&1), (1, "a"), |val| hasher(&val.0));
/// if let Some(val) = table.find_mut(hasher(&1), |val| val.0 == 1) {
/// val.1 = "b";
/// }
/// assert_eq!(table.find(hasher(&1), |val| val.0 == 1), Some(&(1, "b")));
/// assert_eq!(table.find(hasher(&2), |val| val.0 == 2), None);
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn find_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> {
self.raw.get_mut(hash, eq)
}
/// Returns an `OccupiedEntry` for an entry in the table with the given hash
/// and which satisfies the equality function passed.
///
/// This can be used to remove the entry from the table. Call
/// [`HashTable::entry`] instead if you wish to insert an entry if the
/// lookup fails.
///
/// This method will call `eq` for all entries with the given hash, but may
/// also call it for entries with a different hash. `eq` should only return
/// true for the desired entry, at which point the search is stopped.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut table = HashTable::new();
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// table.insert_unique(hasher(&1), (1, "a"), |val| hasher(&val.0));
/// if let Ok(entry) = table.find_entry(hasher(&1), |val| val.0 == 1) {
/// entry.remove();
/// }
/// assert_eq!(table.find(hasher(&1), |val| val.0 == 1), None);
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
#[cfg_attr(feature = "inline-more", inline)]
pub fn find_entry(
&mut self,
hash: u64,
eq: impl FnMut(&T) -> bool,
) -> Result<OccupiedEntry<'_, T, A>, AbsentEntry<'_, T, A>> {
match self.raw.find(hash, eq) {
Some(bucket) => Ok(OccupiedEntry {
hash,
bucket,
table: self,
}),
None => Err(AbsentEntry { table: self }),
}
}
/// Returns an `Entry` for an entry in the table with the given hash
/// and which satisfies the equality function passed.
///
/// This can be used to remove the entry from the table, or insert a new
/// entry with the given hash if one doesn't already exist.
///
/// This method will call `eq` for all entries with the given hash, but may
/// also call it for entries with a different hash. `eq` should only return
/// true for the desired entry, at which point the search is stopped.
///
/// This method may grow the table in preparation for an insertion. Call
/// [`HashTable::find_entry`] if this is undesirable.
///
/// `hasher` is called if entries need to be moved or copied to a new table.
/// This must return the same hash value that each entry was inserted with.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::hash_table::Entry;
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut table = HashTable::new();
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// table.insert_unique(hasher(&1), (1, "a"), |val| hasher(&val.0));
/// if let Entry::Occupied(entry) = table.entry(hasher(&1), |val| val.0 == 1, |val| hasher(&val.0))
/// {
/// entry.remove();
/// }
/// if let Entry::Vacant(entry) = table.entry(hasher(&2), |val| val.0 == 2, |val| hasher(&val.0)) {
/// entry.insert((2, "b"));
/// }
/// assert_eq!(table.find(hasher(&1), |val| val.0 == 1), None);
/// assert_eq!(table.find(hasher(&2), |val| val.0 == 2), Some(&(2, "b")));
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
#[cfg_attr(feature = "inline-more", inline)]
pub fn entry(
&mut self,
hash: u64,
eq: impl FnMut(&T) -> bool,
hasher: impl Fn(&T) -> u64,
) -> Entry<'_, T, A> {
match self.raw.find_or_find_insert_slot(hash, eq, hasher) {
Ok(bucket) => Entry::Occupied(OccupiedEntry {
hash,
bucket,
table: self,
}),
Err(insert_slot) => Entry::Vacant(VacantEntry {
hash,
insert_slot,
table: self,
}),
}
}
/// Inserts an element into the `HashTable` with the given hash value, but
/// without checking whether an equivalent element already exists within the
/// table.
///
/// `hasher` is called if entries need to be moved or copied to a new table.
/// This must return the same hash value that each entry was inserted with.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut v = HashTable::new();
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// v.insert_unique(hasher(&1), 1, hasher);
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn insert_unique(
&mut self,
hash: u64,
value: T,
hasher: impl Fn(&T) -> u64,
) -> OccupiedEntry<'_, T, A> {
let bucket = self.raw.insert(hash, value, hasher);
OccupiedEntry {
hash,
bucket,
table: self,
}
}
/// Clears the table, removing all values.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut v = HashTable::new();
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// v.insert_unique(hasher(&1), 1, hasher);
/// v.clear();
/// assert!(v.is_empty());
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn clear(&mut self) {
self.raw.clear();
}
/// Shrinks the capacity of the table as much as possible. It will drop
/// down as much as possible while maintaining the internal rules
/// and possibly leaving some space in accordance with the resize policy.
///
/// `hasher` is called if entries need to be moved or copied to a new table.
/// This must return the same hash value that each entry was inserted with.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut table = HashTable::with_capacity(100);
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// table.insert_unique(hasher(&1), 1, hasher);
/// table.insert_unique(hasher(&2), 2, hasher);
/// assert!(table.capacity() >= 100);
/// table.shrink_to_fit(hasher);
/// assert!(table.capacity() >= 2);
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn shrink_to_fit(&mut self, hasher: impl Fn(&T) -> u64) {
self.raw.shrink_to(self.len(), hasher)
}
/// Shrinks the capacity of the table with a lower limit. It will drop
/// down no lower than the supplied limit while maintaining the internal rules
/// and possibly leaving some space in accordance with the resize policy.
///
/// `hasher` is called if entries need to be moved or copied to a new table.
/// This must return the same hash value that each entry was inserted with.
///
/// Panics if the current capacity is smaller than the supplied
/// minimum capacity.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut table = HashTable::with_capacity(100);
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// table.insert_unique(hasher(&1), 1, hasher);
/// table.insert_unique(hasher(&2), 2, hasher);
/// assert!(table.capacity() >= 100);
/// table.shrink_to(10, hasher);
/// assert!(table.capacity() >= 10);
/// table.shrink_to(0, hasher);
/// assert!(table.capacity() >= 2);
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn shrink_to(&mut self, min_capacity: usize, hasher: impl Fn(&T) -> u64) {
self.raw.shrink_to(min_capacity, hasher);
}
/// Reserves capacity for at least `additional` more elements to be inserted
/// in the `HashTable`. The collection may reserve more space to avoid
/// frequent reallocations.
///
/// `hasher` is called if entries need to be moved or copied to a new table.
/// This must return the same hash value that each entry was inserted with.
///
/// # Panics
///
/// Panics if the new capacity exceeds [`isize::MAX`] bytes and [`abort`] the program
/// in case of allocation error. Use [`try_reserve`](HashTable::try_reserve) instead
/// if you want to handle memory allocation failure.
///
/// [`isize::MAX`]: https://doc.rust-lang.org/std/primitive.isize.html
/// [`abort`]: https://doc.rust-lang.org/alloc/alloc/fn.handle_alloc_error.html
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut table: HashTable<i32> = HashTable::new();
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// table.reserve(10, hasher);
/// assert!(table.capacity() >= 10);
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn reserve(&mut self, additional: usize, hasher: impl Fn(&T) -> u64) {
self.raw.reserve(additional, hasher)
}
/// Tries to reserve capacity for at least `additional` more elements to be inserted
/// in the given `HashTable`. The collection may reserve more space to avoid
/// frequent reallocations.
///
/// `hasher` is called if entries need to be moved or copied to a new table.
/// This must return the same hash value that each entry was inserted with.
///
/// # Errors
///
/// If the capacity overflows, or the allocator reports a failure, then an error
/// is returned.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut table: HashTable<i32> = HashTable::new();
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// table
/// .try_reserve(10, hasher)
/// .expect("why is the test harness OOMing on 10 bytes?");
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn try_reserve(
&mut self,
additional: usize,
hasher: impl Fn(&T) -> u64,
) -> Result<(), TryReserveError> {
self.raw.try_reserve(additional, hasher)
}
/// Returns the number of elements the table can hold without reallocating.
///
/// # Examples
///
/// ```
/// use hashbrown::HashTable;
/// let table: HashTable<i32> = HashTable::with_capacity(100);
/// assert!(table.capacity() >= 100);
/// ```
pub fn capacity(&self) -> usize {
self.raw.capacity()
}
/// Returns the number of elements in the table.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// let mut v = HashTable::new();
/// assert_eq!(v.len(), 0);
/// v.insert_unique(hasher(&1), 1, hasher);
/// assert_eq!(v.len(), 1);
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn len(&self) -> usize {
self.raw.len()
}
/// Returns `true` if the set contains no elements.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// let mut v = HashTable::new();
/// assert!(v.is_empty());
/// v.insert_unique(hasher(&1), 1, hasher);
/// assert!(!v.is_empty());
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn is_empty(&self) -> bool {
self.raw.is_empty()
}
/// An iterator visiting all elements in arbitrary order.
/// The iterator element type is `&'a T`.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut table = HashTable::new();
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// table.insert_unique(hasher(&"a"), "b", hasher);
/// table.insert_unique(hasher(&"b"), "b", hasher);
///
/// // Will print in an arbitrary order.
/// for x in table.iter() {
/// println!("{}", x);
/// }
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn iter(&self) -> Iter<'_, T> {
Iter {
inner: unsafe { self.raw.iter() },
marker: PhantomData,
}
}
/// An iterator visiting all elements in arbitrary order,
/// with mutable references to the elements.
/// The iterator element type is `&'a mut T`.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut table = HashTable::new();
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// table.insert_unique(hasher(&1), 1, hasher);
/// table.insert_unique(hasher(&2), 2, hasher);
/// table.insert_unique(hasher(&3), 3, hasher);
///
/// // Update all values
/// for val in table.iter_mut() {
/// *val *= 2;
/// }
///
/// assert_eq!(table.len(), 3);
/// let mut vec: Vec<i32> = Vec::new();
///
/// for val in &table {
/// println!("val: {}", val);
/// vec.push(*val);
/// }
///
/// // The `Iter` iterator produces items in arbitrary order, so the
/// // items must be sorted to test them against a sorted array.
/// vec.sort_unstable();
/// assert_eq!(vec, [2, 4, 6]);
///
/// assert_eq!(table.len(), 3);
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn iter_mut(&mut self) -> IterMut<'_, T> {
IterMut {
inner: unsafe { self.raw.iter() },
marker: PhantomData,
}
}
/// Retains only the elements specified by the predicate.
///
/// In other words, remove all elements `e` such that `f(&e)` returns `false`.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut table = HashTable::new();
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// for x in 1..=6 {
/// table.insert_unique(hasher(&x), x, hasher);
/// }
/// table.retain(|&mut x| x % 2 == 0);
/// assert_eq!(table.len(), 3);
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn retain(&mut self, mut f: impl FnMut(&mut T) -> bool) {
// Here we only use `iter` as a temporary, preventing use-after-free
unsafe {
for item in self.raw.iter() {
if !f(item.as_mut()) {
self.raw.erase(item);
}
}
}
}
/// Clears the set, returning all elements in an iterator.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut table = HashTable::new();
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// for x in 1..=3 {
/// table.insert_unique(hasher(&x), x, hasher);
/// }
/// assert!(!table.is_empty());
///
/// // print 1, 2, 3 in an arbitrary order
/// for i in table.drain() {
/// println!("{}", i);
/// }
///
/// assert!(table.is_empty());
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn drain(&mut self) -> Drain<'_, T, A> {
Drain {
inner: self.raw.drain(),
}
}
/// Drains elements which are true under the given predicate,
/// and returns an iterator over the removed items.
///
/// In other words, move all elements `e` such that `f(&e)` returns `true` out
/// into another iterator.
///
/// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
/// or the iteration short-circuits, then the remaining elements will be retained.
/// Use [`retain()`] with a negated predicate if you do not need the returned iterator.
///
/// [`retain()`]: HashTable::retain
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut table = HashTable::new();
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// for x in 0..8 {
/// table.insert_unique(hasher(&x), x, hasher);
/// }
/// let drained: Vec<i32> = table.extract_if(|&mut v| v % 2 == 0).collect();
///
/// let mut evens = drained.into_iter().collect::<Vec<_>>();
/// let mut odds = table.into_iter().collect::<Vec<_>>();
/// evens.sort();
/// odds.sort();
///
/// assert_eq!(evens, vec![0, 2, 4, 6]);
/// assert_eq!(odds, vec![1, 3, 5, 7]);
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn extract_if<F>(&mut self, f: F) -> ExtractIf<'_, T, F, A>
where
F: FnMut(&mut T) -> bool,
{
ExtractIf {
f,
inner: RawExtractIf {
iter: unsafe { self.raw.iter() },
table: &mut self.raw,
},
}
}
/// Attempts to get mutable references to `N` values in the map at once.
///
/// The `eq` argument should be a closure such that `eq(i, k)` returns true if `k` is equal to
/// the `i`th key to be looked up.
///
/// Returns an array of length `N` with the results of each query. For soundness, at most one
/// mutable reference will be returned to any value. `None` will be returned if any of the
/// keys are duplicates or missing.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::hash_table::Entry;
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut libraries: HashTable<(&str, u32)> = HashTable::new();
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// for (k, v) in [
/// ("Bodleian Library", 1602),
/// ("Athenæum", 1807),
/// ("Herzogin-Anna-Amalia-Bibliothek", 1691),
/// ("Library of Congress", 1800),
/// ] {
/// libraries.insert_unique(hasher(&k), (k, v), |(k, _)| hasher(&k));
/// }
///
/// let keys = ["Athenæum", "Library of Congress"];
/// let got = libraries.get_many_mut(keys.map(|k| hasher(&k)), |i, val| keys[i] == val.0);
/// assert_eq!(
/// got,
/// Some([&mut ("Athenæum", 1807), &mut ("Library of Congress", 1800),]),
/// );
///
/// // Missing keys result in None
/// let keys = ["Athenæum", "New York Public Library"];
/// let got = libraries.get_many_mut(keys.map(|k| hasher(&k)), |i, val| keys[i] == val.0);
/// assert_eq!(got, None);
///
/// // Duplicate keys result in None
/// let keys = ["Athenæum", "Athenæum"];
/// let got = libraries.get_many_mut(keys.map(|k| hasher(&k)), |i, val| keys[i] == val.0);
/// assert_eq!(got, None);
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn get_many_mut<const N: usize>(
&mut self,
hashes: [u64; N],
eq: impl FnMut(usize, &T) -> bool,
) -> Option<[&'_ mut T; N]> {
self.raw.get_many_mut(hashes, eq)
}
/// Attempts to get mutable references to `N` values in the map at once, without validating that
/// the values are unique.
///
/// The `eq` argument should be a closure such that `eq(i, k)` returns true if `k` is equal to
/// the `i`th key to be looked up.
///
/// Returns an array of length `N` with the results of each query. `None` will be returned if
/// any of the keys are missing.
///
/// For a safe alternative see [`get_many_mut`](`HashTable::get_many_mut`).
///
/// # Safety
///
/// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
/// references are not used.
///
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use hashbrown::hash_table::Entry;
/// use hashbrown::{HashTable, DefaultHashBuilder};
/// use std::hash::BuildHasher;
///
/// let mut libraries: HashTable<(&str, u32)> = HashTable::new();
/// let hasher = DefaultHashBuilder::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// for (k, v) in [
/// ("Bodleian Library", 1602),
/// ("Athenæum", 1807),
/// ("Herzogin-Anna-Amalia-Bibliothek", 1691),
/// ("Library of Congress", 1800),
/// ] {
/// libraries.insert_unique(hasher(&k), (k, v), |(k, _)| hasher(&k));
/// }
///
/// let keys = ["Athenæum", "Library of Congress"];
/// let got = libraries.get_many_mut(keys.map(|k| hasher(&k)), |i, val| keys[i] == val.0);
/// assert_eq!(
/// got,
/// Some([&mut ("Athenæum", 1807), &mut ("Library of Congress", 1800),]),
/// );
///
/// // Missing keys result in None
/// let keys = ["Athenæum", "New York Public Library"];
/// let got = libraries.get_many_mut(keys.map(|k| hasher(&k)), |i, val| keys[i] == val.0);
/// assert_eq!(got, None);
///
/// // Duplicate keys result in None
/// let keys = ["Athenæum", "Athenæum"];
/// let got = libraries.get_many_mut(keys.map(|k| hasher(&k)), |i, val| keys[i] == val.0);
/// assert_eq!(got, None);
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub unsafe fn get_many_unchecked_mut<const N: usize>(
&mut self,
hashes: [u64; N],
eq: impl FnMut(usize, &T) -> bool,
) -> Option<[&'_ mut T; N]> {
self.raw.get_many_unchecked_mut(hashes, eq)
}
}