blob: f2b1cc06d7c4bc3b1b15b12fa1bdb0770e42d968 [file] [log] [blame]
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ART_RUNTIME_BASE_HASH_SET_H_
18#define ART_RUNTIME_BASE_HASH_SET_H_
19
20#include <functional>
Vladimir Marko1f497642015-10-05 20:34:42 +010021#include <iterator>
Mathieu Chartierc2e20622014-11-03 11:41:47 -080022#include <memory>
23#include <stdint.h>
24#include <utility>
25
Mathieu Chartierd39645e2015-06-09 17:50:29 -070026#include "bit_utils.h"
Mathieu Chartierc2e20622014-11-03 11:41:47 -080027#include "logging.h"
28
29namespace art {
30
31// Returns true if an item is empty.
32template <class T>
33class DefaultEmptyFn {
34 public:
35 void MakeEmpty(T& item) const {
36 item = T();
37 }
38 bool IsEmpty(const T& item) const {
39 return item == T();
40 }
41};
42
43template <class T>
44class DefaultEmptyFn<T*> {
45 public:
46 void MakeEmpty(T*& item) const {
47 item = nullptr;
48 }
Vladimir Marko1f497642015-10-05 20:34:42 +010049 bool IsEmpty(T* const& item) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -080050 return item == nullptr;
51 }
52};
53
54// Low memory version of a hash set, uses less memory than std::unordered_set since elements aren't
Mathieu Chartier47f867a2015-03-18 10:39:00 -070055// boxed. Uses linear probing to resolve collisions.
56// EmptyFn needs to implement two functions MakeEmpty(T& item) and IsEmpty(const T& item).
57// TODO: We could get rid of this requirement by using a bitmap, though maybe this would be slower
58// and more complicated.
Mathieu Chartierc2e20622014-11-03 11:41:47 -080059template <class T, class EmptyFn = DefaultEmptyFn<T>, class HashFn = std::hash<T>,
60 class Pred = std::equal_to<T>, class Alloc = std::allocator<T>>
61class HashSet {
Mathieu Chartier47f867a2015-03-18 10:39:00 -070062 template <class Elem, class HashSetType>
Vladimir Marko1f497642015-10-05 20:34:42 +010063 class BaseIterator : std::iterator<std::forward_iterator_tag, Elem> {
Mathieu Chartierc2e20622014-11-03 11:41:47 -080064 public:
Mathieu Chartier47f867a2015-03-18 10:39:00 -070065 BaseIterator(const BaseIterator&) = default;
66 BaseIterator(BaseIterator&&) = default;
67 BaseIterator(HashSetType* hash_set, size_t index) : index_(index), hash_set_(hash_set) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -080068 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -070069 BaseIterator& operator=(const BaseIterator&) = default;
70 BaseIterator& operator=(BaseIterator&&) = default;
71
72 bool operator==(const BaseIterator& other) const {
73 return hash_set_ == other.hash_set_ && this->index_ == other.index_;
Mathieu Chartierc2e20622014-11-03 11:41:47 -080074 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -070075
76 bool operator!=(const BaseIterator& other) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -080077 return !(*this == other);
78 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -070079
80 BaseIterator operator++() { // Value after modification.
81 this->index_ = this->NextNonEmptySlot(this->index_, hash_set_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -080082 return *this;
83 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -070084
85 BaseIterator operator++(int) {
Vladimir Marko1f497642015-10-05 20:34:42 +010086 BaseIterator temp = *this;
Mathieu Chartier47f867a2015-03-18 10:39:00 -070087 this->index_ = this->NextNonEmptySlot(this->index_, hash_set_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -080088 return temp;
89 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -070090
91 Elem& operator*() const {
92 DCHECK(!hash_set_->IsFreeSlot(this->index_));
93 return hash_set_->ElementForIndex(this->index_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -080094 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -070095
96 Elem* operator->() const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -080097 return &**this;
98 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -070099
Vladimir Marko1f497642015-10-05 20:34:42 +0100100 // TODO: Operator -- --(int) (and use std::bidirectional_iterator_tag)
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800101
102 private:
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800103 size_t index_;
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700104 HashSetType* hash_set_;
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800105
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700106 size_t NextNonEmptySlot(size_t index, const HashSet* hash_set) const {
107 const size_t num_buckets = hash_set->NumBuckets();
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800108 DCHECK_LT(index, num_buckets);
109 do {
110 ++index;
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700111 } while (index < num_buckets && hash_set->IsFreeSlot(index));
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800112 return index;
113 }
114
115 friend class HashSet;
116 };
117
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700118 public:
Vladimir Marko1f497642015-10-05 20:34:42 +0100119 using value_type = T;
120 using allocator_type = Alloc;
121 using reference = T&;
122 using const_reference = const T&;
123 using pointer = T*;
124 using const_pointer = const T*;
125 using iterator = BaseIterator<T, HashSet>;
126 using const_iterator = BaseIterator<const T, const HashSet>;
127 using size_type = size_t;
128 using difference_type = ptrdiff_t;
129
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700130 static constexpr double kDefaultMinLoadFactor = 0.5;
131 static constexpr double kDefaultMaxLoadFactor = 0.9;
132 static constexpr size_t kMinBuckets = 1000;
133
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700134 // If we don't own the data, this will create a new array which owns the data.
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800135 void Clear() {
136 DeallocateStorage();
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800137 num_elements_ = 0;
138 elements_until_expand_ = 0;
139 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700140
Vladimir Marko1f497642015-10-05 20:34:42 +0100141 HashSet()
142 : num_elements_(0u),
143 num_buckets_(0u),
144 elements_until_expand_(0u),
145 owns_data_(false),
146 data_(nullptr),
147 min_load_factor_(kDefaultMinLoadFactor),
148 max_load_factor_(kDefaultMaxLoadFactor) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800149 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700150
Vladimir Marko1f497642015-10-05 20:34:42 +0100151 explicit HashSet(const allocator_type& alloc)
152 : allocfn_(alloc),
153 hashfn_(),
154 emptyfn_(),
155 pred_(),
156 num_elements_(0u),
157 num_buckets_(0u),
158 elements_until_expand_(0u),
159 owns_data_(false),
160 data_(nullptr),
161 min_load_factor_(kDefaultMinLoadFactor),
162 max_load_factor_(kDefaultMaxLoadFactor) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800163 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700164
Vladimir Marko1f497642015-10-05 20:34:42 +0100165 HashSet(const HashSet& other)
166 : allocfn_(other.allocfn_),
167 hashfn_(other.hashfn_),
168 emptyfn_(other.emptyfn_),
169 pred_(other.pred_),
170 num_elements_(other.num_elements_),
171 num_buckets_(0),
172 elements_until_expand_(other.elements_until_expand_),
173 owns_data_(false),
174 data_(nullptr),
175 min_load_factor_(other.min_load_factor_),
176 max_load_factor_(other.max_load_factor_) {
177 AllocateStorage(other.NumBuckets());
178 for (size_t i = 0; i < num_buckets_; ++i) {
179 ElementForIndex(i) = other.data_[i];
180 }
181 }
182
183 HashSet(HashSet&& other)
184 : allocfn_(std::move(other.allocfn_)),
185 hashfn_(std::move(other.hashfn_)),
186 emptyfn_(std::move(other.emptyfn_)),
187 pred_(std::move(other.pred_)),
188 num_elements_(other.num_elements_),
189 num_buckets_(other.num_buckets_),
190 elements_until_expand_(other.elements_until_expand_),
191 owns_data_(other.owns_data_),
192 data_(other.data_),
193 min_load_factor_(other.min_load_factor_),
194 max_load_factor_(other.max_load_factor_) {
195 other.num_elements_ = 0u;
196 other.num_buckets_ = 0u;
197 other.elements_until_expand_ = 0u;
198 other.owns_data_ = false;
199 other.data_ = nullptr;
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800200 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700201
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700202 // Construct from existing data.
203 // Read from a block of memory, if make_copy_of_data is false, then data_ points to within the
204 // passed in ptr_.
205 HashSet(const uint8_t* ptr, bool make_copy_of_data, size_t* read_count) {
206 uint64_t temp;
207 size_t offset = 0;
208 offset = ReadFromBytes(ptr, offset, &temp);
209 num_elements_ = static_cast<uint64_t>(temp);
210 offset = ReadFromBytes(ptr, offset, &temp);
211 num_buckets_ = static_cast<uint64_t>(temp);
212 CHECK_LE(num_elements_, num_buckets_);
213 offset = ReadFromBytes(ptr, offset, &temp);
214 elements_until_expand_ = static_cast<uint64_t>(temp);
215 offset = ReadFromBytes(ptr, offset, &min_load_factor_);
216 offset = ReadFromBytes(ptr, offset, &max_load_factor_);
217 if (!make_copy_of_data) {
218 owns_data_ = false;
219 data_ = const_cast<T*>(reinterpret_cast<const T*>(ptr + offset));
220 offset += sizeof(*data_) * num_buckets_;
221 } else {
222 AllocateStorage(num_buckets_);
223 // Write elements, not that this may not be safe for cross compilation if the elements are
224 // pointer sized.
225 for (size_t i = 0; i < num_buckets_; ++i) {
226 offset = ReadFromBytes(ptr, offset, &data_[i]);
227 }
228 }
229 // Caller responsible for aligning.
230 *read_count = offset;
231 }
232
233 // Returns how large the table is after being written. If target is null, then no writing happens
234 // but the size is still returned. Target must be 8 byte aligned.
235 size_t WriteToMemory(uint8_t* ptr) {
236 size_t offset = 0;
237 offset = WriteToBytes(ptr, offset, static_cast<uint64_t>(num_elements_));
238 offset = WriteToBytes(ptr, offset, static_cast<uint64_t>(num_buckets_));
239 offset = WriteToBytes(ptr, offset, static_cast<uint64_t>(elements_until_expand_));
240 offset = WriteToBytes(ptr, offset, min_load_factor_);
241 offset = WriteToBytes(ptr, offset, max_load_factor_);
242 // Write elements, not that this may not be safe for cross compilation if the elements are
243 // pointer sized.
244 for (size_t i = 0; i < num_buckets_; ++i) {
245 offset = WriteToBytes(ptr, offset, data_[i]);
246 }
247 // Caller responsible for aligning.
248 return offset;
249 }
250
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800251 ~HashSet() {
252 DeallocateStorage();
253 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700254
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800255 HashSet& operator=(HashSet&& other) {
Vladimir Marko1f497642015-10-05 20:34:42 +0100256 HashSet(std::move(other)).swap(*this);
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800257 return *this;
258 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700259
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800260 HashSet& operator=(const HashSet& other) {
Vladimir Marko1f497642015-10-05 20:34:42 +0100261 HashSet(other).swap(*this); // NOLINT(runtime/explicit) - a case of lint gone mad.
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800262 return *this;
263 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700264
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800265 // Lower case for c++11 for each.
Vladimir Marko1f497642015-10-05 20:34:42 +0100266 iterator begin() {
267 iterator ret(this, 0);
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700268 if (num_buckets_ != 0 && IsFreeSlot(ret.index_)) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800269 ++ret; // Skip all the empty slots.
270 }
271 return ret;
272 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700273
Igor Murashkine2facc52015-07-10 13:49:08 -0700274 // Lower case for c++11 for each. const version.
Vladimir Marko1f497642015-10-05 20:34:42 +0100275 const_iterator begin() const {
276 const_iterator ret(this, 0);
Igor Murashkine2facc52015-07-10 13:49:08 -0700277 if (num_buckets_ != 0 && IsFreeSlot(ret.index_)) {
278 ++ret; // Skip all the empty slots.
279 }
280 return ret;
281 }
282
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800283 // Lower case for c++11 for each.
Vladimir Marko1f497642015-10-05 20:34:42 +0100284 iterator end() {
285 return iterator(this, NumBuckets());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800286 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700287
Igor Murashkine2facc52015-07-10 13:49:08 -0700288 // Lower case for c++11 for each. const version.
Vladimir Marko1f497642015-10-05 20:34:42 +0100289 const_iterator end() const {
290 return const_iterator(this, NumBuckets());
Igor Murashkine2facc52015-07-10 13:49:08 -0700291 }
292
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800293 bool Empty() {
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700294 return Size() == 0;
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800295 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700296
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800297 // Erase algorithm:
298 // Make an empty slot where the iterator is pointing.
Igor Murashkine2facc52015-07-10 13:49:08 -0700299 // Scan forwards until we hit another empty slot.
300 // If an element in between doesn't rehash to the range from the current empty slot to the
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800301 // iterator. It must be before the empty slot, in that case we can move it to the empty slot
302 // and set the empty slot to be the location we just moved from.
303 // Relies on maintaining the invariant that there's no empty slots from the 'ideal' index of an
304 // element to its actual location/index.
Vladimir Marko1f497642015-10-05 20:34:42 +0100305 iterator Erase(iterator it) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800306 // empty_index is the index that will become empty.
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700307 size_t empty_index = it.index_;
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800308 DCHECK(!IsFreeSlot(empty_index));
309 size_t next_index = empty_index;
310 bool filled = false; // True if we filled the empty index.
311 while (true) {
312 next_index = NextIndex(next_index);
313 T& next_element = ElementForIndex(next_index);
314 // If the next element is empty, we are done. Make sure to clear the current empty index.
315 if (emptyfn_.IsEmpty(next_element)) {
316 emptyfn_.MakeEmpty(ElementForIndex(empty_index));
317 break;
318 }
319 // Otherwise try to see if the next element can fill the current empty index.
320 const size_t next_hash = hashfn_(next_element);
321 // Calculate the ideal index, if it is within empty_index + 1 to next_index then there is
322 // nothing we can do.
323 size_t next_ideal_index = IndexForHash(next_hash);
324 // Loop around if needed for our check.
325 size_t unwrapped_next_index = next_index;
326 if (unwrapped_next_index < empty_index) {
327 unwrapped_next_index += NumBuckets();
328 }
329 // Loop around if needed for our check.
330 size_t unwrapped_next_ideal_index = next_ideal_index;
331 if (unwrapped_next_ideal_index < empty_index) {
332 unwrapped_next_ideal_index += NumBuckets();
333 }
334 if (unwrapped_next_ideal_index <= empty_index ||
335 unwrapped_next_ideal_index > unwrapped_next_index) {
336 // If the target index isn't within our current range it must have been probed from before
337 // the empty index.
338 ElementForIndex(empty_index) = std::move(next_element);
339 filled = true; // TODO: Optimize
340 empty_index = next_index;
341 }
342 }
343 --num_elements_;
344 // If we didn't fill the slot then we need go to the next non free slot.
345 if (!filled) {
346 ++it;
347 }
348 return it;
349 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700350
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800351 // Find an element, returns end() if not found.
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700352 // Allows custom key (K) types, example of when this is useful:
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800353 // Set of Class* sorted by name, want to find a class with a name but can't allocate a dummy
354 // object in the heap for performance solution.
355 template <typename K>
Vladimir Marko1f497642015-10-05 20:34:42 +0100356 iterator Find(const K& key) {
Igor Murashkine2facc52015-07-10 13:49:08 -0700357 return FindWithHash(key, hashfn_(key));
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800358 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700359
360 template <typename K>
Vladimir Marko1f497642015-10-05 20:34:42 +0100361 const_iterator Find(const K& key) const {
Igor Murashkine2facc52015-07-10 13:49:08 -0700362 return FindWithHash(key, hashfn_(key));
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700363 }
364
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800365 template <typename K>
Vladimir Marko1f497642015-10-05 20:34:42 +0100366 iterator FindWithHash(const K& key, size_t hash) {
367 return iterator(this, FindIndex(key, hash));
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800368 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700369
370 template <typename K>
Vladimir Marko1f497642015-10-05 20:34:42 +0100371 const_iterator FindWithHash(const K& key, size_t hash) const {
372 return const_iterator(this, FindIndex(key, hash));
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700373 }
374
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800375 // Insert an element, allows duplicates.
376 void Insert(const T& element) {
377 InsertWithHash(element, hashfn_(element));
378 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700379
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800380 void InsertWithHash(const T& element, size_t hash) {
381 DCHECK_EQ(hash, hashfn_(element));
382 if (num_elements_ >= elements_until_expand_) {
383 Expand();
384 DCHECK_LT(num_elements_, elements_until_expand_);
385 }
386 const size_t index = FirstAvailableSlot(IndexForHash(hash));
387 data_[index] = element;
388 ++num_elements_;
389 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700390
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800391 size_t Size() const {
392 return num_elements_;
393 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700394
Vladimir Marko1f497642015-10-05 20:34:42 +0100395 void swap(HashSet& other) {
396 // Use argument-dependent lookup with fall-back to std::swap() for function objects.
397 using std::swap;
398 swap(allocfn_, other.allocfn_);
399 swap(hashfn_, other.hashfn_);
400 swap(emptyfn_, other.emptyfn_);
401 swap(pred_, other.pred_);
402 std::swap(data_, other.data_);
403 std::swap(num_buckets_, other.num_buckets_);
404 std::swap(num_elements_, other.num_elements_);
405 std::swap(elements_until_expand_, other.elements_until_expand_);
406 std::swap(min_load_factor_, other.min_load_factor_);
407 std::swap(max_load_factor_, other.max_load_factor_);
408 std::swap(owns_data_, other.owns_data_);
409 }
410
411 allocator_type get_allocator() const {
412 return allocfn_;
413 }
414
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800415 void ShrinkToMaximumLoad() {
416 Resize(Size() / max_load_factor_);
417 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700418
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800419 // To distance that inserted elements were probed. Used for measuring how good hash functions
420 // are.
421 size_t TotalProbeDistance() const {
422 size_t total = 0;
423 for (size_t i = 0; i < NumBuckets(); ++i) {
424 const T& element = ElementForIndex(i);
425 if (!emptyfn_.IsEmpty(element)) {
426 size_t ideal_location = IndexForHash(hashfn_(element));
427 if (ideal_location > i) {
428 total += i + NumBuckets() - ideal_location;
429 } else {
430 total += i - ideal_location;
431 }
432 }
433 }
434 return total;
435 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700436
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800437 // Calculate the current load factor and return it.
438 double CalculateLoadFactor() const {
439 return static_cast<double>(Size()) / static_cast<double>(NumBuckets());
440 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700441
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800442 // Make sure that everything reinserts in the right spot. Returns the number of errors.
443 size_t Verify() {
444 size_t errors = 0;
445 for (size_t i = 0; i < num_buckets_; ++i) {
446 T& element = data_[i];
447 if (!emptyfn_.IsEmpty(element)) {
448 T temp;
449 emptyfn_.MakeEmpty(temp);
450 std::swap(temp, element);
451 size_t first_slot = FirstAvailableSlot(IndexForHash(hashfn_(temp)));
452 if (i != first_slot) {
453 LOG(ERROR) << "Element " << i << " should be in slot " << first_slot;
454 ++errors;
455 }
456 std::swap(temp, element);
457 }
458 }
459 return errors;
460 }
461
462 private:
463 T& ElementForIndex(size_t index) {
464 DCHECK_LT(index, NumBuckets());
465 DCHECK(data_ != nullptr);
466 return data_[index];
467 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700468
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800469 const T& ElementForIndex(size_t index) const {
470 DCHECK_LT(index, NumBuckets());
471 DCHECK(data_ != nullptr);
472 return data_[index];
473 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700474
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800475 size_t IndexForHash(size_t hash) const {
Igor Murashkine2facc52015-07-10 13:49:08 -0700476 // Protect against undefined behavior (division by zero).
477 if (UNLIKELY(num_buckets_ == 0)) {
478 return 0;
479 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800480 return hash % num_buckets_;
481 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700482
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800483 size_t NextIndex(size_t index) const {
484 if (UNLIKELY(++index >= num_buckets_)) {
485 DCHECK_EQ(index, NumBuckets());
486 return 0;
487 }
488 return index;
489 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700490
491 // Find the hash table slot for an element, or return NumBuckets() if not found.
Vladimir Marko1f497642015-10-05 20:34:42 +0100492 // This value for not found is important so that iterator(this, FindIndex(...)) == end().
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700493 template <typename K>
494 size_t FindIndex(const K& element, size_t hash) const {
Igor Murashkine2facc52015-07-10 13:49:08 -0700495 // Guard against failing to get an element for a non-existing index.
496 if (UNLIKELY(NumBuckets() == 0)) {
497 return 0;
498 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700499 DCHECK_EQ(hashfn_(element), hash);
500 size_t index = IndexForHash(hash);
501 while (true) {
502 const T& slot = ElementForIndex(index);
503 if (emptyfn_.IsEmpty(slot)) {
504 return NumBuckets();
505 }
506 if (pred_(slot, element)) {
507 return index;
508 }
509 index = NextIndex(index);
510 }
511 }
512
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800513 bool IsFreeSlot(size_t index) const {
514 return emptyfn_.IsEmpty(ElementForIndex(index));
515 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700516
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800517 size_t NumBuckets() const {
518 return num_buckets_;
519 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700520
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800521 // Allocate a number of buckets.
522 void AllocateStorage(size_t num_buckets) {
523 num_buckets_ = num_buckets;
524 data_ = allocfn_.allocate(num_buckets_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700525 owns_data_ = true;
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800526 for (size_t i = 0; i < num_buckets_; ++i) {
527 allocfn_.construct(allocfn_.address(data_[i]));
528 emptyfn_.MakeEmpty(data_[i]);
529 }
530 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700531
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800532 void DeallocateStorage() {
Mathieu Chartier88b6b052015-07-22 19:39:56 -0700533 if (owns_data_) {
534 for (size_t i = 0; i < NumBuckets(); ++i) {
535 allocfn_.destroy(allocfn_.address(data_[i]));
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800536 }
Mathieu Chartier88b6b052015-07-22 19:39:56 -0700537 if (data_ != nullptr) {
538 allocfn_.deallocate(data_, NumBuckets());
539 }
540 owns_data_ = false;
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800541 }
Mathieu Chartier88b6b052015-07-22 19:39:56 -0700542 data_ = nullptr;
543 num_buckets_ = 0;
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800544 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700545
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800546 // Expand the set based on the load factors.
547 void Expand() {
548 size_t min_index = static_cast<size_t>(Size() / min_load_factor_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800549 // Resize based on the minimum load factor.
550 Resize(min_index);
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800551 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700552
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800553 // Expand / shrink the table to the new specified size.
554 void Resize(size_t new_size) {
Mathieu Chartier88b6b052015-07-22 19:39:56 -0700555 if (new_size < kMinBuckets) {
556 new_size = kMinBuckets;
557 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800558 DCHECK_GE(new_size, Size());
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700559 T* const old_data = data_;
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800560 size_t old_num_buckets = num_buckets_;
561 // Reinsert all of the old elements.
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700562 const bool owned_data = owns_data_;
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800563 AllocateStorage(new_size);
564 for (size_t i = 0; i < old_num_buckets; ++i) {
565 T& element = old_data[i];
566 if (!emptyfn_.IsEmpty(element)) {
567 data_[FirstAvailableSlot(IndexForHash(hashfn_(element)))] = std::move(element);
568 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700569 if (owned_data) {
570 allocfn_.destroy(allocfn_.address(element));
571 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800572 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700573 if (owned_data) {
574 allocfn_.deallocate(old_data, old_num_buckets);
575 }
Igor Murashkin3552d962015-06-22 15:57:38 -0700576
577 // When we hit elements_until_expand_, we are at the max load factor and must expand again.
578 elements_until_expand_ = NumBuckets() * max_load_factor_;
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800579 }
Mathieu Chartier47f867a2015-03-18 10:39:00 -0700580
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800581 ALWAYS_INLINE size_t FirstAvailableSlot(size_t index) const {
Igor Murashkin3552d962015-06-22 15:57:38 -0700582 DCHECK_LT(index, NumBuckets()); // Don't try to get a slot out of range.
583 size_t non_empty_count = 0;
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800584 while (!emptyfn_.IsEmpty(data_[index])) {
585 index = NextIndex(index);
Igor Murashkin3552d962015-06-22 15:57:38 -0700586 non_empty_count++;
587 DCHECK_LE(non_empty_count, NumBuckets()); // Don't loop forever.
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800588 }
589 return index;
590 }
591
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700592 // Return new offset.
593 template <typename Elem>
594 static size_t WriteToBytes(uint8_t* ptr, size_t offset, Elem n) {
595 DCHECK_ALIGNED(ptr + offset, sizeof(n));
596 if (ptr != nullptr) {
597 *reinterpret_cast<Elem*>(ptr + offset) = n;
598 }
599 return offset + sizeof(n);
600 }
601
602 template <typename Elem>
603 static size_t ReadFromBytes(const uint8_t* ptr, size_t offset, Elem* out) {
604 DCHECK(ptr != nullptr);
605 DCHECK_ALIGNED(ptr + offset, sizeof(*out));
606 *out = *reinterpret_cast<const Elem*>(ptr + offset);
607 return offset + sizeof(*out);
608 }
609
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800610 Alloc allocfn_; // Allocator function.
611 HashFn hashfn_; // Hashing function.
612 EmptyFn emptyfn_; // IsEmpty/SetEmpty function.
613 Pred pred_; // Equals function.
614 size_t num_elements_; // Number of inserted elements.
615 size_t num_buckets_; // Number of hash table buckets.
Igor Murashkin3552d962015-06-22 15:57:38 -0700616 size_t elements_until_expand_; // Maximum number of elements until we expand the table.
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700617 bool owns_data_; // If we own data_ and are responsible for freeing it.
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800618 T* data_; // Backing storage.
619 double min_load_factor_;
620 double max_load_factor_;
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800621};
622
Vladimir Marko1f497642015-10-05 20:34:42 +0100623template <class T, class EmptyFn, class HashFn, class Pred, class Alloc>
624void swap(HashSet<T, EmptyFn, HashFn, Pred, Alloc>& lhs,
625 HashSet<T, EmptyFn, HashFn, Pred, Alloc>& rhs) {
626 lhs.swap(rhs);
627}
628
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800629} // namespace art
630
631#endif // ART_RUNTIME_BASE_HASH_SET_H_