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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
//! [`HashSet`] is an asynchronous/concurrent hash set.
#![deny(unsafe_code)]
use std::collections::hash_map::RandomState;
use std::fmt::{self, Debug};
use std::hash::{BuildHasher, Hash};
use std::mem::swap;
use std::ops::{Deref, RangeInclusive};
use super::hash_map;
use super::hash_table::{HashTable, num_entries_from_hint};
use super::{Equivalent, HashMap};
/// Scalable asynchronous/concurrent hash set.
///
/// [`HashSet`] is an asynchronous/concurrent hash set based on [`HashMap`].
pub struct HashSet<K, H = RandomState>
where
H: BuildHasher,
{
map: HashMap<K, (), H>,
}
/// [`OccupiedEntry`] is a view into an occupied entry in a [`HashSet`].
pub struct OccupiedEntry<'h, K, H = RandomState>
where
H: BuildHasher,
{
occupied: hash_map::OccupiedEntry<'h, K, (), H>,
}
/// [`ConsumableEntry`] is a view into an occupied entry in a [`HashSet`] when iterating over
/// entries in it.
pub struct ConsumableEntry<'w, K> {
consumable: hash_map::ConsumableEntry<'w, K, ()>,
}
/// [`Reserve`] keeps the capacity of the associated [`HashSet`] higher than a certain level.
///
/// The [`HashSet`] does not shrink the capacity below the reserved capacity.
pub type Reserve<'h, K, H = RandomState> = super::hash_map::Reserve<'h, K, (), H>;
impl<K, H> HashSet<K, H>
where
H: BuildHasher,
{
/// Creates an empty [`HashSet`] with the given [`BuildHasher`].
///
/// # Examples
///
/// ```
/// use scc::HashSet;
/// use std::collections::hash_map::RandomState;
///
/// let hashset: HashSet<u64, RandomState> = HashSet::with_hasher(RandomState::new());
/// ```
#[cfg(not(feature = "loom"))]
#[inline]
pub const fn with_hasher(build_hasher: H) -> Self {
Self {
map: HashMap::with_hasher(build_hasher),
}
}
/// Creates an empty [`HashSet`] with the given [`BuildHasher`].
#[cfg(feature = "loom")]
#[inline]
pub fn with_hasher(build_hasher: H) -> Self {
Self {
map: HashMap::with_hasher(build_hasher),
}
}
/// Creates an empty [`HashSet`] with the specified capacity and [`BuildHasher`].
///
/// The actual capacity is equal to or greater than `capacity` unless it is greater than
/// `1 << (usize::BITS - 1)`.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
/// use std::collections::hash_map::RandomState;
///
/// let hashset: HashSet<u64, RandomState> =
/// HashSet::with_capacity_and_hasher(800, RandomState::new());
///
/// let result = hashset.capacity();
/// assert_eq!(result, 1024);
/// ```
#[inline]
pub fn with_capacity_and_hasher(capacity: usize, build_hasher: H) -> Self {
Self {
map: HashMap::with_capacity_and_hasher(capacity, build_hasher),
}
}
}
impl<K, H> HashSet<K, H>
where
K: Eq + Hash,
H: BuildHasher,
{
/// Temporarily increases the minimum capacity of the [`HashSet`].
///
/// A [`Reserve`] is returned if the [`HashSet`] could increase the minimum capacity while the
/// increased capacity is not exclusively owned by the returned [`Reserve`], allowing others to
/// benefit from it. The memory for the additional space may not be immediately allocated if
/// the [`HashSet`] is empty or currently being resized, however once the memory is reserved
/// eventually, the capacity will not shrink below the additional capacity until the returned
/// [`Reserve`] is dropped.
///
/// # Errors
///
/// Returns `None` if a too large number is given.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<usize> = HashSet::with_capacity(800);
/// assert_eq!(hashset.capacity(), 1024);
///
/// let reserved = hashset.reserve(10000);
/// assert!(reserved.is_some());
/// assert_eq!(hashset.capacity(), 16384);
///
/// assert!(hashset.reserve(usize::MAX).is_none());
/// assert_eq!(hashset.capacity(), 16384);
///
/// for i in 0..16 {
/// assert!(hashset.insert_sync(i).is_ok());
/// }
/// drop(reserved);
///
/// assert_eq!(hashset.capacity(), 1024);
/// ```
#[inline]
pub fn reserve(&self, capacity: usize) -> Option<Reserve<'_, K, H>> {
self.map.reserve(capacity)
}
/// Begins iterating over entries by getting the first occupied entry.
///
/// The returned [`OccupiedEntry`] in combination with [`OccupiedEntry::next_async`] can act as
/// a mutable iterator over entries.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u32> = HashSet::default();
///
/// let future_entry = hashset.begin_async();
/// ```
#[inline]
pub async fn begin_async(&self) -> Option<OccupiedEntry<'_, K, H>> {
self.any_async(|_| true).await
}
/// Begins iterating over entries by getting the first occupied entry.
///
/// The returned [`OccupiedEntry`] in combination with [`OccupiedEntry::next_sync`] can act as a
/// mutable iterator over entries.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// assert!(hashset.insert_sync(1).is_ok());
///
/// let mut first_entry = hashset.begin_sync().unwrap();
/// assert_eq!(*first_entry.get(), 1);
///
/// assert!(first_entry.next_sync().is_none());
/// assert!(hashset.read_sync(&1, |_| true).unwrap());
/// ```
#[inline]
pub fn begin_sync(&self) -> Option<OccupiedEntry<'_, K, H>> {
self.any_sync(|_| true)
}
/// Finds any entry satisfying the supplied predicate for in-place manipulation.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u32> = HashSet::default();
///
/// let future_entry = hashset.any_async(|k| *k == 2);
/// ```
#[inline]
pub async fn any_async<P: FnMut(&K) -> bool>(
&self,
mut pred: P,
) -> Option<OccupiedEntry<'_, K, H>> {
self.map
.any_async(|k, ()| pred(k))
.await
.map(|occupied| OccupiedEntry { occupied })
}
/// Finds any entry satisfying the supplied predicate for in-place manipulation.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u32> = HashSet::default();
///
/// assert!(hashset.insert_sync(1).is_ok());
/// assert!(hashset.insert_sync(2).is_ok());
///
/// let mut entry = hashset.any_sync(|k| *k == 2).unwrap();
/// assert_eq!(*entry.get(), 2);
/// ```
#[inline]
pub fn any_sync<P: FnMut(&K) -> bool>(&self, mut pred: P) -> Option<OccupiedEntry<'_, K, H>> {
self.map
.any_sync(|k, ()| pred(k))
.map(|occupied| OccupiedEntry { occupied })
}
/// Inserts a key into the [`HashSet`].
///
/// # Errors
///
/// Returns an error along with the supplied key if the key exists.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
/// let future_insert = hashset.insert_async(11);
/// ```
#[inline]
pub async fn insert_async(&self, key: K) -> Result<(), K> {
self.map.insert_async(key, ()).await.map_err(|(k, ())| k)
}
/// Inserts a key into the [`HashSet`].
///
/// # Errors
///
/// Returns an error along with the supplied key if the key exists.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// assert!(hashset.insert_sync(1).is_ok());
/// assert_eq!(hashset.insert_sync(1).unwrap_err(), 1);
/// ```
#[inline]
pub fn insert_sync(&self, key: K) -> Result<(), K> {
if let Err((k, ())) = self.map.insert_sync(key, ()) {
return Err(k);
}
Ok(())
}
/// Adds a key to the set, replacing the existing key, if any, that is equal to the given one.
///
/// Returns the replaced key, if any.
///
/// # Examples
///
/// ```
/// use std::cmp::{Eq, PartialEq};
/// use std::hash::{Hash, Hasher};
///
/// use scc::HashSet;
///
/// #[derive(Debug)]
/// struct MaybeEqual(u64, u64);
///
/// impl Eq for MaybeEqual {}
///
/// impl Hash for MaybeEqual {
/// fn hash<H: Hasher>(&self, state: &mut H) {
/// // Do not read `self.1`.
/// self.0.hash(state);
/// }
/// }
///
/// impl PartialEq for MaybeEqual {
/// fn eq(&self, other: &Self) -> bool {
/// // Do not compare `self.1`.
/// self.0 == other.0
/// }
/// }
///
/// let hashset: HashSet<MaybeEqual> = HashSet::default();
///
/// assert!(hashset.replace_sync(MaybeEqual(11, 7)).is_none());
/// assert_eq!(hashset.replace_sync(MaybeEqual(11, 11)), Some(MaybeEqual(11, 7)));
/// ```
#[inline]
pub async fn replace_async(&self, mut key: K) -> Option<K> {
let hash = self.map.hash(&key);
let mut locked_bucket = self.map.writer_async(hash).await;
let mut entry_ptr = locked_bucket.search(&key, hash);
if entry_ptr.is_valid() {
let k = locked_bucket.entry_mut(&mut entry_ptr).0;
swap(k, &mut key);
Some(key)
} else {
locked_bucket.insert(hash, (key, ()));
None
}
}
/// Adds a key to the set, replacing the existing key, if any, that is equal to the given one.
///
/// Returns the replaced key, if any.
///
/// # Examples
///
/// ```
/// use std::cmp::{Eq, PartialEq};
/// use std::hash::{Hash, Hasher};
///
/// use scc::HashSet;
///
/// #[derive(Debug)]
/// struct MaybeEqual(u64, u64);
///
/// impl Eq for MaybeEqual {}
///
/// impl Hash for MaybeEqual {
/// fn hash<H: Hasher>(&self, state: &mut H) {
/// // Do not read `self.1`.
/// self.0.hash(state);
/// }
/// }
///
/// impl PartialEq for MaybeEqual {
/// fn eq(&self, other: &Self) -> bool {
/// // Do not compare `self.1`.
/// self.0 == other.0
/// }
/// }
///
/// let hashset: HashSet<MaybeEqual> = HashSet::default();
///
/// async {
/// assert!(hashset.replace_async(MaybeEqual(11, 7)).await.is_none());
/// assert_eq!(hashset.replace_async(MaybeEqual(11, 11)).await, Some(MaybeEqual(11, 7)));
/// };
/// ```
#[inline]
pub fn replace_sync(&self, mut key: K) -> Option<K> {
let hash = self.map.hash(&key);
let mut locked_bucket = self.map.writer_sync(hash);
let mut entry_ptr = locked_bucket.search(&key, hash);
if entry_ptr.is_valid() {
let k = locked_bucket.entry_mut(&mut entry_ptr).0;
swap(k, &mut key);
Some(key)
} else {
locked_bucket.insert(hash, (key, ()));
None
}
}
/// Removes a key if the key exists.
///
/// Returns `None` if the key does not exist.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
/// let future_insert = hashset.insert_async(11);
/// let future_remove = hashset.remove_async(&11);
/// ```
#[inline]
pub async fn remove_async<Q>(&self, key: &Q) -> Option<K>
where
Q: Equivalent<K> + Hash + ?Sized,
{
self.map
.remove_if_async(key, |()| true)
.await
.map(|(k, ())| k)
}
/// Removes a key if the key exists.
///
/// Returns `None` if the key does not exist.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// assert!(hashset.remove_sync(&1).is_none());
/// assert!(hashset.insert_sync(1).is_ok());
/// assert_eq!(hashset.remove_sync(&1).unwrap(), 1);
/// ```
#[inline]
pub fn remove_sync<Q>(&self, key: &Q) -> Option<K>
where
Q: Equivalent<K> + Hash + ?Sized,
{
self.map.remove_sync(key).map(|(k, ())| k)
}
/// Removes a key if the key exists and the given condition is met.
///
/// Returns `None` if the key does not exist or the condition was not met.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
/// let future_insert = hashset.insert_async(11);
/// let future_remove = hashset.remove_if_async(&11, || true);
/// ```
#[inline]
pub async fn remove_if_async<Q, F: FnOnce() -> bool>(&self, key: &Q, condition: F) -> Option<K>
where
Q: Equivalent<K> + Hash + ?Sized,
{
self.map
.remove_if_async(key, |()| condition())
.await
.map(|(k, ())| k)
}
/// Removes a key if the key exists and the given condition is met.
///
/// Returns `None` if the key does not exist or the condition was not met.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// assert!(hashset.insert_sync(1).is_ok());
/// assert!(hashset.remove_if_sync(&1, || false).is_none());
/// assert_eq!(hashset.remove_if_sync(&1, || true).unwrap(), 1);
/// ```
#[inline]
pub fn remove_if_sync<Q, F: FnOnce() -> bool>(&self, key: &Q, condition: F) -> Option<K>
where
Q: Equivalent<K> + Hash + ?Sized,
{
self.map
.remove_if_sync(key, |()| condition())
.map(|(k, ())| k)
}
/// Reads a key.
///
/// Returns `None` if the key does not exist.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
/// let future_insert = hashset.insert_async(11);
/// let future_read = hashset.read_async(&11, |k| *k);
/// ```
#[inline]
pub async fn read_async<Q, R, F: FnOnce(&K) -> R>(&self, key: &Q, reader: F) -> Option<R>
where
Q: Equivalent<K> + Hash + ?Sized,
{
self.map.read_async(key, |k, ()| reader(k)).await
}
/// Reads a key.
///
/// Returns `None` if the key does not exist.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// assert!(hashset.read_sync(&1, |_| true).is_none());
/// assert!(hashset.insert_sync(1).is_ok());
/// assert!(hashset.read_sync(&1, |_| true).unwrap());
/// ```
#[inline]
pub fn read_sync<Q, R, F: FnOnce(&K) -> R>(&self, key: &Q, reader: F) -> Option<R>
where
Q: Equivalent<K> + Hash + ?Sized,
{
self.map.read_sync(key, |k, ()| reader(k))
}
/// Returns `true` if the [`HashSet`] contains the specified key.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// let future_contains = hashset.contains_async(&1);
/// ```
#[inline]
pub async fn contains_async<Q>(&self, key: &Q) -> bool
where
Q: Equivalent<K> + Hash + ?Sized,
{
self.map.contains_async(key).await
}
/// Returns `true` if the [`HashSet`] contains the specified key.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// assert!(!hashset.contains_sync(&1));
/// assert!(hashset.insert_sync(1).is_ok());
/// assert!(hashset.contains_sync(&1));
/// ```
#[inline]
pub fn contains_sync<Q>(&self, key: &Q) -> bool
where
Q: Equivalent<K> + Hash + ?Sized,
{
self.read_sync(key, |_| ()).is_some()
}
/// Iterates over entries asynchronously for reading.
///
/// Stops iterating when the closure returns `false`, and this method also returns `false`.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// assert!(hashset.insert_sync(1).is_ok());
///
/// async {
/// let result = hashset.iter_async(|k| {
/// true
/// }).await;
/// assert!(result);
/// };
/// ```
#[inline]
pub async fn iter_async<F: FnMut(&K) -> bool>(&self, mut f: F) -> bool {
self.map.iter_async(|k, ()| f(k)).await
}
/// Iterates over entries synchronously for reading.
///
/// Stops iterating when the closure returns `false`, and this method also returns `false`.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// assert!(hashset.insert_sync(1).is_ok());
/// assert!(hashset.insert_sync(2).is_ok());
///
/// let mut acc = 0;
/// let result = hashset.iter_sync(|k| {
/// acc += *k;
/// true
/// });
///
/// assert!(result);
/// assert_eq!(acc, 3);
/// ```
#[inline]
pub fn iter_sync<F: FnMut(&K) -> bool>(&self, mut f: F) -> bool {
self.map.iter_sync(|k, ()| f(k))
}
/// Iterates over entries asynchronously for modification.
///
/// This method stops iterating when the closure returns `false`, and also returns `false` in
/// that case.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// assert!(hashset.insert_sync(1).is_ok());
/// assert!(hashset.insert_sync(2).is_ok());
///
/// async {
/// let result = hashset.iter_mut_async(|e| {
/// if *e == 1 {
/// e.consume();
/// return false;
/// }
/// true
/// }).await;
///
/// assert!(!result);
/// assert_eq!(hashset.len(), 1);
/// };
/// ```
#[inline]
pub async fn iter_mut_async<F: FnMut(ConsumableEntry<'_, K>) -> bool>(&self, mut f: F) -> bool {
self.map
.iter_mut_async(|consumable| f(ConsumableEntry { consumable }))
.await
}
/// Iterates over entries synchronously for modification.
///
/// This method stops iterating when the closure returns `false`, and also returns `false` in
/// that case.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// assert!(hashset.insert_sync(1).is_ok());
/// assert!(hashset.insert_sync(2).is_ok());
/// assert!(hashset.insert_sync(3).is_ok());
///
/// let result = hashset.iter_mut_sync(|e| {
/// if *e == 1 {
/// e.consume();
/// return false;
/// }
/// true
/// });
///
/// assert!(!result);
/// assert!(!hashset.contains_sync(&1));
/// assert_eq!(hashset.len(), 2);
/// ```
#[inline]
pub fn iter_mut_sync<F: FnMut(ConsumableEntry<'_, K>) -> bool>(&self, mut f: F) -> bool {
self.map
.iter_mut_sync(|consumable| f(ConsumableEntry { consumable }))
}
/// Retains keys that satisfy the given predicate.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// let future_insert = hashset.insert_async(1);
/// let future_retain = hashset.retain_async(|k| *k == 1);
/// ```
#[inline]
pub async fn retain_async<F: FnMut(&K) -> bool>(&self, mut filter: F) {
self.map.retain_async(|k, ()| filter(k)).await;
}
/// Retains keys that satisfy the given predicate.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// assert!(hashset.insert_sync(1).is_ok());
/// assert!(hashset.insert_sync(2).is_ok());
/// assert!(hashset.insert_sync(3).is_ok());
///
/// hashset.retain_sync(|k| *k == 1);
///
/// assert!(hashset.contains_sync(&1));
/// assert!(!hashset.contains_sync(&2));
/// assert!(!hashset.contains_sync(&3));
/// ```
#[inline]
pub fn retain_sync<F: FnMut(&K) -> bool>(&self, mut pred: F) {
self.iter_mut_sync(|e| {
if !pred(&*e) {
drop(e.consume());
}
true
});
}
/// Clears the [`HashSet`] by removing all keys.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// let future_insert = hashset.insert_async(1);
/// let future_clear = hashset.clear_async();
/// ```
#[inline]
pub async fn clear_async(&self) {
self.map.clear_async().await;
}
/// Clears the [`HashSet`] by removing all keys.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// assert!(hashset.insert_sync(1).is_ok());
/// hashset.clear_sync();
///
/// assert!(!hashset.contains_sync(&1));
/// ```
#[inline]
pub fn clear_sync(&self) {
self.map.clear_sync();
}
/// Returns the number of entries in the [`HashSet`].
///
/// It reads the entire metadata area of the bucket array to calculate the number of valid
/// entries, making its time complexity `O(N)`. Furthermore, it may overcount entries if an old
/// bucket array has yet to be dropped.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// assert!(hashset.insert_sync(1).is_ok());
/// assert_eq!(hashset.len(), 1);
/// ```
#[inline]
pub fn len(&self) -> usize {
self.map.len()
}
/// Returns `true` if the [`HashSet`] is empty.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// assert!(hashset.is_empty());
/// assert!(hashset.insert_sync(1).is_ok());
/// assert!(!hashset.is_empty());
/// ```
#[inline]
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
/// Returns the capacity of the [`HashSet`].
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset_default: HashSet<u64> = HashSet::default();
/// assert_eq!(hashset_default.capacity(), 0);
///
/// assert!(hashset_default.insert_sync(1).is_ok());
/// assert_eq!(hashset_default.capacity(), 64);
///
/// let hashset: HashSet<u64> = HashSet::with_capacity(800);
/// assert_eq!(hashset.capacity(), 1024);
/// ```
#[inline]
pub fn capacity(&self) -> usize {
self.map.capacity()
}
/// Returns the current capacity range of the [`HashSet`].
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// assert_eq!(hashset.capacity_range(), 0..=(1_usize << (usize::BITS - 2)));
///
/// let reserved = hashset.reserve(1000);
/// assert_eq!(hashset.capacity_range(), 1000..=(1_usize << (usize::BITS - 2)));
/// ```
#[inline]
pub fn capacity_range(&self) -> RangeInclusive<usize> {
self.map.capacity_range()
}
/// Returns the index of the bucket that may contain the key.
///
/// The method returns the index of the bucket associated with the key. The number of buckets
/// can be calculated by dividing the capacity by `32`.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::with_capacity(1024);
///
/// let bucket_index = hashset.bucket_index(&11);
/// assert!(bucket_index < hashset.capacity() / 32);
/// ```
#[inline]
pub fn bucket_index<Q>(&self, key: &Q) -> usize
where
Q: Equivalent<K> + Hash + ?Sized,
{
self.map.bucket_index(key)
}
}
impl<K, H> Clone for HashSet<K, H>
where
K: Clone + Eq + Hash,
H: BuildHasher + Clone,
{
#[inline]
fn clone(&self) -> Self {
Self {
map: self.map.clone(),
}
}
}
impl<K, H> Debug for HashSet<K, H>
where
K: Debug + Eq + Hash,
H: BuildHasher,
{
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_set();
self.iter_sync(|k| {
d.entry(k);
true
});
d.finish()
}
}
impl<K: Eq + Hash> HashSet<K, RandomState> {
/// Creates an empty default [`HashSet`].
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::new();
///
/// let result = hashset.capacity();
/// assert_eq!(result, 0);
/// ```
#[inline]
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Creates an empty [`HashSet`] with the specified capacity.
///
/// The actual capacity is equal to or greater than `capacity` unless it is greater than
/// `1 << (usize::BITS - 1)`.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::with_capacity(800);
///
/// let result = hashset.capacity();
/// assert_eq!(result, 1024);
/// ```
#[inline]
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
Self {
map: HashMap::with_capacity(capacity),
}
}
}
impl<K, H> Default for HashSet<K, H>
where
H: BuildHasher + Default,
{
/// Creates an empty default [`HashSet`].
///
/// The default capacity is `0`.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// let result = hashset.capacity();
/// assert_eq!(result, 0);
/// ```
#[inline]
fn default() -> Self {
Self {
map: HashMap::default(),
}
}
}
impl<K, H> FromIterator<K> for HashSet<K, H>
where
K: Eq + Hash,
H: BuildHasher + Default,
{
#[inline]
fn from_iter<T: IntoIterator<Item = K>>(iter: T) -> Self {
let into_iter = iter.into_iter();
let hashset = Self::with_capacity_and_hasher(
num_entries_from_hint(into_iter.size_hint()),
H::default(),
);
into_iter.for_each(|k| {
let _result = hashset.insert_sync(k);
});
hashset
}
}
impl<K, H> PartialEq for HashSet<K, H>
where
K: Eq + Hash,
H: BuildHasher,
{
/// Compares two [`HashSet`] instances.
///
/// ### Locking behavior
///
/// Shared locks on buckets are acquired when comparing two instances of [`HashSet`], therefore
/// it may lead to a deadlock if the instances are being modified by another thread.
#[inline]
fn eq(&self, other: &Self) -> bool {
if self.iter_sync(|k| other.contains_sync(k)) {
return other.iter_sync(|k| self.contains_sync(k));
}
false
}
}
impl<'h, K, H> OccupiedEntry<'h, K, H>
where
K: Eq + Hash,
H: BuildHasher,
{
/// Takes ownership of the value from the [`HashSet`].
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u32> = HashSet::default();
/// hashset.insert_sync(42);
///
/// assert_eq!(hashset.begin_sync().unwrap().remove_entry(), 42);
/// ```
#[inline]
#[must_use]
pub fn remove_entry(self) -> K {
self.occupied.remove_entry().0
}
/// Gets a reference to the value in the entry.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let mut hashset: HashSet<u32> = HashSet::default();
/// hashset.insert_sync(42);
///
/// assert_eq!(hashset.begin_sync().unwrap().get(), &42);
/// ```
#[inline]
#[must_use]
pub fn get(&self) -> &K {
self.occupied.key()
}
/// Removes the entry and gets the next closest occupied entry.
///
/// [`HashSet::begin_async`] and this method together allow the [`OccupiedEntry`] to
/// effectively act as a mutable iterator over entries. This method never acquires more than one
/// lock, even when it searches other buckets for the next closest occupied entry.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u32> = HashSet::default();
///
/// assert!(hashset.insert_sync(1).is_ok());
/// assert!(hashset.insert_sync(2).is_ok());
///
/// let second_entry_future = hashset.begin_sync().unwrap().remove_and_async();
/// ```
#[inline]
pub async fn remove_and_async(self) -> (K, Option<OccupiedEntry<'h, K, H>>) {
let ((k, ()), occupied) = self.occupied.remove_and_async().await;
(k, occupied.map(|occupied| Self { occupied }))
}
/// Removes the entry and gets the next closest occupied entry.
///
/// [`HashSet::begin_sync`] and this method together allow the [`OccupiedEntry`] to effectively
/// act as a mutable iterator over entries. This method never acquires more than one lock, even
/// when it searches other buckets for the next closest occupied entry.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u32> = HashSet::default();
///
/// assert!(hashset.insert_sync(1).is_ok());
/// assert!(hashset.insert_sync(2).is_ok());
///
/// let first_entry = hashset.begin_sync().unwrap();
/// let first_value = *first_entry.get();
/// let (_, second_entry) = first_entry.remove_and_sync();
/// assert_eq!(hashset.len(), 1);
///
/// let second_entry = second_entry.unwrap();
/// let second_value = *second_entry.get();
///
/// assert!(second_entry.remove_and_sync().1.is_none());
/// assert_eq!(first_value + second_value, 3);
/// ```
#[inline]
#[must_use]
pub fn remove_and_sync(self) -> (K, Option<Self>) {
let ((k, ()), occupied) = self.occupied.remove_and_sync();
(k, occupied.map(|occupied| Self { occupied }))
}
/// Gets the next closest occupied entry.
///
/// [`HashSet::begin_async`] and this method together allow the [`OccupiedEntry`] to
/// effectively act as a mutable iterator over entries. This method never acquires more than one
/// lock, even when it searches other buckets for the next closest occupied entry.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u32> = HashSet::default();
///
/// assert!(hashset.insert_sync(1).is_ok());
/// assert!(hashset.insert_sync(2).is_ok());
///
/// let second_entry_future = hashset.begin_sync().unwrap().next_async();
/// ```
#[inline]
pub async fn next_async(self) -> Option<OccupiedEntry<'h, K, H>> {
self.occupied
.next_async()
.await
.map(|occupied| Self { occupied })
}
/// Gets the next closest occupied entry.
///
/// [`HashSet::begin_sync`] and this method together allow the [`OccupiedEntry`] to effectively
/// act as a mutable iterator over entries. This method never acquires more than one lock, even
/// when it searches other buckets for the next closest occupied entry.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u32> = HashSet::default();
///
/// assert!(hashset.insert_sync(1).is_ok());
/// assert!(hashset.insert_sync(2).is_ok());
///
/// let first_entry = hashset.begin_sync().unwrap();
/// let first_value = *first_entry.get();
/// let second_entry = first_entry.next_sync().unwrap();
/// let second_value = *second_entry.get();
///
/// assert!(second_entry.next_sync().is_none());
/// assert_eq!(first_value + second_value, 3);
/// ```
#[inline]
#[must_use]
pub fn next_sync(self) -> Option<Self> {
self.occupied.next_sync().map(|occupied| Self { occupied })
}
}
impl<K, H> Debug for OccupiedEntry<'_, K, H>
where
K: Debug + Eq + Hash,
H: BuildHasher,
{
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OccupiedEntry")
.field("data", self.get())
.finish_non_exhaustive()
}
}
impl<K, H> Deref for OccupiedEntry<'_, K, H>
where
K: Eq + Hash,
H: BuildHasher,
{
type Target = K;
#[inline]
fn deref(&self) -> &Self::Target {
self.get()
}
}
impl<K> ConsumableEntry<'_, K> {
/// Consumes the entry by moving out the key.
///
/// # Examples
///
/// ```
/// use scc::HashSet;
///
/// let hashset: HashSet<u64> = HashSet::default();
///
/// assert!(hashset.insert_sync(1).is_ok());
/// assert!(hashset.insert_sync(2).is_ok());
/// assert!(hashset.insert_sync(3).is_ok());
///
/// let mut consumed = None;
///
/// hashset.iter_mut_sync(|e| {
/// if *e == 1 {
/// consumed.replace(e.consume());
/// }
/// true
/// });
///
/// assert!(!hashset.contains_sync(&1));
/// assert_eq!(consumed, Some(1));
/// ```
#[inline]
#[must_use]
pub fn consume(self) -> K {
self.consumable.consume().0
}
}
impl<K> Deref for ConsumableEntry<'_, K> {
type Target = K;
#[inline]
fn deref(&self) -> &Self::Target {
self.consumable.key()
}
}