Encapsulate probe offset, wrap, and distance in ProbeCapacity and plumb probe offsets through resize helpers. Turn ProbeCapacity into a class encapsulating H1ToOffset, Wrap, and Distance (still implemented with power-of-two bitmasks), and construct probe_seq from an initial probe offset via probe_from_offset rather than re-masking raw hashes inside probe_seq. Rename find_first_non_full_from_h1 to find_first_non_full_from_offset, store new_offset instead of h1 in ProbedItemImpl, and pass initial probe offsets to TransferSlotToNewPosition so probing and resize callers no longer assume power-of-two bitmasking directly. Motivation: preparation for non-power-of-2 capacities. No behavior change. PiperOrigin-RevId: 1033784185
diff --git a/absl/container/internal/raw_hash_set.cc b/absl/container/internal/raw_hash_set.cc index bbd769e..99fb0ee 100644 --- a/absl/container/internal/raw_hash_set.cc +++ b/absl/container/internal/raw_hash_set.cc
@@ -98,8 +98,8 @@ // `min(1, RehashProbabilityConstant() / capacity())`. In order to do this, // we probe based on a random hash and see if the offset is less than // RehashProbabilityConstant(). - return probe(ProbeCapacity{capacity}, absl::HashOf(RandomSeed())) - .offset() < RehashProbabilityConstant(); + return probe(ProbeCapacity(capacity), absl::HashOf(RandomSeed())).offset() < + RehashProbabilityConstant(); } // Returns the offset of the new element after resize from capacity 1 to 3. @@ -173,9 +173,9 @@ } } -FindInfo find_first_non_full_from_h1(size_t cap, const ctrl_t* ctrl, - size_t h1) { - auto seq = probe_h1(ProbeCapacity{cap}, h1); +FindInfo find_first_non_full_from_offset(size_t cap, const ctrl_t* ctrl, + size_t offset) { + auto seq = probe_from_offset(ProbeCapacity(cap), offset); if (IsEmptyOrDeleted(ctrl[seq.offset()])) { return {seq.offset(), /*probe_length=*/0}; } @@ -191,7 +191,8 @@ // NOTE: this function must work with tables having both empty and deleted // slots in the same group. Such tables appear during `erase()`. FindInfo find_first_non_full(size_t cap, const ctrl_t* ctrl, size_t hash) { - return find_first_non_full_from_h1(cap, ctrl, H1(hash)); + return find_first_non_full_from_offset( + cap, ctrl, ProbeCapacity(cap).H1ToOffset(H1(hash))); } // Same as `find_first_non_full`, but returns the mask corresponding to the @@ -645,6 +646,7 @@ auto hasher = policy.hash_slot; auto transfer_n = policy.transfer_n; const size_t slot_size = policy.slot_size; + const ProbeCapacity probe_capacity(capacity); size_t total_probe_length = 0; void* slot_ptr = SlotAddress(slot_array, 0, slot_size); @@ -670,10 +672,10 @@ // Verify if the old and new i fall within the same group wrt the hash. // If they do, we don't need to move the object as it falls already in the // best probe we can. - const size_t probe_offset = probe(ProbeCapacity{capacity}, hash).offset(); + const size_t probe_offset = probe_capacity.H1ToOffset(H1(hash)); const h2_t h2 = H2(hash); - const auto probe_index = [probe_offset, capacity](size_t pos) { - return ((pos - probe_offset) & capacity) / Group::kWidth; + const auto probe_index = [probe_offset, probe_capacity](size_t pos) { + return probe_capacity.Distance(probe_offset, pos) / Group::kWidth; }; // Element doesn't move. @@ -729,7 +731,8 @@ if (is_single_group(capacity)) { return true; } - const size_t index_before = (index - Group::kWidth) & capacity; + const size_t index_before = + ProbeCapacity(capacity).Distance(Group::kWidth, index); const auto empty_after = Group(ctrl + index).MaskEmpty(); const auto empty_before = Group(ctrl + index_before).MaskEmpty(); @@ -1054,21 +1057,20 @@ namespace { -// Finds the first non-full slot in the probe sequence of `h1` in the large -// table with control bytes `new_ctrl`, marks it as full with `h2` and transfers -// `src_slot` into it. `new_ctrl` is passed explicitly rather than read from `c` -// so that the function can be used while `c` still stores SOO data in place of -// the control pointer. -// This function is shared by the cold paths that move elements to new -// positions (growth of probed elements, rehash and reserve). -// Returns the probe length. +// Finds the first non-full slot in the probe sequence starting at initial +// probe offset `offset` in the large table with control bytes `new_ctrl`, marks +// it as full with `h2` and transfers `src_slot` into it. `new_ctrl` is passed +// explicitly rather than read from `c` so that the function can be used while +// `c` still stores SOO data in place of the control pointer. This function is +// shared by the cold paths that move elements to new positions (growth of +// probed elements, rehash and reserve). Returns the probe length. ABSL_ATTRIBUTE_NOINLINE size_t TransferSlotToNewPosition( CommonFields& c, const PolicyFunctions& __restrict policy, ctrl_t* new_ctrl, - void* src_slot, size_t h1, h2_t h2) { + void* src_slot, size_t offset, h2_t h2) { const size_t new_capacity = c.capacity(); ABSL_SWISSTABLE_ASSERT(!IsSmallCapacity(new_capacity)); const FindInfo target = - find_first_non_full_from_h1(new_capacity, new_ctrl, h1); + find_first_non_full_from_offset(new_capacity, new_ctrl, offset); ABSL_SWISSTABLE_ASSERT(IsEmptyOrDeleted(new_ctrl[target.offset])); SetCtrlNoSanitizeImpl(new_capacity, new_ctrl, target.offset, static_cast<ctrl_t>(h2)); @@ -1104,8 +1106,9 @@ return 0; } const size_t hash = policy.hash_slot(hash_fn, slot, seed); - return TransferSlotToNewPosition(common, policy, new_ctrl, slot, H1(hash), - H2(hash)); + return TransferSlotToNewPosition( + common, policy, new_ctrl, slot, + ProbeCapacity(new_capacity).H1ToOffset(H1(hash)), H2(hash)); }; if (IsSmallCapacity(old_capacity)) { if (common.size() == 1) insert_slot(old_slots); @@ -1181,9 +1184,10 @@ ABSL_ATTRIBUTE_COLD ABSL_ATTRIBUTE_NOINLINE void* ReportInsertMissToInfozAndGetSlot(CommonFields& common, size_t slot_size, size_t hash, size_t target) { - const size_t cap = common.capacity(); - auto seq = probe(ProbeCapacity{cap}, hash); - while (((target - seq.offset()) & cap) >= Group::kWidth) { + const ProbeCapacity probe_capacity(common.capacity_impl()); + const size_t cap = probe_capacity.capacity(); + auto seq = probe(probe_capacity, hash); + while (probe_capacity.Distance(seq.offset(), target) >= Group::kWidth) { seq.next(); } common.infoz().RecordInsertMiss(hash, seq.index()); @@ -1551,7 +1555,7 @@ ABSL_SWISSTABLE_ASSERT(old_index < c.capacity() / 2); total_probe_length += TransferSlotToNewPosition( c, policy, new_ctrl, SlotAddress(old_slots, old_index, slot_size), - static_cast<size_t>(start->h1), static_cast<h2_t>(start->h2)); + static_cast<size_t>(start->new_offset), static_cast<h2_t>(start->h2)); } return total_probe_length; } @@ -1580,7 +1584,8 @@ void* src_slot = SlotAddress(old_slots, old_index, slot_size); const size_t hash = hash_slot(hash_fn, src_slot, seed); total_probe_length += TransferSlotToNewPosition( - c, policy, c.control(), src_slot, H1(hash), H2(hash)); + c, policy, c.control(), src_slot, + ProbeCapacity(c.capacity_impl()).H1ToOffset(H1(hash)), H2(hash)); } return total_probe_length; } @@ -1634,24 +1639,25 @@ // Transfers item to the first probe group if possible, otherwise encodes it // into the best available location. void EncodeProbedElement(size_t hash, size_t source_offset) { - size_t h1 = H1(hash); + const size_t h1 = H1(hash); const size_t new_capacity = new_capacity_; - const size_t old_capacity = PreviousCapacity(new_capacity); - ABSL_SWISSTABLE_ASSERT(((source_offset - h1) & old_capacity) >= - Group::kWidth); + const ProbeCapacity old_pc(PreviousCapacity(new_capacity)); + const ProbeCapacity new_pc(new_capacity); + ABSL_SWISSTABLE_ASSERT( + old_pc.Distance(old_pc.H1ToOffset(h1), source_offset) >= Group::kWidth); + const size_t new_offset = new_pc.H1ToOffset(h1); // Try to insert element into the first probe group. // new_ctrl is not yet fully initialized so we can't use regular search via // find_first_non_full. // // We can search in the first probe group only if it is located in already // initialized part of the table. - if (ABSL_PREDICT_TRUE((h1 & old_capacity) < source_offset)) { + if (ABSL_PREDICT_TRUE(old_pc.H1ToOffset(h1) < source_offset)) { ctrl_t* new_ctrl = new_ctrl_; - size_t offset = h1 & new_capacity; - Group new_g(new_ctrl + offset); + Group new_g(new_ctrl + new_offset); if (auto mask = new_g.MaskNonFull(); ABSL_PREDICT_TRUE(mask)) { - size_t new_index = offset + mask.LowestBitSet(); - ABSL_SWISSTABLE_ASSERT((new_index & old_capacity) <= source_offset); + size_t new_index = new_offset + mask.LowestBitSet(); + ABSL_SWISSTABLE_ASSERT(old_pc.H1ToOffset(new_index) <= source_offset); ABSL_SWISSTABLE_ASSERT(IsEmpty(new_ctrl[new_index])); new_ctrl[new_index] = static_cast<ctrl_t>(H2(hash)); const size_t slot_size = policy_.slot_size; @@ -1663,7 +1669,7 @@ return; } } - EncodeItem(ProbedItem(H2(hash), source_offset, h1)); + EncodeItem(ProbedItem(H2(hash), source_offset, new_offset)); } // Decodes information about probed elements from all available sources. @@ -2656,10 +2662,11 @@ } PrepareInsertCommon(common); common.OverwriteEmptyAsFull(); - const size_t cap = common.capacity(); + const ProbeCapacity probe_capacity(common.capacity_impl()); + const size_t cap = probe_capacity.capacity(); ABSL_ASSUME(cap > kMaxSmallCapacity); - target_group_offset += mask_empty.LowestBitSet(); - target_group_offset &= cap; + target_group_offset = + probe_capacity.Wrap(target_group_offset + mask_empty.LowestBitSet()); const size_t slot_size = policy.slot_size; // Compute before `SetCtrl` to avoid reloading `control_`. void* res =
diff --git a/absl/container/internal/raw_hash_set.h b/absl/container/internal/raw_hash_set.h index 200e751..426a92f 100644 --- a/absl/container/internal/raw_hash_set.h +++ b/absl/container/internal/raw_hash_set.h
@@ -1913,23 +1913,48 @@ size_t probe_length; }; -struct ProbeCapacity { - size_t capacity; +// Encapsulates capacity-dependent probe indexing operations: initial probe +// offset, modular wrap, and probe distance. +class ProbeCapacity { + public: + explicit constexpr ProbeCapacity(size_t capacity) : mask_(capacity) {} + explicit constexpr ProbeCapacity(HashtableCapacity c) + : mask_(c.capacity()) {} + + constexpr size_t capacity() const { return mask_; } + + // Maps `h1` to an initial probe offset in `[0, capacity()]`. + constexpr size_t H1ToOffset(size_t h1) const { return h1 & mask_; } + + // Wraps `pos < 2 * (capacity() + 1)` into `[0, capacity()]`. + constexpr size_t Wrap(size_t pos) const { + ABSL_SWISSTABLE_ASSERT(pos < 2 * (mask_ + 1)); + return pos & mask_; + } + + // Probe distance from `from` to `pos` around the table. + constexpr size_t Distance(size_t from, size_t pos) const { + ABSL_SWISSTABLE_ASSERT(from <= mask_ && pos <= mask_); + return (pos - from) & mask_; + } + + private: + size_t mask_; }; // The state for a probe sequence. // // Currently, the sequence is a triangular progression of the form // -// p(i) := Width * (i^2 + i)/2 + hash (mod mask + 1) +// p(i) := Width * (i^2 + i)/2 + offset (mod capacity + 1) // // The use of `Width` ensures that each probe step does not overlap groups; // the sequence effectively outputs the addresses of *groups* (although not // necessarily aligned to any boundary). The `Group` machinery allows us // to check an entire group with minimal branching. // -// Wrapping around at `mask + 1` is important, but not for the obvious reason. -// As described above, the first few entries of the control byte array +// Wrapping around at `capacity + 1` is important, but not for the obvious +// reason. As described above, the first few entries of the control byte array // are mirrored at the end of the array, which `Group` will find and use // for selecting candidates. However, when those candidates' slots are // actually inspected, there are no corresponding slots for the cloned bytes, @@ -1941,42 +1966,45 @@ template <size_t Width> class probe_seq { public: - // Creates a new probe sequence using `hash` as the initial value of the - // sequence and `capacity` as the mask to apply to each value in the - // progression. - probe_seq(ProbeCapacity capacity, size_t hash) - : capacity_(capacity.capacity), offset_(hash & capacity_) {} + // Creates a new probe sequence starting at initial probe offset `offset`. + probe_seq(ProbeCapacity capacity, size_t offset) + : capacity_(capacity), offset_(offset) { + ABSL_SWISSTABLE_ASSERT(offset <= capacity.capacity()); + } // The offset within the table, i.e., the value `p(i)` above. size_t offset() const { return offset_; } - size_t offset(size_t i) const { return (offset_ + i) & capacity_; } + size_t offset(size_t i) const { return capacity_.Wrap(offset_ + i); } void next() { - ABSL_SWISSTABLE_ASSERT(next_index_ <= capacity_ && "full table!"); - offset_ += next_index_; - offset_ &= capacity_; + ABSL_SWISSTABLE_ASSERT(next_index_ <= capacity_.capacity() && + "full table!"); + offset_ = capacity_.Wrap(offset_ + next_index_); next_index_ += Width; } // 0-based probe index, a multiple of `Width`. size_t index() const { return next_index_ - Width; } private: - size_t capacity_; + ProbeCapacity capacity_; size_t offset_; // We keep track of the next index rather than the current index to get better // generated code. See e.g. https://godbolt.org/z/6jvWd135G. size_t next_index_ = Width; }; -// Begins a probing operation on `common.control`, using `hash`. -inline probe_seq<Group::kWidth> probe_h1(ProbeCapacity capacity, size_t h1) { - return probe_seq<Group::kWidth>(capacity, h1); +// Begins a probing operation on `common.control`, starting at `offset` (see +// `ProbeCapacity::H1ToOffset`) or using `hash`. +inline probe_seq<Group::kWidth> probe_from_offset(ProbeCapacity capacity, + size_t offset) { + return probe_seq<Group::kWidth>(capacity, offset); } -inline probe_seq<Group::kWidth> probe(ProbeCapacity capacity, size_t hash) { - return probe_h1(capacity, H1(hash)); +inline probe_seq<Group::kWidth> probe(ProbeCapacity capacity, + size_t hash) { + return probe_from_offset(capacity, capacity.H1ToOffset(H1(hash))); } inline probe_seq<Group::kWidth> probe(const CommonFields& common, size_t hash) { - return probe(ProbeCapacity{common.capacity()}, hash); + return probe(ProbeCapacity(common.capacity_impl()), hash); } constexpr size_t kProbedElementIndexSentinel = ~size_t{}; @@ -2825,9 +2853,10 @@ reinterpret_cast<const char*>(this) + kEqOffset); const size_t hash = hash_of<typename SlotEq::SlotKeyType, Hash, kHasherOffset>(key); - const size_t cap = common().capacity(); + const ProbeCapacity probe_capacity(common().capacity_impl()); + const size_t cap = probe_capacity.capacity(); ABSL_ASSUME(cap > kMaxSmallCapacity); - auto seq = probe(ProbeCapacity{cap}, hash); + auto seq = probe(probe_capacity, hash); const h2_t h2 = H2(hash); ctrl_t* ctrl = control<kIsDefaultAlloc>(); auto* slot_array = sized_slot_array<kSlotSize, kIsDefaultAlloc>(cap); @@ -2860,9 +2889,10 @@ const Eq& eq_ref = *reinterpret_cast<const Eq*>( reinterpret_cast<const char*>(this) + kEqOffset); const size_t hash = hash_of<SlotKeyType, Hash, kHasherOffset>(key); - const size_t cap = common().capacity(); + const ProbeCapacity probe_capacity(common().capacity_impl()); + const size_t cap = probe_capacity.capacity(); ABSL_ASSUME(cap > kMaxSmallCapacity); - auto seq = probe(ProbeCapacity{cap}, hash); + auto seq = probe(probe_capacity, hash); const h2_t h2 = H2(hash); const ctrl_t* ctrl = control<kIsDefaultAlloc>(); auto* slot_array = sized_slot_array<kSlotSize, kIsDefaultAlloc>(cap);
diff --git a/absl/container/internal/raw_hash_set_resize_impl.h b/absl/container/internal/raw_hash_set_resize_impl.h index ed48d96..1debdd0 100644 --- a/absl/container/internal/raw_hash_set_resize_impl.h +++ b/absl/container/internal/raw_hash_set_resize_impl.h
@@ -32,15 +32,15 @@ // Storage format for 4 bytes: // - 7 bits for h2 // - 12 bits for source_offset -// - 13 bits for h1 +// - 13 bits for new_offset (initial probe offset in the new table) // Storage format for 8 bytes: // - 7 bits for h2 // - 28 bits for source_offset -// - 29 bits for h1 +// - 29 bits for new_offset // Storage format for 16 bytes: // - 7 bits for h2 // - 57 bits for source_offset -// - 58 bits for h1 +// - 58 bits for new_offset template <typename IntType, size_t kTotalBits> struct ProbedItemImpl { static constexpr IntType kH2Bits = 7; @@ -48,21 +48,22 @@ static constexpr IntType kMaxOldBits = (kTotalBits - kH2Bits) / 2; static constexpr IntType kMaxOldCapacity = (IntType{1} << kMaxOldBits) - 1; - // We always have one bit more for h1. + // We always have one bit more for new_offset (< new_capacity + 1). static constexpr IntType kMaxNewBits = kMaxOldBits + 1; static constexpr IntType kMaxNewCapacity = (IntType{1} << kMaxNewBits) - 1; static_assert(kMaxNewBits + kMaxOldBits + kH2Bits == kTotalBits); ProbedItemImpl() = default; - ProbedItemImpl(uint8_t h2_arg, size_t source_offset_arg, size_t h1_arg) + ProbedItemImpl(uint8_t h2_arg, size_t source_offset_arg, + size_t new_offset_arg) : h2(h2_arg), source_offset(static_cast<IntType>(source_offset_arg)), - h1(static_cast<IntType>(h1_arg)) {} + new_offset(static_cast<IntType>(new_offset_arg)) {} IntType h2 : kH2Bits; IntType source_offset : kMaxOldBits; - IntType h1 : kMaxNewBits; + IntType new_offset : kMaxNewBits; }; using ProbedItem4Bytes = ProbedItemImpl<uint32_t, 32>;
diff --git a/absl/container/internal/raw_hash_set_resize_impl_test.cc b/absl/container/internal/raw_hash_set_resize_impl_test.cc index 5020fca..c4d881b 100644 --- a/absl/container/internal/raw_hash_set_resize_impl_test.cc +++ b/absl/container/internal/raw_hash_set_resize_impl_test.cc
@@ -27,7 +27,7 @@ namespace { constexpr size_t kSmallSourceOffset = 17; -constexpr size_t kSmallH1 = 25; +constexpr size_t kSmallNewOffset = 25; template <class Encoder> class EncoderTest : public testing::Test {}; @@ -39,10 +39,10 @@ TYPED_TEST(EncoderTest, EncodeDecodeSmall) { using ProbedItem = TypeParam; for (uint8_t h2 = 0; h2 < 128; ++h2) { - ProbedItem item(h2, kSmallSourceOffset, kSmallH1); + ProbedItem item(h2, kSmallSourceOffset, kSmallNewOffset); EXPECT_EQ(item.h2, h2); EXPECT_EQ(item.source_offset, kSmallSourceOffset); - EXPECT_EQ(item.h1 & ProbedItem::kMaxNewCapacity, kSmallH1); + EXPECT_EQ(item.new_offset & ProbedItem::kMaxNewCapacity, kSmallNewOffset); } } @@ -51,12 +51,12 @@ for (uint8_t h2 = 0; h2 < 128; ++h2) { size_t source_offset = static_cast<size_t>(std::min<uint64_t>( ProbedItem::kMaxOldCapacity, (std::numeric_limits<size_t>::max)())); - size_t h1 = static_cast<size_t>(std::min<uint64_t>( + size_t new_offset = static_cast<size_t>(std::min<uint64_t>( ProbedItem::kMaxNewCapacity, (std::numeric_limits<size_t>::max)())); - ProbedItem item(h2, source_offset, h1); + ProbedItem item(h2, source_offset, new_offset); EXPECT_EQ(item.h2, h2); EXPECT_EQ(item.source_offset, source_offset); - EXPECT_EQ(item.h1 & ProbedItem::kMaxNewCapacity, h1); + EXPECT_EQ(item.new_offset & ProbedItem::kMaxNewCapacity, new_offset); } }
diff --git a/absl/container/internal/raw_hash_set_test.cc b/absl/container/internal/raw_hash_set_test.cc index ff1c060..d3bd363 100644 --- a/absl/container/internal/raw_hash_set_test.cc +++ b/absl/container/internal/raw_hash_set_test.cc
@@ -760,8 +760,8 @@ } TEST(Util, probe_seq) { - size_t capacity = 127; - probe_seq<16> seq(ProbeCapacity{capacity}, /*hash=*/0); + const ProbeCapacity capacity(127); + probe_seq<16> seq(capacity, /*offset=*/0); auto gen = [&]() { seq.next(); return seq.offset(); @@ -770,10 +770,27 @@ offsets[0] = seq.offset(); std::generate_n(offsets.begin() + 1, 7, gen); EXPECT_THAT(offsets, ElementsAre(0, 16, 48, 96, 32, 112, 80, 64)); - seq = probe_seq<16>(ProbeCapacity{capacity}, /*hash=*/128); + seq = probe_seq<16>(capacity, capacity.H1ToOffset(H1(/*hash=*/128))); offsets[0] = seq.offset(); std::generate_n(offsets.begin() + 1, 7, gen); EXPECT_THAT(offsets, ElementsAre(0, 16, 48, 96, 32, 112, 80, 64)); + EXPECT_EQ(probe(capacity, /*hash=*/128).offset(), 0); +} + +TEST(Util, ProbeCapacity) { + for (size_t cap : {size_t{15}, size_t{31}, size_t{127}}) { + const ProbeCapacity pc{HashtableCapacity(cap)}; + EXPECT_EQ(pc.capacity(), cap); + const size_t n = cap + 1; + for (size_t pos = 0; pos < 2 * n; ++pos) { + EXPECT_EQ(pc.Wrap(pos), pos % n); + } + for (size_t from = 0; from < n; ++from) { + for (size_t pos = 0; pos < n; ++pos) { + EXPECT_EQ(pc.Distance(from, pos), (pos + n - from) % n); + } + } + } } TEST(HashtableDataTest, HashtableCapacity) {