Debian Codegraph @

src/core/SkTHash.h

raw
1 /*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #ifndef SkTHash_DEFINED
9 #define SkTHash_DEFINED
10
11 #include "include/core/SkTypes.h"
12 #include "src/base/SkMathPriv.h"
13 #include "src/core/SkChecksum.h"
14
15 #include <initializer_list>
16 #include <memory>
17 #include <new>
18 #include <type_traits>
19 #include <utility>
20
21 namespace skia_private {
22
23 // Before trying to use THashTable, look below to see if THashMap or THashSet works for you.
24 // They're easier to use, usually perform the same, and have fewer sharp edges.
25
26 // T and K are treated as ordinary copyable C++ types.
27 // Traits must have:
28 // - static K GetKey(T)
29 // - static uint32_t Hash(K)
30 // Traits may also define (both required if either is defined):
31 // - static bool ShouldGrow(int count, int capacity)
32 // - static bool ShouldShrink(int count, int capacity)
33 // , which specify the max/min load factor of the table.
34 // If the key is large and stored inside T, you may want to make K a const&.
35 // Similarly, if T is large you might want it to be a pointer.
36 template <typename T, typename K, typename Traits = T>
37 class THashTable {
38 public:
39 THashTable() = default;
40 ~THashTable() = default;
41
42 THashTable(const THashTable& that) { *this = that; }
43 THashTable( THashTable&& that) { *this = std::move(that); }
44
45 THashTable& operator=(const THashTable& that) {
46 if (this != &that) {
47 fCount = that.fCount;
48 fCapacity = that.fCapacity;
49 fSlots.reset(new Slot[that.fCapacity]);
50 for (int i = 0; i < fCapacity; i++) {
51 fSlots[i] = that.fSlots[i];
52 }
53 }
54 return *this;
55 }
56
57 THashTable& operator=(THashTable&& that) {
58 if (this != &that) {
59 fCount = that.fCount;
60 fCapacity = that.fCapacity;
61 fSlots = std::move(that.fSlots);
62
63 that.fCount = that.fCapacity = 0;
64 }
65 return *this;
66 }
67
68 // Clear the table.
69 void reset() { *this = THashTable(); }
70
71 // How many entries are in the table?
72 int count() const { return fCount; }
73
74 // How many slots does the table contain? (Note that unlike an array, hash tables can grow
75 // before reaching 100% capacity.)
76 int capacity() const { return fCapacity; }
77
78 // Approximately how many bytes of memory do we use beyond sizeof(*this)?
79 size_t approxBytesUsed() const { return fCapacity * sizeof(Slot); }
80
81 // Exchange two hash tables.
82 void swap(THashTable& that) {
83 std::swap(fCount, that.fCount);
84 std::swap(fCapacity, that.fCapacity);
85 std::swap(fSlots, that.fSlots);
86 }
87
88 void swap(THashTable&& that) {
89 *this = std::move(that);
90 }
91
92 // !!!!!!!!!!!!!!!!! CAUTION !!!!!!!!!!!!!!!!!
93 // set(), find() and foreach() all allow mutable access to table entries.
94 // If you change an entry so that it no longer has the same key, all hell
95 // will break loose. Do not do that!
96 //
97 // Please prefer to use THashMap or THashSet, which do not have this danger.
98
99 // The pointers returned by set() and find() are valid only until the next call to set().
100 // The pointers you receive in foreach() are only valid for its duration.
101
102 // Copy val into the hash table, returning a pointer to the copy now in the table.
103 // If there already is an entry in the table with the same key, we overwrite it.
104 T* set(T val) {
105 bool shouldGrow = false;
106 if constexpr (HasShouldGrow<Traits>::value) {
107 shouldGrow = Traits::ShouldGrow(fCount, fCapacity);
108 } else {
109 shouldGrow = (4 * fCount >= 3 * fCapacity);
110 }
111 if (shouldGrow) {
112 this->resize(fCapacity > 0 ? fCapacity * 2 : 4);
113 }
114 return this->uncheckedSet(std::move(val));
115 }
116
117 // If there is an entry in the table with this key, return a pointer to it. If not, null.
118 T* find(const K& key) const {
119 uint32_t hash = Hash(key);
120 int index = hash & (fCapacity-1);
121 for (int n = 0; n < fCapacity; n++) {
122 Slot& s = fSlots[index];
123 if (s.empty()) {
124 return nullptr;
125 }
126 if (hash == s.fHash && key == Traits::GetKey(*s)) {
127 return &*s;
128 }
129 index = this->next(index);
130 }
131 SkASSERT(fCapacity == fCount);
132 return nullptr;
133 }
134
135 // If there is an entry in the table with this key, return it. If not, null.
136 // This only works for pointer type T, and cannot be used to find an nullptr entry.
137 T findOrNull(const K& key) const {
138 if (T* p = this->find(key)) {
139 return *p;
140 }
141 return nullptr;
142 }
143
144 // If a value with this key exists in the hash table, removes it and returns true.
145 // Otherwise, returns false.
146 bool removeIfExists(const K& key) {
147 uint32_t hash = Hash(key);
148 int index = hash & (fCapacity-1);
149 for (int n = 0; n < fCapacity; n++) {
150 Slot& s = fSlots[index];
151 if (s.empty()) {
152 return false;
153 }
154 if (hash == s.fHash && key == Traits::GetKey(*s)) {
155 this->removeSlot(index);
156 if (fCapacity > 4) {
157 bool shouldShrink = false;
158 if constexpr (HasShouldShrink<Traits>::value) {
159 shouldShrink = Traits::ShouldShrink(fCount, fCapacity);
160 } else {
161 shouldShrink = (4 * fCount <= fCapacity);
162 }
163 if (shouldShrink) {
164 this->resize(fCapacity / 2);
165 }
166 }
167 return true;
168 }
169 index = this->next(index);
170 }
171 SkASSERT(fCapacity == fCount);
172 return false;
173 }
174
175 // Removes the value with this key from the hash table. Asserts if it is missing.
176 void remove(const K& key) {
177 SkAssertResult(this->removeIfExists(key));
178 }
179
180 // Hash tables will automatically resize themselves when set() and remove() are called, but
181 // resize() can be called to manually grow capacity before a bulk insertion.
182 void resize(int capacity) {
183 // We must have enough capacity to hold every key.
184 SkASSERT(capacity >= fCount);
185 // `capacity` must be a power of two, because we use `hash & (capacity-1)` to look up keys
186 // in the table (since this is faster than a modulo).
187 SkASSERT((capacity & (capacity - 1)) == 0);
188
189 int oldCapacity = fCapacity;
190 SkDEBUGCODE(int oldCount = fCount);
191
192 fCount = 0;
193 fCapacity = capacity;
194 std::unique_ptr<Slot[]> oldSlots = std::move(fSlots);
195 fSlots.reset(new Slot[capacity]);
196
197 for (int i = 0; i < oldCapacity; i++) {
198 Slot& s = oldSlots[i];
199 if (s.has_value()) {
200 this->uncheckedSet(*std::move(s));
201 }
202 }
203 SkASSERT(fCount == oldCount);
204 }
205
206 // Reserve extra capacity. This only grows capacity; requests to shrink are ignored.
207 // We assume that the passed-in value represents the number of items that the caller wants to
208 // store in the table. The passed-in value is adjusted to honor the following rules:
209 // - Hash tables must have a power-of-two capacity.
210 // - Hash tables grow when they exceed 3/4 capacity, not when they are full.
211 void reserve(int n) {
212 int newCapacity = SkNextPow2(n);
213
214 bool shouldGrow = false;
215 if constexpr (HasShouldGrow<Traits>::value) {
216 shouldGrow = Traits::ShouldGrow(n, newCapacity);
217 } else {
218 shouldGrow = (n * 4 > newCapacity * 3);
219 }
220 if (shouldGrow) {
221 newCapacity *= 2;
222 }
223
224 if (newCapacity > fCapacity) {
225 this->resize(newCapacity);
226 }
227 }
228
229 // Call fn on every entry in the table. You may mutate the entries, but be very careful.
230 template <typename Fn> // f(T*)
231 void foreach(Fn&& fn) {
232 for (int i = 0; i < fCapacity; i++) {
233 if (fSlots[i].has_value()) {
234 fn(&*fSlots[i]);
235 }
236 }
237 }
238
239 // Call fn on every entry in the table. You may not mutate anything.
240 template <typename Fn> // f(T) or f(const T&)
241 void foreach(Fn&& fn) const {
242 for (int i = 0; i < fCapacity; i++) {
243 if (fSlots[i].has_value()) {
244 fn(*fSlots[i]);
245 }
246 }
247 }
248
249 // A basic iterator-like class which disallows mutation; sufficient for range-based for loops.
250 // Intended for use by THashMap and THashSet via begin() and end().
251 // Adding or removing elements may invalidate all iterators.
252 template <typename SlotVal>
253 class Iter {
254 public:
255 using TTable = THashTable<T, K, Traits>;
256
257 Iter(const TTable* table, int slot) : fTable(table), fSlot(slot) {}
258
259 static Iter MakeBegin(const TTable* table) {
260 return Iter{table, table->firstPopulatedSlot()};
261 }
262
263 static Iter MakeEnd(const TTable* table) {
264 return Iter{table, table->capacity()};
265 }
266
267 const SlotVal& operator*() const {
268 return *fTable->slot(fSlot);
269 }
270
271 const SlotVal* operator->() const {
272 return fTable->slot(fSlot);
273 }
274
275 bool operator==(const Iter& that) const {
276 // Iterators from different tables shouldn't be compared against each other.
277 SkASSERT(fTable == that.fTable);
278 return fSlot == that.fSlot;
279 }
280
281 bool operator!=(const Iter& that) const {
282 return !(*this == that);
283 }
284
285 Iter& operator++() {
286 fSlot = fTable->nextPopulatedSlot(fSlot);
287 return *this;
288 }
289
290 Iter operator++(int) {
291 Iter old = *this;
292 this->operator++();
293 return old;
294 }
295
296 protected:
297 const TTable* fTable;
298 int fSlot;
299 };
300
301 private:
302 template <typename U, typename = void> struct HasShouldGrow : std::false_type {};
303 template <typename U, typename = void> struct HasShouldShrink : std::false_type {};
304
305 template <typename U>
306 struct HasShouldGrow<
307 U,
308 std::void_t<decltype(U::ShouldGrow(std::declval<int>(), std::declval<int>()))>>
309 : std::true_type {
310 static_assert(HasShouldShrink<U>::value,
311 "The traits class must also provide ShouldShrink() method.");
312 };
313
314 template <typename U>
315 struct HasShouldShrink<
316 U,
317 std::void_t<decltype(U::ShouldShrink(std::declval<int>(), std::declval<int>()))>>
318 : std::true_type {
319 static_assert(HasShouldGrow<U>::value,
320 "The traits class must also provide ShouldGrow() method.");
321 };
322
323 // Finds the first non-empty slot for an iterator.
324 int firstPopulatedSlot() const {
325 for (int i = 0; i < fCapacity; i++) {
326 if (fSlots[i].has_value()) {
327 return i;
328 }
329 }
330 return fCapacity;
331 }
332
333 // Increments an iterator's slot.
334 int nextPopulatedSlot(int currentSlot) const {
335 for (int i = currentSlot + 1; i < fCapacity; i++) {
336 if (fSlots[i].has_value()) {
337 return i;
338 }
339 }
340 return fCapacity;
341 }
342
343 // Reads from an iterator's slot.
344 const T* slot(int i) const {
345 SkASSERT(fSlots[i].has_value());
346 return &*fSlots[i];
347 }
348
349 T* uncheckedSet(T&& val) {
350 const K& key = Traits::GetKey(val);
351 SkASSERT(key == key);
352 uint32_t hash = Hash(key);
353 int index = hash & (fCapacity-1);
354 for (int n = 0; n < fCapacity; n++) {
355 Slot& s = fSlots[index];
356 if (s.empty()) {
357 // New entry.
358 s.emplace(std::move(val), hash);
359 fCount++;
360 return &*s;
361 }
362 if (hash == s.fHash && key == Traits::GetKey(*s)) {
363 // Overwrite previous entry.
364 // Note: this triggers extra copies when adding the same value repeatedly.
365 s.emplace(std::move(val), hash);
366 return &*s;
367 }
368
369 index = this->next(index);
370 }
371 SkASSERT(false);
372 return nullptr;
373 }
374
375 void removeSlot(int index) {
376 fCount--;
377
378 // Rearrange elements to restore the invariants for linear probing.
379 for (;;) {
380 Slot& emptySlot = fSlots[index];
381 int emptyIndex = index;
382 int originalIndex;
383 // Look for an element that can be moved into the empty slot.
384 // If the empty slot is in between where an element landed, and its native slot, then
385 // move it to the empty slot. Don't move it if its native slot is in between where
386 // the element landed and the empty slot.
387 // [native] <= [empty] < [candidate] == GOOD, can move candidate to empty slot
388 // [empty] < [native] < [candidate] == BAD, need to leave candidate where it is
389 do {
390 index = this->next(index);
391 Slot& s = fSlots[index];
392 if (s.empty()) {
393 // We're done shuffling elements around. Clear the last empty slot.
394 emptySlot.reset();
395 return;
396 }
397 originalIndex = s.fHash & (fCapacity - 1);
398 } while ((index <= originalIndex && originalIndex < emptyIndex)
399 || (originalIndex < emptyIndex && emptyIndex < index)
400 || (emptyIndex < index && index <= originalIndex));
401 // Move the element to the empty slot.
402 Slot& moveFrom = fSlots[index];
403 emptySlot = std::move(moveFrom);
404 }
405 }
406
407 int next(int index) const {
408 index--;
409 if (index < 0) { index += fCapacity; }
410 return index;
411 }
412
413 static uint32_t Hash(const K& key) {
414 uint32_t hash = Traits::Hash(key) & 0xffffffff;
415 return hash ? hash : 1; // We reserve hash 0 to mark empty.
416 }
417
418 class Slot {
419 public:
420 Slot() = default;
421 ~Slot() { this->reset(); }
422
423 Slot(const Slot& that) { *this = that; }
424 Slot& operator=(const Slot& that) {
425 if (this == &that) {
426 return *this;
427 }
428 if (fHash) {
429 if (that.fHash) {
430 fVal.fStorage = that.fVal.fStorage;
431 fHash = that.fHash;
432 } else {
433 this->reset();
434 }
435 } else {
436 if (that.fHash) {
437 new (&fVal.fStorage) T(that.fVal.fStorage);
438 fHash = that.fHash;
439 } else {
440 // do nothing, no value on either side
441 }
442 }
443 return *this;
444 }
445
446 Slot(Slot&& that) { *this = std::move(that); }
447 Slot& operator=(Slot&& that) {
448 if (this == &that) {
449 return *this;
450 }
451 if (fHash) {
452 if (that.fHash) {
453 fVal.fStorage = std::move(that.fVal.fStorage);
454 fHash = that.fHash;
455 } else {
456 this->reset();
457 }
458 } else {
459 if (that.fHash) {
460 new (&fVal.fStorage) T(std::move(that.fVal.fStorage));
461 fHash = that.fHash;
462 } else {
463 // do nothing, no value on either side
464 }
465 }
466 return *this;
467 }
468
469 T& operator*() & { return fVal.fStorage; }
470 const T& operator*() const& { return fVal.fStorage; }
471 T&& operator*() && { return std::move(fVal.fStorage); }
472 const T&& operator*() const&& { return std::move(fVal.fStorage); }
473
474 Slot& emplace(T&& v, uint32_t h) {
475 this->reset();
476 new (&fVal.fStorage) T(std::move(v));
477 fHash = h;
478 return *this;
479 }
480
481 bool has_value() const { return fHash != 0; }
482 explicit operator bool() const { return this->has_value(); }
483 bool empty() const { return !this->has_value(); }
484
485 void reset() {
486 if (fHash) {
487 fVal.fStorage.~T();
488 fHash = 0;
489 }
490 }
491
492 uint32_t fHash = 0;
493
494 private:
495 union Storage {
496 T fStorage;
497 Storage() {}
498 ~Storage() {}
499 } fVal;
500 };
501
502 int fCount = 0,
503 fCapacity = 0;
504 std::unique_ptr<Slot[]> fSlots;
505 };
506
507 // Maps K->V. A more user-friendly wrapper around THashTable, suitable for most use cases.
508 // K and V are treated as ordinary copyable C++ types, with no assumed relationship between the two.
509 template <typename K, typename V, typename HashK = SkGoodHash>
510 class THashMap {
511 public:
512 // Allow default construction and assignment.
513 THashMap() = default;
514
515 THashMap(THashMap<K, V, HashK>&& that) = default;
516 THashMap(const THashMap<K, V, HashK>& that) = default;
517
518 THashMap<K, V, HashK>& operator=(THashMap<K, V, HashK>&& that) = default;
519 THashMap<K, V, HashK>& operator=(const THashMap<K, V, HashK>& that) = default;
520
521 // Construct with an initializer list of key-value pairs.
522 struct Pair : public std::pair<K, V> {
523 using std::pair<K, V>::pair;
524 static const K& GetKey(const Pair& p) { return p.first; }
525 static auto Hash(const K& key) { return HashK()(key); }
526 };
527
528 THashMap(std::initializer_list<Pair> pairs) {
529 int capacity = pairs.size() >= 4 ? SkNextPow2(pairs.size() * 4 / 3)
530 : 4;
531 fTable.resize(capacity);
532 for (const Pair& p : pairs) {
533 fTable.set(p);
534 }
535 }
536
537 // Clear the map.
538 void reset() { fTable.reset(); }
539
540 // How many key/value pairs are in the table?
541 int count() const { return fTable.count(); }
542
543 // Is empty?
544 bool empty() const { return fTable.count() == 0; }
545
546 // Approximately how many bytes of memory do we use beyond sizeof(*this)?
547 size_t approxBytesUsed() const { return fTable.approxBytesUsed(); }
548
549 // Reserve extra capacity.
550 void reserve(int n) { fTable.reserve(n); }
551
552 // Exchange two hash maps.
553 void swap(THashMap& that) { fTable.swap(that.fTable); }
554 void swap(THashMap&& that) { fTable.swap(std::move(that.fTable)); }
555
556 // N.B. The pointers returned by set() and find() are valid only until the next call to set().
557
558 // Set key to val in the table, replacing any previous value with the same key.
559 // We copy both key and val, and return a pointer to the value copy now in the table.
560 V* set(K key, V val) {
561 Pair* out = fTable.set({std::move(key), std::move(val)});
562 return &out->second;
563 }
564
565 // If there is key/value entry in the table with this key, return a pointer to the value.
566 // If not, return null.
567 V* find(const K& key) const {
568 if (Pair* p = fTable.find(key)) {
569 return &p->second;
570 }
571 return nullptr;
572 }
573
574 V& operator[](const K& key) {
575 if (V* val = this->find(key)) {
576 return *val;
577 }
578 return *this->set(key, V{});
579 }
580
581 // Removes the key/value entry in the table with this key. Asserts if the key is not present.
582 void remove(const K& key) {
583 fTable.remove(key);
584 }
585
586 // If the key exists in the table, removes it and returns true. Otherwise, returns false.
587 bool removeIfExists(const K& key) {
588 return fTable.removeIfExists(key);
589 }
590
591 // Call fn on every key/value pair in the table. You may mutate the value but not the key.
592 template <typename Fn, // f(K, V*) or f(const K&, V*)
593 std::enable_if_t<std::is_invocable_v<Fn, K, V*>>* = nullptr>
594 void foreach(Fn&& fn) {
595 fTable.foreach([&fn](Pair* p) { fn(p->first, &p->second); });
596 }
597
598 // Call fn on every key/value pair in the table. You may not mutate anything.
599 template <typename Fn, // f(K, V), f(const K&, V), f(K, const V&) or f(const K&, const V&).
600 std::enable_if_t<std::is_invocable_v<Fn, K, V>>* = nullptr>
601 void foreach(Fn&& fn) const {
602 fTable.foreach([&fn](const Pair& p) { fn(p.first, p.second); });
603 }
604
605 // Call fn on every key/value pair in the table. You may not mutate anything.
606 template <typename Fn, // f(Pair), or f(const Pair&)
607 std::enable_if_t<std::is_invocable_v<Fn, Pair>>* = nullptr>
608 void foreach(Fn&& fn) const {
609 fTable.foreach([&fn](const Pair& p) { fn(p); });
610 }
611
612 // Dereferencing an iterator gives back a key-value pair, suitable for structured binding.
613 using Iter = typename THashTable<Pair, K>::template Iter<std::pair<K, V>>;
614
615 Iter begin() const {
616 return Iter::MakeBegin(&fTable);
617 }
618
619 Iter end() const {
620 return Iter::MakeEnd(&fTable);
621 }
622
623 private:
624 THashTable<Pair, K> fTable;
625 };
626
627 // A set of T. T is treated as an ordinary copyable C++ type.
628 template <typename T, typename HashT = SkGoodHash>
629 class THashSet {
630 public:
631 // Allow default construction and assignment.
632 THashSet() = default;
633
634 THashSet(THashSet<T, HashT>&& that) = default;
635 THashSet(const THashSet<T, HashT>& that) = default;
636
637 THashSet<T, HashT>& operator=(THashSet<T, HashT>&& that) = default;
638 THashSet<T, HashT>& operator=(const THashSet<T, HashT>& that) = default;
639
640 // Construct with an initializer list of Ts.
641 THashSet(std::initializer_list<T> vals) {
642 int capacity = vals.size() >= 4 ? SkNextPow2(vals.size() * 4 / 3)
643 : 4;
644 fTable.resize(capacity);
645 for (const T& val : vals) {
646 fTable.set(val);
647 }
648 }
649
650 // Clear the set.
651 void reset() { fTable.reset(); }
652
653 // How many items are in the set?
654 int count() const { return fTable.count(); }
655
656 // Is empty?
657 bool empty() const { return fTable.count() == 0; }
658
659 // Approximately how many bytes of memory do we use beyond sizeof(*this)?
660 size_t approxBytesUsed() const { return fTable.approxBytesUsed(); }
661
662 // Reserve extra capacity.
663 void reserve(int n) { fTable.reserve(n); }
664
665 // Exchange two hash sets.
666 void swap(THashSet& that) { fTable.swap(that.fTable); }
667 void swap(THashSet&& that) { fTable.swap(std::move(that.fTable)); }
668
669 // Copy an item into the set.
670 void add(T item) { fTable.set(std::move(item)); }
671
672 // Is this item in the set?
673 bool contains(const T& item) const { return SkToBool(this->find(item)); }
674
675 // If an item equal to this is in the set, return a pointer to it, otherwise null.
676 // This pointer remains valid until the next call to add().
677 const T* find(const T& item) const { return fTable.find(item); }
678
679 // Remove the item in the set equal to this.
680 void remove(const T& item) {
681 SkASSERT(this->contains(item));
682 fTable.remove(item);
683 }
684
685 // Call fn on every item in the set. You may not mutate anything.
686 template <typename Fn> // f(T), f(const T&)
687 void foreach (Fn&& fn) const {
688 fTable.foreach(fn);
689 }
690
691 private:
692 struct Traits {
693 static const T& GetKey(const T& item) { return item; }
694 static auto Hash(const T& item) { return HashT()(item); }
695 };
696
697 public:
698 using Iter = typename THashTable<T, T, Traits>::template Iter<T>;
699
700 Iter begin() const {
701 return Iter::MakeBegin(&fTable);
702 }
703
704 Iter end() const {
705 return Iter::MakeEnd(&fTable);
706 }
707
708 private:
709 THashTable<T, T, Traits> fTable;
710 };
711
712 } // namespace skia_private
713
714 #endif // SkTHash_DEFINED