blob: 06e63a2113974db3b0e7e5bf42c7346a96921cdd [file] [log] [blame]
halcanary038cb5e2015-03-25 10:22:53 -07001/*
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
mtklein979e0ea2015-02-12 13:20:08 -08008#ifndef SkTHash_DEFINED
9#define SkTHash_DEFINED
10
halcanary038cb5e2015-03-25 10:22:53 -070011#include "SkChecksum.h"
mtklein979e0ea2015-02-12 13:20:08 -080012#include "SkTypes.h"
13#include "SkTemplates.h"
Mike Klein79aea6a2018-06-11 10:45:26 -040014#include <new>
mtklein979e0ea2015-02-12 13:20:08 -080015
16// Before trying to use SkTHashTable, look below to see if SkTHashMap or SkTHashSet works for you.
17// They're easier to use, usually perform the same, and have fewer sharp edges.
18
19// T and K are treated as ordinary copyable C++ types.
20// Traits must have:
21// - static K GetKey(T)
22// - static uint32_t Hash(K)
23// If the key is large and stored inside T, you may want to make K a const&.
24// Similarly, if T is large you might want it to be a pointer.
25template <typename T, typename K, typename Traits = T>
Hal Canary725d5ad2018-06-14 15:54:29 -040026class SkTHashTable {
mtklein979e0ea2015-02-12 13:20:08 -080027public:
Herb Derbyacef51f2016-12-14 14:20:08 -050028 SkTHashTable() : fCount(0), fCapacity(0) {}
Hal Canary725d5ad2018-06-14 15:54:29 -040029 SkTHashTable(SkTHashTable&& other)
30 : fCount(other.fCount)
31 , fCapacity(other.fCapacity)
32 , fSlots(std::move(other.fSlots)) { other.fCount = other.fCapacity = 0; }
33
34 SkTHashTable& operator=(SkTHashTable&& other) {
35 if (this != &other) {
36 this->~SkTHashTable();
37 new (this) SkTHashTable(std::move(other));
38 }
39 return *this;
40 }
41
42 SkTHashTable(const SkTHashTable&) = delete;
43 SkTHashTable& operator=(const SkTHashTable&) = delete;
mtklein979e0ea2015-02-12 13:20:08 -080044
mtklein2aa1f7e2015-02-20 12:35:32 -080045 // Clear the table.
Hal Canary725d5ad2018-06-14 15:54:29 -040046 void reset() { *this = SkTHashTable(); }
mtklein2aa1f7e2015-02-20 12:35:32 -080047
mtklein979e0ea2015-02-12 13:20:08 -080048 // How many entries are in the table?
49 int count() const { return fCount; }
50
mtklein469a3fe2015-08-07 09:33:37 -070051 // Approximately how many bytes of memory do we use beyond sizeof(*this)?
52 size_t approxBytesUsed() const { return fCapacity * sizeof(Slot); }
53
mtklein979e0ea2015-02-12 13:20:08 -080054 // !!!!!!!!!!!!!!!!! CAUTION !!!!!!!!!!!!!!!!!
55 // set(), find() and foreach() all allow mutable access to table entries.
56 // If you change an entry so that it no longer has the same key, all hell
57 // will break loose. Do not do that!
58 //
59 // Please prefer to use SkTHashMap or SkTHashSet, which do not have this danger.
60
61 // The pointers returned by set() and find() are valid only until the next call to set().
62 // The pointers you receive in foreach() are only valid for its duration.
63
64 // Copy val into the hash table, returning a pointer to the copy now in the table.
65 // If there already is an entry in the table with the same key, we overwrite it.
Mike Klein6b00a072016-12-15 15:13:13 -050066 T* set(T val) {
Herb Derbyacef51f2016-12-14 14:20:08 -050067 if (4 * fCount >= 3 * fCapacity) {
mtklein979e0ea2015-02-12 13:20:08 -080068 this->resize(fCapacity > 0 ? fCapacity * 2 : 4);
69 }
Mike Kleindb402ca2016-12-13 12:46:05 -050070 return this->uncheckedSet(std::move(val));
mtklein979e0ea2015-02-12 13:20:08 -080071 }
72
Herb Derbyacef51f2016-12-14 14:20:08 -050073 // If there is an entry in the table with this key, return a pointer to it. If not, null.
fmalita79ca0812015-02-12 17:32:49 -080074 T* find(const K& key) const {
mtklein979e0ea2015-02-12 13:20:08 -080075 uint32_t hash = Hash(key);
76 int index = hash & (fCapacity-1);
77 for (int n = 0; n < fCapacity; n++) {
78 Slot& s = fSlots[index];
79 if (s.empty()) {
Herb Derbyacef51f2016-12-14 14:20:08 -050080 return nullptr;
mtklein979e0ea2015-02-12 13:20:08 -080081 }
Herb Derbyacef51f2016-12-14 14:20:08 -050082 if (hash == s.hash && key == Traits::GetKey(s.val)) {
mtklein979e0ea2015-02-12 13:20:08 -080083 return &s.val;
84 }
Herb Derbyacef51f2016-12-14 14:20:08 -050085 index = this->next(index);
mtklein979e0ea2015-02-12 13:20:08 -080086 }
87 SkASSERT(fCapacity == 0);
Herb Derbyacef51f2016-12-14 14:20:08 -050088 return nullptr;
mtklein979e0ea2015-02-12 13:20:08 -080089 }
90
mtklein33d73c32015-04-21 06:53:56 -070091 // Remove the value with this key from the hash table.
92 void remove(const K& key) {
93 SkASSERT(this->find(key));
94
95 uint32_t hash = Hash(key);
96 int index = hash & (fCapacity-1);
97 for (int n = 0; n < fCapacity; n++) {
98 Slot& s = fSlots[index];
99 SkASSERT(!s.empty());
Herb Derbyacef51f2016-12-14 14:20:08 -0500100 if (hash == s.hash && key == Traits::GetKey(s.val)) {
mtklein33d73c32015-04-21 06:53:56 -0700101 fCount--;
Herb Derbyacef51f2016-12-14 14:20:08 -0500102 break;
mtklein33d73c32015-04-21 06:53:56 -0700103 }
Herb Derbyacef51f2016-12-14 14:20:08 -0500104 index = this->next(index);
mtklein33d73c32015-04-21 06:53:56 -0700105 }
Herb Derbyacef51f2016-12-14 14:20:08 -0500106
107 // Rearrange elements to restore the invariants for linear probing.
108 for (;;) {
109 Slot& emptySlot = fSlots[index];
110 int emptyIndex = index;
Herb Derbyacef51f2016-12-14 14:20:08 -0500111 int originalIndex;
112 // Look for an element that can be moved into the empty slot.
113 // If the empty slot is in between where an element landed, and its native slot, then
114 // move it to the empty slot. Don't move it if its native slot is in between where
115 // the element landed and the empty slot.
116 // [native] <= [empty] < [candidate] == GOOD, can move candidate to empty slot
117 // [empty] < [native] < [candidate] == BAD, need to leave candidate where it is
118 do {
119 index = this->next(index);
120 Slot& s = fSlots[index];
Florin Malita053730d2017-03-10 11:51:07 -0500121 if (s.empty()) {
122 // We're done shuffling elements around. Clear the last empty slot.
123 emptySlot = Slot();
124 return;
125 }
Herb Derbyacef51f2016-12-14 14:20:08 -0500126 originalIndex = s.hash & (fCapacity - 1);
127 } while ((index <= originalIndex && originalIndex < emptyIndex)
128 || (originalIndex < emptyIndex && emptyIndex < index)
129 || (emptyIndex < index && index <= originalIndex));
130 // Move the element to the empty slot.
131 Slot& moveFrom = fSlots[index];
132 emptySlot = std::move(moveFrom);
133 }
mtklein33d73c32015-04-21 06:53:56 -0700134 }
135
mtklein979e0ea2015-02-12 13:20:08 -0800136 // Call fn on every entry in the table. You may mutate the entries, but be very careful.
mtklein02f46cf2015-03-20 13:48:42 -0700137 template <typename Fn> // f(T*)
138 void foreach(Fn&& fn) {
mtklein979e0ea2015-02-12 13:20:08 -0800139 for (int i = 0; i < fCapacity; i++) {
Herb Derbyacef51f2016-12-14 14:20:08 -0500140 if (!fSlots[i].empty()) {
mtklein02f46cf2015-03-20 13:48:42 -0700141 fn(&fSlots[i].val);
142 }
143 }
144 }
145
146 // Call fn on every entry in the table. You may not mutate anything.
147 template <typename Fn> // f(T) or f(const T&)
148 void foreach(Fn&& fn) const {
149 for (int i = 0; i < fCapacity; i++) {
Herb Derbyacef51f2016-12-14 14:20:08 -0500150 if (!fSlots[i].empty()) {
mtklein02f46cf2015-03-20 13:48:42 -0700151 fn(fSlots[i].val);
mtklein979e0ea2015-02-12 13:20:08 -0800152 }
153 }
154 }
155
156private:
Mike Kleindb402ca2016-12-13 12:46:05 -0500157 T* uncheckedSet(T&& val) {
fmalita79ca0812015-02-12 17:32:49 -0800158 const K& key = Traits::GetKey(val);
mtklein979e0ea2015-02-12 13:20:08 -0800159 uint32_t hash = Hash(key);
160 int index = hash & (fCapacity-1);
161 for (int n = 0; n < fCapacity; n++) {
162 Slot& s = fSlots[index];
Herb Derbyacef51f2016-12-14 14:20:08 -0500163 if (s.empty()) {
mtklein979e0ea2015-02-12 13:20:08 -0800164 // New entry.
Mike Kleindb402ca2016-12-13 12:46:05 -0500165 s.val = std::move(val);
mtklein979e0ea2015-02-12 13:20:08 -0800166 s.hash = hash;
167 fCount++;
168 return &s.val;
169 }
170 if (hash == s.hash && key == Traits::GetKey(s.val)) {
171 // Overwrite previous entry.
fmalita79ca0812015-02-12 17:32:49 -0800172 // Note: this triggers extra copies when adding the same value repeatedly.
Mike Kleindb402ca2016-12-13 12:46:05 -0500173 s.val = std::move(val);
mtklein979e0ea2015-02-12 13:20:08 -0800174 return &s.val;
175 }
Herb Derbyacef51f2016-12-14 14:20:08 -0500176
177 index = this->next(index);
mtklein979e0ea2015-02-12 13:20:08 -0800178 }
179 SkASSERT(false);
Herb Derbyacef51f2016-12-14 14:20:08 -0500180 return nullptr;
mtklein979e0ea2015-02-12 13:20:08 -0800181 }
182
183 void resize(int capacity) {
184 int oldCapacity = fCapacity;
185 SkDEBUGCODE(int oldCount = fCount);
186
Herb Derbyacef51f2016-12-14 14:20:08 -0500187 fCount = 0;
mtklein979e0ea2015-02-12 13:20:08 -0800188 fCapacity = capacity;
Hal Canary67362362018-04-24 13:58:37 -0400189 SkAutoTArray<Slot> oldSlots = std::move(fSlots);
190 fSlots = SkAutoTArray<Slot>(capacity);
mtklein979e0ea2015-02-12 13:20:08 -0800191
192 for (int i = 0; i < oldCapacity; i++) {
Mike Kleindb402ca2016-12-13 12:46:05 -0500193 Slot& s = oldSlots[i];
Herb Derbyacef51f2016-12-14 14:20:08 -0500194 if (!s.empty()) {
Mike Kleindb402ca2016-12-13 12:46:05 -0500195 this->uncheckedSet(std::move(s.val));
mtklein979e0ea2015-02-12 13:20:08 -0800196 }
197 }
198 SkASSERT(fCount == oldCount);
199 }
200
Herb Derbyacef51f2016-12-14 14:20:08 -0500201 int next(int index) const {
202 index--;
203 if (index < 0) { index += fCapacity; }
204 return index;
mtklein979e0ea2015-02-12 13:20:08 -0800205 }
206
fmalita79ca0812015-02-12 17:32:49 -0800207 static uint32_t Hash(const K& key) {
mtklein979e0ea2015-02-12 13:20:08 -0800208 uint32_t hash = Traits::Hash(key);
Herb Derbyacef51f2016-12-14 14:20:08 -0500209 return hash ? hash : 1; // We reserve hash 0 to mark empty.
mtklein979e0ea2015-02-12 13:20:08 -0800210 }
211
212 struct Slot {
213 Slot() : hash(0) {}
Herb Derbyacef51f2016-12-14 14:20:08 -0500214 Slot(T&& v, uint32_t h) : val(std::move(v)), hash(h) {}
215 Slot(Slot&& o) { *this = std::move(o); }
216 Slot& operator=(Slot&& o) {
217 val = std::move(o.val);
218 hash = o.hash;
219 return *this;
220 }
mtklein33d73c32015-04-21 06:53:56 -0700221
Herb Derbyacef51f2016-12-14 14:20:08 -0500222 bool empty() const { return this->hash == 0; }
mtklein979e0ea2015-02-12 13:20:08 -0800223
Herb Derbyacef51f2016-12-14 14:20:08 -0500224 T val;
mtklein979e0ea2015-02-12 13:20:08 -0800225 uint32_t hash;
226 };
227
Herb Derbyacef51f2016-12-14 14:20:08 -0500228 int fCount, fCapacity;
mtklein979e0ea2015-02-12 13:20:08 -0800229 SkAutoTArray<Slot> fSlots;
230};
231
232// Maps K->V. A more user-friendly wrapper around SkTHashTable, suitable for most use cases.
233// K and V are treated as ordinary copyable C++ types, with no assumed relationship between the two.
mtkleinc8d1dd42015-10-15 12:23:01 -0700234template <typename K, typename V, typename HashK = SkGoodHash>
Hal Canary725d5ad2018-06-14 15:54:29 -0400235class SkTHashMap {
mtklein979e0ea2015-02-12 13:20:08 -0800236public:
237 SkTHashMap() {}
Hal Canary725d5ad2018-06-14 15:54:29 -0400238 SkTHashMap(SkTHashMap&&) = default;
239 SkTHashMap(const SkTHashMap&) = delete;
240 SkTHashMap& operator=(SkTHashMap&&) = default;
241 SkTHashMap& operator=(const SkTHashMap&) = delete;
mtklein979e0ea2015-02-12 13:20:08 -0800242
mtklein2aa1f7e2015-02-20 12:35:32 -0800243 // Clear the map.
244 void reset() { fTable.reset(); }
245
mtklein979e0ea2015-02-12 13:20:08 -0800246 // How many key/value pairs are in the table?
247 int count() const { return fTable.count(); }
248
mtklein469a3fe2015-08-07 09:33:37 -0700249 // Approximately how many bytes of memory do we use beyond sizeof(*this)?
250 size_t approxBytesUsed() const { return fTable.approxBytesUsed(); }
251
mtklein979e0ea2015-02-12 13:20:08 -0800252 // N.B. The pointers returned by set() and find() are valid only until the next call to set().
253
254 // Set key to val in the table, replacing any previous value with the same key.
255 // We copy both key and val, and return a pointer to the value copy now in the table.
Mike Klein6b00a072016-12-15 15:13:13 -0500256 V* set(K key, V val) {
Mike Kleindb402ca2016-12-13 12:46:05 -0500257 Pair* out = fTable.set({std::move(key), std::move(val)});
mtklein979e0ea2015-02-12 13:20:08 -0800258 return &out->val;
259 }
260
261 // If there is key/value entry in the table with this key, return a pointer to the value.
Herb Derbyacef51f2016-12-14 14:20:08 -0500262 // If not, return null.
fmalita79ca0812015-02-12 17:32:49 -0800263 V* find(const K& key) const {
mtklein979e0ea2015-02-12 13:20:08 -0800264 if (Pair* p = fTable.find(key)) {
265 return &p->val;
266 }
Herb Derbyacef51f2016-12-14 14:20:08 -0500267 return nullptr;
mtklein979e0ea2015-02-12 13:20:08 -0800268 }
269
mtklein33d73c32015-04-21 06:53:56 -0700270 // Remove the key/value entry in the table with this key.
271 void remove(const K& key) {
272 SkASSERT(this->find(key));
273 fTable.remove(key);
274 }
275
mtklein979e0ea2015-02-12 13:20:08 -0800276 // Call fn on every key/value pair in the table. You may mutate the value but not the key.
mtklein02f46cf2015-03-20 13:48:42 -0700277 template <typename Fn> // f(K, V*) or f(const K&, V*)
278 void foreach(Fn&& fn) {
279 fTable.foreach([&fn](Pair* p){ fn(p->key, &p->val); });
280 }
281
282 // Call fn on every key/value pair in the table. You may not mutate anything.
283 template <typename Fn> // f(K, V), f(const K&, V), f(K, const V&) or f(const K&, const V&).
284 void foreach(Fn&& fn) const {
285 fTable.foreach([&fn](const Pair& p){ fn(p.key, p.val); });
286 }
mtklein979e0ea2015-02-12 13:20:08 -0800287
288private:
289 struct Pair {
290 K key;
291 V val;
fmalita79ca0812015-02-12 17:32:49 -0800292 static const K& GetKey(const Pair& p) { return p.key; }
mtkleinc8d1dd42015-10-15 12:23:01 -0700293 static uint32_t Hash(const K& key) { return HashK()(key); }
mtklein979e0ea2015-02-12 13:20:08 -0800294 };
mtklein979e0ea2015-02-12 13:20:08 -0800295
296 SkTHashTable<Pair, K> fTable;
297};
298
Brian Salomon8fe24272017-07-07 12:56:11 -0400299// A set of T. T is treated as an ordinary copyable C++ type.
mtkleinc8d1dd42015-10-15 12:23:01 -0700300template <typename T, typename HashT = SkGoodHash>
Hal Canary725d5ad2018-06-14 15:54:29 -0400301class SkTHashSet {
mtklein979e0ea2015-02-12 13:20:08 -0800302public:
303 SkTHashSet() {}
Hal Canary725d5ad2018-06-14 15:54:29 -0400304 SkTHashSet(SkTHashSet&&) = default;
305 SkTHashSet(const SkTHashSet&) = delete;
306 SkTHashSet& operator=(SkTHashSet&&) = default;
307 SkTHashSet& operator=(const SkTHashSet&) = delete;
mtklein979e0ea2015-02-12 13:20:08 -0800308
mtklein2aa1f7e2015-02-20 12:35:32 -0800309 // Clear the set.
310 void reset() { fTable.reset(); }
311
mtklein979e0ea2015-02-12 13:20:08 -0800312 // How many items are in the set?
313 int count() const { return fTable.count(); }
314
mtklein469a3fe2015-08-07 09:33:37 -0700315 // Approximately how many bytes of memory do we use beyond sizeof(*this)?
316 size_t approxBytesUsed() const { return fTable.approxBytesUsed(); }
317
mtklein979e0ea2015-02-12 13:20:08 -0800318 // Copy an item into the set.
Mike Klein6b00a072016-12-15 15:13:13 -0500319 void add(T item) { fTable.set(std::move(item)); }
mtklein979e0ea2015-02-12 13:20:08 -0800320
321 // Is this item in the set?
mtkleinfb8307c2015-04-01 11:21:27 -0700322 bool contains(const T& item) const { return SkToBool(this->find(item)); }
323
324 // If an item equal to this is in the set, return a pointer to it, otherwise null.
325 // This pointer remains valid until the next call to add().
326 const T* find(const T& item) const { return fTable.find(item); }
mtklein979e0ea2015-02-12 13:20:08 -0800327
mtklein33d73c32015-04-21 06:53:56 -0700328 // Remove the item in the set equal to this.
329 void remove(const T& item) {
330 SkASSERT(this->contains(item));
331 fTable.remove(item);
332 }
333
halcanarybe27a112015-04-01 13:31:19 -0700334 // Call fn on every item in the set. You may not mutate anything.
335 template <typename Fn> // f(T), f(const T&)
336 void foreach (Fn&& fn) const {
mtklein33d73c32015-04-21 06:53:56 -0700337 fTable.foreach(fn);
halcanarybe27a112015-04-01 13:31:19 -0700338 }
339
mtklein979e0ea2015-02-12 13:20:08 -0800340private:
341 struct Traits {
fmalita79ca0812015-02-12 17:32:49 -0800342 static const T& GetKey(const T& item) { return item; }
mtkleinc8d1dd42015-10-15 12:23:01 -0700343 static uint32_t Hash(const T& item) { return HashT()(item); }
mtklein979e0ea2015-02-12 13:20:08 -0800344 };
345 SkTHashTable<T, T, Traits> fTable;
346};
347
348#endif//SkTHash_DEFINED