-
Notifications
You must be signed in to change notification settings - Fork 293
/
Copy pathmod.rs
4817 lines (4461 loc) · 202 KB
/
mod.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 crate::alloc::alloc::{handle_alloc_error, Layout};
use crate::scopeguard::{guard, ScopeGuard};
use crate::TryReserveError;
use core::iter::FusedIterator;
use core::marker::PhantomData;
use core::mem;
use core::mem::MaybeUninit;
use core::ptr::NonNull;
use core::{hint, ptr};
cfg_if! {
// Use the SSE2 implementation if possible: it allows us to scan 16 buckets
// at once instead of 8. We don't bother with AVX since it would require
// runtime dispatch and wouldn't gain us much anyways: the probability of
// finding a match drops off drastically after the first few buckets.
//
// I attempted an implementation on ARM using NEON instructions, but it
// turns out that most NEON instructions have multi-cycle latency, which in
// the end outweighs any gains over the generic implementation.
if #[cfg(all(
target_feature = "sse2",
any(target_arch = "x86", target_arch = "x86_64"),
not(miri),
))] {
mod sse2;
use sse2 as imp;
} else if #[cfg(all(
target_arch = "aarch64",
target_feature = "neon",
// NEON intrinsics are currently broken on big-endian targets.
// See https://github.com/rust-lang/stdarch/issues/1484.
target_endian = "little",
not(miri),
))] {
mod neon;
use neon as imp;
} else {
mod generic;
use generic as imp;
}
}
mod alloc;
pub(crate) use self::alloc::{do_alloc, Allocator, Global};
mod bitmask;
use self::bitmask::BitMaskIter;
use self::imp::Group;
// Branch prediction hint. This is currently only available on nightly but it
// consistently improves performance by 10-15%.
#[cfg(not(feature = "nightly"))]
use core::convert::identity as likely;
#[cfg(not(feature = "nightly"))]
use core::convert::identity as unlikely;
#[cfg(feature = "nightly")]
use core::intrinsics::{likely, unlikely};
// FIXME: use strict provenance functions once they are stable.
// Implement it with a transmute for now.
#[inline(always)]
#[allow(clippy::useless_transmute)] // clippy is wrong, cast and transmute are different here
fn invalid_mut<T>(addr: usize) -> *mut T {
unsafe { core::mem::transmute(addr) }
}
#[inline]
unsafe fn offset_from<T>(to: *const T, from: *const T) -> usize {
to.offset_from(from) as usize
}
/// Whether memory allocation errors should return an error or abort.
#[derive(Copy, Clone)]
enum Fallibility {
Fallible,
Infallible,
}
impl Fallibility {
/// Error to return on capacity overflow.
#[cfg_attr(feature = "inline-more", inline)]
fn capacity_overflow(self) -> TryReserveError {
match self {
Fallibility::Fallible => TryReserveError::CapacityOverflow,
Fallibility::Infallible => panic!("Hash table capacity overflow"),
}
}
/// Error to return on allocation error.
#[cfg_attr(feature = "inline-more", inline)]
fn alloc_err(self, layout: Layout) -> TryReserveError {
match self {
Fallibility::Fallible => TryReserveError::AllocError { layout },
Fallibility::Infallible => handle_alloc_error(layout),
}
}
}
trait SizedTypeProperties: Sized {
const IS_ZERO_SIZED: bool = mem::size_of::<Self>() == 0;
const NEEDS_DROP: bool = mem::needs_drop::<Self>();
}
impl<T> SizedTypeProperties for T {}
/// Control byte value for an empty bucket.
const EMPTY: u8 = 0b1111_1111;
/// Control byte value for a deleted bucket.
const DELETED: u8 = 0b1000_0000;
/// Checks whether a control byte represents a full bucket (top bit is clear).
#[inline]
fn is_full(ctrl: u8) -> bool {
ctrl & 0x80 == 0
}
/// Checks whether a control byte represents a special value (top bit is set).
#[inline]
fn is_special(ctrl: u8) -> bool {
ctrl & 0x80 != 0
}
/// Checks whether a special control value is EMPTY (just check 1 bit).
#[inline]
fn special_is_empty(ctrl: u8) -> bool {
debug_assert!(is_special(ctrl));
ctrl & 0x01 != 0
}
/// Primary hash function, used to select the initial bucket to probe from.
#[inline]
#[allow(clippy::cast_possible_truncation)]
fn h1(hash: u64) -> usize {
// On 32-bit platforms we simply ignore the higher hash bits.
hash as usize
}
// Constant for h2 function that grabing the top 7 bits of the hash.
const MIN_HASH_LEN: usize = if mem::size_of::<usize>() < mem::size_of::<u64>() {
mem::size_of::<usize>()
} else {
mem::size_of::<u64>()
};
/// Secondary hash function, saved in the low 7 bits of the control byte.
#[inline]
#[allow(clippy::cast_possible_truncation)]
fn h2(hash: u64) -> u8 {
// Grab the top 7 bits of the hash. While the hash is normally a full 64-bit
// value, some hash functions (such as FxHash) produce a usize result
// instead, which means that the top 32 bits are 0 on 32-bit platforms.
// So we use MIN_HASH_LEN constant to handle this.
let top7 = hash >> (MIN_HASH_LEN * 8 - 7);
(top7 & 0x7f) as u8 // truncation
}
/// Probe sequence based on triangular numbers, which is guaranteed (since our
/// table size is a power of two) to visit every group of elements exactly once.
///
/// A triangular probe has us jump by 1 more group every time. So first we
/// jump by 1 group (meaning we just continue our linear scan), then 2 groups
/// (skipping over 1 group), then 3 groups (skipping over 2 groups), and so on.
///
/// Proof that the probe will visit every group in the table:
/// <https://fgiesen.wordpress.com/2015/02/22/triangular-numbers-mod-2n/>
struct ProbeSeq {
pos: usize,
stride: usize,
}
impl ProbeSeq {
#[inline]
fn move_next(&mut self, bucket_mask: usize) {
// We should have found an empty bucket by now and ended the probe.
debug_assert!(
self.stride <= bucket_mask,
"Went past end of probe sequence"
);
self.stride += Group::WIDTH;
self.pos += self.stride;
self.pos &= bucket_mask;
}
}
/// Returns the number of buckets needed to hold the given number of items,
/// taking the maximum load factor into account.
///
/// Returns `None` if an overflow occurs.
// Workaround for emscripten bug emscripten-core/emscripten-fastcomp#258
#[cfg_attr(target_os = "emscripten", inline(never))]
#[cfg_attr(not(target_os = "emscripten"), inline)]
fn capacity_to_buckets(cap: usize) -> Option<usize> {
debug_assert_ne!(cap, 0);
// For small tables we require at least 1 empty bucket so that lookups are
// guaranteed to terminate if an element doesn't exist in the table.
if cap < 8 {
// We don't bother with a table size of 2 buckets since that can only
// hold a single element. Instead we skip directly to a 4 bucket table
// which can hold 3 elements.
return Some(if cap < 4 { 4 } else { 8 });
}
// Otherwise require 1/8 buckets to be empty (87.5% load)
//
// Be careful when modifying this, calculate_layout relies on the
// overflow check here.
let adjusted_cap = cap.checked_mul(8)? / 7;
// Any overflows will have been caught by the checked_mul. Also, any
// rounding errors from the division above will be cleaned up by
// next_power_of_two (which can't overflow because of the previous division).
Some(adjusted_cap.next_power_of_two())
}
/// Returns the maximum effective capacity for the given bucket mask, taking
/// the maximum load factor into account.
#[inline]
fn bucket_mask_to_capacity(bucket_mask: usize) -> usize {
if bucket_mask < 8 {
// For tables with 1/2/4/8 buckets, we always reserve one empty slot.
// Keep in mind that the bucket mask is one less than the bucket count.
bucket_mask
} else {
// For larger tables we reserve 12.5% of the slots as empty.
((bucket_mask + 1) / 8) * 7
}
}
/// Helper which allows the max calculation for ctrl_align to be statically computed for each T
/// while keeping the rest of `calculate_layout_for` independent of `T`
#[derive(Copy, Clone)]
struct TableLayout {
size: usize,
ctrl_align: usize,
}
impl TableLayout {
#[inline]
const fn new<T>() -> Self {
let layout = Layout::new::<T>();
Self {
size: layout.size(),
ctrl_align: if layout.align() > Group::WIDTH {
layout.align()
} else {
Group::WIDTH
},
}
}
#[inline]
fn calculate_layout_for(self, buckets: usize) -> Option<(Layout, usize)> {
debug_assert!(buckets.is_power_of_two());
let TableLayout { size, ctrl_align } = self;
// Manual layout calculation since Layout methods are not yet stable.
let ctrl_offset =
size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1);
let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?;
// We need an additional check to ensure that the allocation doesn't
// exceed `isize::MAX` (https://github.com/rust-lang/rust/pull/95295).
if len > isize::MAX as usize - (ctrl_align - 1) {
return None;
}
Some((
unsafe { Layout::from_size_align_unchecked(len, ctrl_align) },
ctrl_offset,
))
}
}
/// A reference to an empty bucket into which an can be inserted.
pub struct InsertSlot {
index: usize,
}
/// A reference to a hash table bucket containing a `T`.
///
/// This is usually just a pointer to the element itself. However if the element
/// is a ZST, then we instead track the index of the element in the table so
/// that `erase` works properly.
pub struct Bucket<T> {
// Actually it is pointer to next element than element itself
// this is needed to maintain pointer arithmetic invariants
// keeping direct pointer to element introduces difficulty.
// Using `NonNull` for variance and niche layout
ptr: NonNull<T>,
}
// This Send impl is needed for rayon support. This is safe since Bucket is
// never exposed in a public API.
unsafe impl<T> Send for Bucket<T> {}
impl<T> Clone for Bucket<T> {
#[inline]
fn clone(&self) -> Self {
Self { ptr: self.ptr }
}
}
impl<T> Bucket<T> {
/// Creates a [`Bucket`] that contain pointer to the data.
/// The pointer calculation is performed by calculating the
/// offset from given `base` pointer (convenience for
/// `base.as_ptr().sub(index)`).
///
/// `index` is in units of `T`; e.g., an `index` of 3 represents a pointer
/// offset of `3 * size_of::<T>()` bytes.
///
/// If the `T` is a ZST, then we instead track the index of the element
/// in the table so that `erase` works properly (return
/// `NonNull::new_unchecked((index + 1) as *mut T)`)
///
/// # Safety
///
/// If `mem::size_of::<T>() != 0`, then the safety rules are directly derived
/// from the safety rules for [`<*mut T>::sub`] method of `*mut T` and the safety
/// rules of [`NonNull::new_unchecked`] function.
///
/// Thus, in order to uphold the safety contracts for the [`<*mut T>::sub`] method
/// and [`NonNull::new_unchecked`] function, as well as for the correct
/// logic of the work of this crate, the following rules are necessary and
/// sufficient:
///
/// * the `base` pointer must not be `dangling` and must points to the
/// end of the first `value element` from the `data part` of the table, i.e.
/// must be the pointer that returned by [`RawTable::data_end`] or by
/// [`RawTableInner::data_end<T>`];
///
/// * `index` must not be greater than `RawTableInner.bucket_mask`, i.e.
/// `index <= RawTableInner.bucket_mask` or, in other words, `(index + 1)`
/// must be no greater than the number returned by the function
/// [`RawTable::buckets`] or [`RawTableInner::buckets`].
///
/// If `mem::size_of::<T>() == 0`, then the only requirement is that the
/// `index` must not be greater than `RawTableInner.bucket_mask`, i.e.
/// `index <= RawTableInner.bucket_mask` or, in other words, `(index + 1)`
/// must be no greater than the number returned by the function
/// [`RawTable::buckets`] or [`RawTableInner::buckets`].
///
/// [`Bucket`]: crate::raw::Bucket
/// [`<*mut T>::sub`]: https://doc.rust-lang.org/core/primitive.pointer.html#method.sub-1
/// [`NonNull::new_unchecked`]: https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.new_unchecked
/// [`RawTable::data_end`]: crate::raw::RawTable::data_end
/// [`RawTableInner::data_end<T>`]: RawTableInner::data_end<T>
/// [`RawTable::buckets`]: crate::raw::RawTable::buckets
/// [`RawTableInner::buckets`]: RawTableInner::buckets
#[inline]
unsafe fn from_base_index(base: NonNull<T>, index: usize) -> Self {
// If mem::size_of::<T>() != 0 then return a pointer to an `element` in
// the data part of the table (we start counting from "0", so that
// in the expression T[last], the "last" index actually one less than the
// "buckets" number in the table, i.e. "last = RawTableInner.bucket_mask"):
//
// `from_base_index(base, 1).as_ptr()` returns a pointer that
// points here in the data part of the table
// (to the start of T1)
// |
// | `base: NonNull<T>` must point here
// | (to the end of T0 or to the start of C0)
// v v
// [Padding], Tlast, ..., |T1|, T0, |C0, C1, ..., Clast
// ^
// `from_base_index(base, 1)` returns a pointer
// that points here in the data part of the table
// (to the end of T1)
//
// where: T0...Tlast - our stored data; C0...Clast - control bytes
// or metadata for data.
let ptr = if T::IS_ZERO_SIZED {
// won't overflow because index must be less than length (bucket_mask)
// and bucket_mask is guaranteed to be less than `isize::MAX`
// (see TableLayout::calculate_layout_for method)
invalid_mut(index + 1)
} else {
base.as_ptr().sub(index)
};
Self {
ptr: NonNull::new_unchecked(ptr),
}
}
/// Calculates the index of a [`Bucket`] as distance between two pointers
/// (convenience for `base.as_ptr().offset_from(self.ptr.as_ptr()) as usize`).
/// The returned value is in units of T: the distance in bytes divided by
/// [`core::mem::size_of::<T>()`].
///
/// If the `T` is a ZST, then we return the index of the element in
/// the table so that `erase` works properly (return `self.ptr.as_ptr() as usize - 1`).
///
/// This function is the inverse of [`from_base_index`].
///
/// # Safety
///
/// If `mem::size_of::<T>() != 0`, then the safety rules are directly derived
/// from the safety rules for [`<*const T>::offset_from`] method of `*const T`.
///
/// Thus, in order to uphold the safety contracts for [`<*const T>::offset_from`]
/// method, as well as for the correct logic of the work of this crate, the
/// following rules are necessary and sufficient:
///
/// * `base` contained pointer must not be `dangling` and must point to the
/// end of the first `element` from the `data part` of the table, i.e.
/// must be a pointer that returns by [`RawTable::data_end`] or by
/// [`RawTableInner::data_end<T>`];
///
/// * `self` also must not contain dangling pointer;
///
/// * both `self` and `base` must be created from the same [`RawTable`]
/// (or [`RawTableInner`]).
///
/// If `mem::size_of::<T>() == 0`, this function is always safe.
///
/// [`Bucket`]: crate::raw::Bucket
/// [`from_base_index`]: crate::raw::Bucket::from_base_index
/// [`RawTable::data_end`]: crate::raw::RawTable::data_end
/// [`RawTableInner::data_end<T>`]: RawTableInner::data_end<T>
/// [`RawTable`]: crate::raw::RawTable
/// [`RawTableInner`]: RawTableInner
/// [`<*const T>::offset_from`]: https://doc.rust-lang.org/nightly/core/primitive.pointer.html#method.offset_from
#[inline]
unsafe fn to_base_index(&self, base: NonNull<T>) -> usize {
// If mem::size_of::<T>() != 0 then return an index under which we used to store the
// `element` in the data part of the table (we start counting from "0", so
// that in the expression T[last], the "last" index actually is one less than the
// "buckets" number in the table, i.e. "last = RawTableInner.bucket_mask").
// For example for 5th element in table calculation is performed like this:
//
// mem::size_of::<T>()
// |
// | `self = from_base_index(base, 5)` that returns pointer
// | that points here in tha data part of the table
// | (to the end of T5)
// | | `base: NonNull<T>` must point here
// v | (to the end of T0 or to the start of C0)
// /???\ v v
// [Padding], Tlast, ..., |T10|, ..., T5|, T4, T3, T2, T1, T0, |C0, C1, C2, C3, C4, C5, ..., C10, ..., Clast
// \__________ __________/
// \/
// `bucket.to_base_index(base)` = 5
// (base.as_ptr() as usize - self.ptr.as_ptr() as usize) / mem::size_of::<T>()
//
// where: T0...Tlast - our stored data; C0...Clast - control bytes or metadata for data.
if T::IS_ZERO_SIZED {
// this can not be UB
self.ptr.as_ptr() as usize - 1
} else {
offset_from(base.as_ptr(), self.ptr.as_ptr())
}
}
/// Acquires the underlying raw pointer `*mut T` to `data`.
///
/// # Note
///
/// If `T` is not [`Copy`], do not use `*mut T` methods that can cause calling the
/// destructor of `T` (for example the [`<*mut T>::drop_in_place`] method), because
/// for properly dropping the data we also need to clear `data` control bytes. If we
/// drop data, but do not clear `data control byte` it leads to double drop when
/// [`RawTable`] goes out of scope.
///
/// If you modify an already initialized `value`, so [`Hash`] and [`Eq`] on the new
/// `T` value and its borrowed form *must* match those for the old `T` value, as the map
/// will not re-evaluate where the new value should go, meaning the value may become
/// "lost" if their location does not reflect their state.
///
/// [`RawTable`]: crate::raw::RawTable
/// [`<*mut T>::drop_in_place`]: https://doc.rust-lang.org/core/primitive.pointer.html#method.drop_in_place
/// [`Hash`]: https://doc.rust-lang.org/core/hash/trait.Hash.html
/// [`Eq`]: https://doc.rust-lang.org/core/cmp/trait.Eq.html
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "raw")]
/// # fn test() {
/// use core::hash::{BuildHasher, Hash};
/// use hashbrown::raw::{Bucket, RawTable};
///
/// type NewHashBuilder = core::hash::BuildHasherDefault<ahash::AHasher>;
///
/// fn make_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
/// use core::hash::Hasher;
/// let mut state = hash_builder.build_hasher();
/// key.hash(&mut state);
/// state.finish()
/// }
///
/// let hash_builder = NewHashBuilder::default();
/// let mut table = RawTable::new();
///
/// let value = ("a", 100);
/// let hash = make_hash(&hash_builder, &value.0);
///
/// table.insert(hash, value.clone(), |val| make_hash(&hash_builder, &val.0));
///
/// let bucket: Bucket<(&str, i32)> = table.find(hash, |(k1, _)| k1 == &value.0).unwrap();
///
/// assert_eq!(unsafe { &*bucket.as_ptr() }, &("a", 100));
/// # }
/// # fn main() {
/// # #[cfg(feature = "raw")]
/// # test()
/// # }
/// ```
#[inline]
pub fn as_ptr(&self) -> *mut T {
if T::IS_ZERO_SIZED {
// Just return an arbitrary ZST pointer which is properly aligned
// invalid pointer is good enough for ZST
invalid_mut(mem::align_of::<T>())
} else {
unsafe { self.ptr.as_ptr().sub(1) }
}
}
/// Create a new [`Bucket`] that is offset from the `self` by the given
/// `offset`. The pointer calculation is performed by calculating the
/// offset from `self` pointer (convenience for `self.ptr.as_ptr().sub(offset)`).
/// This function is used for iterators.
///
/// `offset` is in units of `T`; e.g., a `offset` of 3 represents a pointer
/// offset of `3 * size_of::<T>()` bytes.
///
/// # Safety
///
/// If `mem::size_of::<T>() != 0`, then the safety rules are directly derived
/// from the safety rules for [`<*mut T>::sub`] method of `*mut T` and safety
/// rules of [`NonNull::new_unchecked`] function.
///
/// Thus, in order to uphold the safety contracts for [`<*mut T>::sub`] method
/// and [`NonNull::new_unchecked`] function, as well as for the correct
/// logic of the work of this crate, the following rules are necessary and
/// sufficient:
///
/// * `self` contained pointer must not be `dangling`;
///
/// * `self.to_base_index() + ofset` must not be greater than `RawTableInner.bucket_mask`,
/// i.e. `(self.to_base_index() + ofset) <= RawTableInner.bucket_mask` or, in other
/// words, `self.to_base_index() + ofset + 1` must be no greater than the number returned
/// by the function [`RawTable::buckets`] or [`RawTableInner::buckets`].
///
/// If `mem::size_of::<T>() == 0`, then the only requirement is that the
/// `self.to_base_index() + ofset` must not be greater than `RawTableInner.bucket_mask`,
/// i.e. `(self.to_base_index() + ofset) <= RawTableInner.bucket_mask` or, in other words,
/// `self.to_base_index() + ofset + 1` must be no greater than the number returned by the
/// function [`RawTable::buckets`] or [`RawTableInner::buckets`].
///
/// [`Bucket`]: crate::raw::Bucket
/// [`<*mut T>::sub`]: https://doc.rust-lang.org/core/primitive.pointer.html#method.sub-1
/// [`NonNull::new_unchecked`]: https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html#method.new_unchecked
/// [`RawTable::buckets`]: crate::raw::RawTable::buckets
/// [`RawTableInner::buckets`]: RawTableInner::buckets
#[inline]
unsafe fn next_n(&self, offset: usize) -> Self {
let ptr = if T::IS_ZERO_SIZED {
// invalid pointer is good enough for ZST
invalid_mut(self.ptr.as_ptr() as usize + offset)
} else {
self.ptr.as_ptr().sub(offset)
};
Self {
ptr: NonNull::new_unchecked(ptr),
}
}
/// Executes the destructor (if any) of the pointed-to `data`.
///
/// # Safety
///
/// See [`ptr::drop_in_place`] for safety concerns.
///
/// You should use [`RawTable::erase`] instead of this function,
/// or be careful with calling this function directly, because for
/// properly dropping the data we need also clear `data` control bytes.
/// If we drop data, but do not erase `data control byte` it leads to
/// double drop when [`RawTable`] goes out of scope.
///
/// [`ptr::drop_in_place`]: https://doc.rust-lang.org/core/ptr/fn.drop_in_place.html
/// [`RawTable`]: crate::raw::RawTable
/// [`RawTable::erase`]: crate::raw::RawTable::erase
#[cfg_attr(feature = "inline-more", inline)]
pub(crate) unsafe fn drop(&self) {
self.as_ptr().drop_in_place();
}
/// Reads the `value` from `self` without moving it. This leaves the
/// memory in `self` unchanged.
///
/// # Safety
///
/// See [`ptr::read`] for safety concerns.
///
/// You should use [`RawTable::remove`] instead of this function,
/// or be careful with calling this function directly, because compiler
/// calls its destructor when readed `value` goes out of scope. It
/// can cause double dropping when [`RawTable`] goes out of scope,
/// because of not erased `data control byte`.
///
/// [`ptr::read`]: https://doc.rust-lang.org/core/ptr/fn.read.html
/// [`RawTable`]: crate::raw::RawTable
/// [`RawTable::remove`]: crate::raw::RawTable::remove
#[inline]
pub(crate) unsafe fn read(&self) -> T {
self.as_ptr().read()
}
/// Overwrites a memory location with the given `value` without reading
/// or dropping the old value (like [`ptr::write`] function).
///
/// # Safety
///
/// See [`ptr::write`] for safety concerns.
///
/// # Note
///
/// [`Hash`] and [`Eq`] on the new `T` value and its borrowed form *must* match
/// those for the old `T` value, as the map will not re-evaluate where the new
/// value should go, meaning the value may become "lost" if their location
/// does not reflect their state.
///
/// [`ptr::write`]: https://doc.rust-lang.org/core/ptr/fn.write.html
/// [`Hash`]: https://doc.rust-lang.org/core/hash/trait.Hash.html
/// [`Eq`]: https://doc.rust-lang.org/core/cmp/trait.Eq.html
#[inline]
pub(crate) unsafe fn write(&self, val: T) {
self.as_ptr().write(val);
}
/// Returns a shared immutable reference to the `value`.
///
/// # Safety
///
/// See [`NonNull::as_ref`] for safety concerns.
///
/// [`NonNull::as_ref`]: https://doc.rust-lang.org/core/ptr/struct.NonNull.html#method.as_ref
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "raw")]
/// # fn test() {
/// use core::hash::{BuildHasher, Hash};
/// use hashbrown::raw::{Bucket, RawTable};
///
/// type NewHashBuilder = core::hash::BuildHasherDefault<ahash::AHasher>;
///
/// fn make_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
/// use core::hash::Hasher;
/// let mut state = hash_builder.build_hasher();
/// key.hash(&mut state);
/// state.finish()
/// }
///
/// let hash_builder = NewHashBuilder::default();
/// let mut table = RawTable::new();
///
/// let value: (&str, String) = ("A pony", "is a small horse".to_owned());
/// let hash = make_hash(&hash_builder, &value.0);
///
/// table.insert(hash, value.clone(), |val| make_hash(&hash_builder, &val.0));
///
/// let bucket: Bucket<(&str, String)> = table.find(hash, |(k, _)| k == &value.0).unwrap();
///
/// assert_eq!(
/// unsafe { bucket.as_ref() },
/// &("A pony", "is a small horse".to_owned())
/// );
/// # }
/// # fn main() {
/// # #[cfg(feature = "raw")]
/// # test()
/// # }
/// ```
#[inline]
pub unsafe fn as_ref<'a>(&self) -> &'a T {
&*self.as_ptr()
}
/// Returns a unique mutable reference to the `value`.
///
/// # Safety
///
/// See [`NonNull::as_mut`] for safety concerns.
///
/// # Note
///
/// [`Hash`] and [`Eq`] on the new `T` value and its borrowed form *must* match
/// those for the old `T` value, as the map will not re-evaluate where the new
/// value should go, meaning the value may become "lost" if their location
/// does not reflect their state.
///
/// [`NonNull::as_mut`]: https://doc.rust-lang.org/core/ptr/struct.NonNull.html#method.as_mut
/// [`Hash`]: https://doc.rust-lang.org/core/hash/trait.Hash.html
/// [`Eq`]: https://doc.rust-lang.org/core/cmp/trait.Eq.html
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "raw")]
/// # fn test() {
/// use core::hash::{BuildHasher, Hash};
/// use hashbrown::raw::{Bucket, RawTable};
///
/// type NewHashBuilder = core::hash::BuildHasherDefault<ahash::AHasher>;
///
/// fn make_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
/// use core::hash::Hasher;
/// let mut state = hash_builder.build_hasher();
/// key.hash(&mut state);
/// state.finish()
/// }
///
/// let hash_builder = NewHashBuilder::default();
/// let mut table = RawTable::new();
///
/// let value: (&str, String) = ("A pony", "is a small horse".to_owned());
/// let hash = make_hash(&hash_builder, &value.0);
///
/// table.insert(hash, value.clone(), |val| make_hash(&hash_builder, &val.0));
///
/// let bucket: Bucket<(&str, String)> = table.find(hash, |(k, _)| k == &value.0).unwrap();
///
/// unsafe {
/// bucket
/// .as_mut()
/// .1
/// .push_str(" less than 147 cm at the withers")
/// };
/// assert_eq!(
/// unsafe { bucket.as_ref() },
/// &(
/// "A pony",
/// "is a small horse less than 147 cm at the withers".to_owned()
/// )
/// );
/// # }
/// # fn main() {
/// # #[cfg(feature = "raw")]
/// # test()
/// # }
/// ```
#[inline]
pub unsafe fn as_mut<'a>(&self) -> &'a mut T {
&mut *self.as_ptr()
}
/// Copies `size_of<T>` bytes from `other` to `self`. The source
/// and destination may *not* overlap.
///
/// # Safety
///
/// See [`ptr::copy_nonoverlapping`] for safety concerns.
///
/// Like [`read`], `copy_nonoverlapping` creates a bitwise copy of `T`, regardless of
/// whether `T` is [`Copy`]. If `T` is not [`Copy`], using *both* the values
/// in the region beginning at `*self` and the region beginning at `*other` can
/// [violate memory safety].
///
/// # Note
///
/// [`Hash`] and [`Eq`] on the new `T` value and its borrowed form *must* match
/// those for the old `T` value, as the map will not re-evaluate where the new
/// value should go, meaning the value may become "lost" if their location
/// does not reflect their state.
///
/// [`ptr::copy_nonoverlapping`]: https://doc.rust-lang.org/core/ptr/fn.copy_nonoverlapping.html
/// [`read`]: https://doc.rust-lang.org/core/ptr/fn.read.html
/// [violate memory safety]: https://doc.rust-lang.org/std/ptr/fn.read.html#ownership-of-the-returned-value
/// [`Hash`]: https://doc.rust-lang.org/core/hash/trait.Hash.html
/// [`Eq`]: https://doc.rust-lang.org/core/cmp/trait.Eq.html
#[cfg(feature = "raw")]
#[inline]
pub unsafe fn copy_from_nonoverlapping(&self, other: &Self) {
self.as_ptr().copy_from_nonoverlapping(other.as_ptr(), 1);
}
}
/// A raw hash table with an unsafe API.
pub struct RawTable<T, A: Allocator = Global> {
table: RawTableInner,
alloc: A,
// Tell dropck that we own instances of T.
marker: PhantomData<T>,
}
/// Non-generic part of `RawTable` which allows functions to be instantiated only once regardless
/// of how many different key-value types are used.
struct RawTableInner {
// Mask to get an index from a hash value. The value is one less than the
// number of buckets in the table.
bucket_mask: usize,
// [Padding], T1, T2, ..., Tlast, C1, C2, ...
// ^ points here
ctrl: NonNull<u8>,
// Number of elements that can be inserted before we need to grow the table
growth_left: usize,
// Number of elements in the table, only really used by len()
items: usize,
}
impl<T> RawTable<T, Global> {
/// Creates a new empty hash table without allocating any memory.
///
/// In effect this returns a table with exactly 1 bucket. However we can
/// leave the data pointer dangling since that bucket is never written to
/// due to our load factor forcing us to always have at least 1 free bucket.
#[inline]
pub const fn new() -> Self {
Self {
table: RawTableInner::NEW,
alloc: Global,
marker: PhantomData,
}
}
/// Attempts to allocate a new hash table with at least enough capacity
/// for inserting the given number of elements without reallocating.
#[cfg(feature = "raw")]
pub fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError> {
Self::try_with_capacity_in(capacity, Global)
}
/// Allocates a new hash table with at least enough capacity for inserting
/// the given number of elements without reallocating.
pub fn with_capacity(capacity: usize) -> Self {
Self::with_capacity_in(capacity, Global)
}
}
impl<T, A: Allocator> RawTable<T, A> {
const TABLE_LAYOUT: TableLayout = TableLayout::new::<T>();
/// Creates a new empty hash table without allocating any memory, using the
/// given allocator.
///
/// In effect this returns a table with exactly 1 bucket. However we can
/// leave the data pointer dangling since that bucket is never written to
/// due to our load factor forcing us to always have at least 1 free bucket.
#[inline]
pub const fn new_in(alloc: A) -> Self {
Self {
table: RawTableInner::NEW,
alloc,
marker: PhantomData,
}
}
/// Allocates a new hash table with the given number of buckets.
///
/// The control bytes are left uninitialized.
#[cfg_attr(feature = "inline-more", inline)]
unsafe fn new_uninitialized(
alloc: A,
buckets: usize,
fallibility: Fallibility,
) -> Result<Self, TryReserveError> {
debug_assert!(buckets.is_power_of_two());
Ok(Self {
table: RawTableInner::new_uninitialized(
&alloc,
Self::TABLE_LAYOUT,
buckets,
fallibility,
)?,
alloc,
marker: PhantomData,
})
}
/// Attempts to allocate a new hash table using the given allocator, with at least enough
/// capacity for inserting the given number of elements without reallocating.
#[cfg(feature = "raw")]
pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, TryReserveError> {
Ok(Self {
table: RawTableInner::fallible_with_capacity(
&alloc,
Self::TABLE_LAYOUT,
capacity,
Fallibility::Fallible,
)?,
alloc,
marker: PhantomData,
})
}
/// Allocates a new hash table using the given allocator, with at least enough capacity for
/// inserting the given number of elements without reallocating.
pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
Self {
table: RawTableInner::with_capacity(&alloc, Self::TABLE_LAYOUT, capacity),
alloc,
marker: PhantomData,
}
}
/// Returns a reference to the underlying allocator.
#[inline]
pub fn allocator(&self) -> &A {
&self.alloc
}
/// Returns pointer to one past last `data` element in the table as viewed from
/// the start point of the allocation.
///
/// The caller must ensure that the `RawTable` outlives the returned [`NonNull<T>`],
/// otherwise using it may result in [`undefined behavior`].
///
/// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
#[inline]
pub fn data_end(&self) -> NonNull<T> {
// `self.table.ctrl.cast()` returns pointer that
// points here (to the end of `T0`)
// ∨
// [Pad], T_n, ..., T1, T0, |CT0, CT1, ..., CT_n|, CTa_0, CTa_1, ..., CTa_m
// \________ ________/
// \/
// `n = buckets - 1`, i.e. `RawTable::buckets() - 1`
//
// where: T0...T_n - our stored data;
// CT0...CT_n - control bytes or metadata for `data`.
// CTa_0...CTa_m - additional control bytes, where `m = Group::WIDTH - 1` (so that the search
// with loading `Group` bytes from the heap works properly, even if the result
// of `h1(hash) & self.bucket_mask` is equal to `self.bucket_mask`). See also
// `RawTableInner::set_ctrl` function.
//
// P.S. `h1(hash) & self.bucket_mask` is the same as `hash as usize % self.buckets()` because the number
// of buckets is a power of two, and `self.bucket_mask = self.buckets() - 1`.
self.table.ctrl.cast()
}
/// Returns pointer to start of data table.
#[inline]
#[cfg(any(feature = "raw", feature = "nightly"))]
pub unsafe fn data_start(&self) -> NonNull<T> {
NonNull::new_unchecked(self.data_end().as_ptr().wrapping_sub(self.buckets()))
}
/// Return the information about memory allocated by the table.
///
/// `RawTable` allocates single memory block to store both data and metadata.
/// This function returns allocation size and alignment and the beginning of the area.
/// These are the arguments which will be passed to `dealloc` when the table is dropped.
///
/// This function might be useful for memory profiling.
#[inline]
#[cfg(feature = "raw")]
pub fn allocation_info(&self) -> (NonNull<u8>, Layout) {
// SAFETY: We use the same `table_layout` that was used to allocate
// this table.
unsafe { self.table.allocation_info_or_zero(Self::TABLE_LAYOUT) }
}
/// Returns the index of a bucket from a `Bucket`.
#[inline]
pub unsafe fn bucket_index(&self, bucket: &Bucket<T>) -> usize {
bucket.to_base_index(self.data_end())
}
/// Returns a pointer to an element in the table.
///
/// The caller must ensure that the `RawTable` outlives the returned [`Bucket<T>`],
/// otherwise using it may result in [`undefined behavior`].
///
/// # Safety
///
/// If `mem::size_of::<T>() != 0`, then the caller of this function must observe the
/// following safety rules:
///
/// * The table must already be allocated;
///
/// * The `index` must not be greater than the number returned by the [`RawTable::buckets`]
/// function, i.e. `(index + 1) <= self.buckets()`.
///
/// It is safe to call this function with index of zero (`index == 0`) on a table that has
/// not been allocated, but using the returned [`Bucket`] results in [`undefined behavior`].
///
/// If `mem::size_of::<T>() == 0`, then the only requirement is that the `index` must
/// not be greater than the number returned by the [`RawTable::buckets`] function, i.e.
/// `(index + 1) <= self.buckets()`.
///
/// [`RawTable::buckets`]: RawTable::buckets
/// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
#[inline]
pub unsafe fn bucket(&self, index: usize) -> Bucket<T> {
// If mem::size_of::<T>() != 0 then return a pointer to the `element` in the `data part` of the table
// (we start counting from "0", so that in the expression T[n], the "n" index actually one less than
// the "buckets" number of our `RawTable`, i.e. "n = RawTable::buckets() - 1"):
//
// `table.bucket(3).as_ptr()` returns a pointer that points here in the `data`