blob: 2388905c38c69c2aa2dbd4d887b1a2b6031f1f76 [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"
14
15// Before trying to use SkTHashTable, look below to see if SkTHashMap or SkTHashSet works for you.
16// They're easier to use, usually perform the same, and have fewer sharp edges.
17
18// T and K are treated as ordinary copyable C++ types.
19// Traits must have:
20// - static K GetKey(T)
21// - static uint32_t Hash(K)
22// If the key is large and stored inside T, you may want to make K a const&.
23// Similarly, if T is large you might want it to be a pointer.
24template <typename T, typename K, typename Traits = T>
25class SkTHashTable : SkNoncopyable {
26public:
Herb Derbyacef51f2016-12-14 14:20:08 -050027 SkTHashTable() : fCount(0), fCapacity(0) {}
mtklein979e0ea2015-02-12 13:20:08 -080028
mtklein2aa1f7e2015-02-20 12:35:32 -080029 // Clear the table.
30 void reset() {
31 this->~SkTHashTable();
halcanary385fe4d2015-08-26 13:07:48 -070032 new (this) SkTHashTable;
mtklein2aa1f7e2015-02-20 12:35:32 -080033 }
34
mtklein979e0ea2015-02-12 13:20:08 -080035 // How many entries are in the table?
36 int count() const { return fCount; }
37
mtklein469a3fe2015-08-07 09:33:37 -070038 // Approximately how many bytes of memory do we use beyond sizeof(*this)?
39 size_t approxBytesUsed() const { return fCapacity * sizeof(Slot); }
40
mtklein979e0ea2015-02-12 13:20:08 -080041 // !!!!!!!!!!!!!!!!! CAUTION !!!!!!!!!!!!!!!!!
42 // set(), find() and foreach() all allow mutable access to table entries.
43 // If you change an entry so that it no longer has the same key, all hell
44 // will break loose. Do not do that!
45 //
46 // Please prefer to use SkTHashMap or SkTHashSet, which do not have this danger.
47
48 // The pointers returned by set() and find() are valid only until the next call to set().
49 // The pointers you receive in foreach() are only valid for its duration.
50
51 // Copy val into the hash table, returning a pointer to the copy now in the table.
52 // If there already is an entry in the table with the same key, we overwrite it.
Mike Klein6b00a072016-12-15 15:13:13 -050053 T* set(T val) {
Herb Derbyacef51f2016-12-14 14:20:08 -050054 if (4 * fCount >= 3 * fCapacity) {
mtklein979e0ea2015-02-12 13:20:08 -080055 this->resize(fCapacity > 0 ? fCapacity * 2 : 4);
56 }
Mike Kleindb402ca2016-12-13 12:46:05 -050057 return this->uncheckedSet(std::move(val));
mtklein979e0ea2015-02-12 13:20:08 -080058 }
59
Herb Derbyacef51f2016-12-14 14:20:08 -050060 // 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 -080061 T* find(const K& key) const {
mtklein979e0ea2015-02-12 13:20:08 -080062 uint32_t hash = Hash(key);
63 int index = hash & (fCapacity-1);
64 for (int n = 0; n < fCapacity; n++) {
65 Slot& s = fSlots[index];
66 if (s.empty()) {
Herb Derbyacef51f2016-12-14 14:20:08 -050067 return nullptr;
mtklein979e0ea2015-02-12 13:20:08 -080068 }
Herb Derbyacef51f2016-12-14 14:20:08 -050069 if (hash == s.hash && key == Traits::GetKey(s.val)) {
mtklein979e0ea2015-02-12 13:20:08 -080070 return &s.val;
71 }
Herb Derbyacef51f2016-12-14 14:20:08 -050072 index = this->next(index);
mtklein979e0ea2015-02-12 13:20:08 -080073 }
74 SkASSERT(fCapacity == 0);
Herb Derbyacef51f2016-12-14 14:20:08 -050075 return nullptr;
mtklein979e0ea2015-02-12 13:20:08 -080076 }
77
mtklein33d73c32015-04-21 06:53:56 -070078 // Remove the value with this key from the hash table.
79 void remove(const K& key) {
80 SkASSERT(this->find(key));
81
82 uint32_t hash = Hash(key);
83 int index = hash & (fCapacity-1);
84 for (int n = 0; n < fCapacity; n++) {
85 Slot& s = fSlots[index];
86 SkASSERT(!s.empty());
Herb Derbyacef51f2016-12-14 14:20:08 -050087 if (hash == s.hash && key == Traits::GetKey(s.val)) {
mtklein33d73c32015-04-21 06:53:56 -070088 fCount--;
Herb Derbyacef51f2016-12-14 14:20:08 -050089 break;
mtklein33d73c32015-04-21 06:53:56 -070090 }
Herb Derbyacef51f2016-12-14 14:20:08 -050091 index = this->next(index);
mtklein33d73c32015-04-21 06:53:56 -070092 }
Herb Derbyacef51f2016-12-14 14:20:08 -050093
94 // Rearrange elements to restore the invariants for linear probing.
95 for (;;) {
96 Slot& emptySlot = fSlots[index];
97 int emptyIndex = index;
Herb Derbyacef51f2016-12-14 14:20:08 -050098 int originalIndex;
99 // Look for an element that can be moved into the empty slot.
100 // If the empty slot is in between where an element landed, and its native slot, then
101 // move it to the empty slot. Don't move it if its native slot is in between where
102 // the element landed and the empty slot.
103 // [native] <= [empty] < [candidate] == GOOD, can move candidate to empty slot
104 // [empty] < [native] < [candidate] == BAD, need to leave candidate where it is
105 do {
106 index = this->next(index);
107 Slot& s = fSlots[index];
Florin Malita053730d2017-03-10 11:51:07 -0500108 if (s.empty()) {
109 // We're done shuffling elements around. Clear the last empty slot.
110 emptySlot = Slot();
111 return;
112 }
Herb Derbyacef51f2016-12-14 14:20:08 -0500113 originalIndex = s.hash & (fCapacity - 1);
114 } while ((index <= originalIndex && originalIndex < emptyIndex)
115 || (originalIndex < emptyIndex && emptyIndex < index)
116 || (emptyIndex < index && index <= originalIndex));
117 // Move the element to the empty slot.
118 Slot& moveFrom = fSlots[index];
119 emptySlot = std::move(moveFrom);
120 }
mtklein33d73c32015-04-21 06:53:56 -0700121 }
122
mtklein979e0ea2015-02-12 13:20:08 -0800123 // Call fn on every entry in the table. You may mutate the entries, but be very careful.
mtklein02f46cf2015-03-20 13:48:42 -0700124 template <typename Fn> // f(T*)
125 void foreach(Fn&& fn) {
mtklein979e0ea2015-02-12 13:20:08 -0800126 for (int i = 0; i < fCapacity; i++) {
Herb Derbyacef51f2016-12-14 14:20:08 -0500127 if (!fSlots[i].empty()) {
mtklein02f46cf2015-03-20 13:48:42 -0700128 fn(&fSlots[i].val);
129 }
130 }
131 }
132
133 // Call fn on every entry in the table. You may not mutate anything.
134 template <typename Fn> // f(T) or f(const T&)
135 void foreach(Fn&& fn) const {
136 for (int i = 0; i < fCapacity; i++) {
Herb Derbyacef51f2016-12-14 14:20:08 -0500137 if (!fSlots[i].empty()) {
mtklein02f46cf2015-03-20 13:48:42 -0700138 fn(fSlots[i].val);
mtklein979e0ea2015-02-12 13:20:08 -0800139 }
140 }
141 }
142
143private:
Mike Kleindb402ca2016-12-13 12:46:05 -0500144 T* uncheckedSet(T&& val) {
fmalita79ca0812015-02-12 17:32:49 -0800145 const K& key = Traits::GetKey(val);
mtklein979e0ea2015-02-12 13:20:08 -0800146 uint32_t hash = Hash(key);
147 int index = hash & (fCapacity-1);
148 for (int n = 0; n < fCapacity; n++) {
149 Slot& s = fSlots[index];
Herb Derbyacef51f2016-12-14 14:20:08 -0500150 if (s.empty()) {
mtklein979e0ea2015-02-12 13:20:08 -0800151 // New entry.
Mike Kleindb402ca2016-12-13 12:46:05 -0500152 s.val = std::move(val);
mtklein979e0ea2015-02-12 13:20:08 -0800153 s.hash = hash;
154 fCount++;
155 return &s.val;
156 }
157 if (hash == s.hash && key == Traits::GetKey(s.val)) {
158 // Overwrite previous entry.
fmalita79ca0812015-02-12 17:32:49 -0800159 // Note: this triggers extra copies when adding the same value repeatedly.
Mike Kleindb402ca2016-12-13 12:46:05 -0500160 s.val = std::move(val);
mtklein979e0ea2015-02-12 13:20:08 -0800161 return &s.val;
162 }
Herb Derbyacef51f2016-12-14 14:20:08 -0500163
164 index = this->next(index);
mtklein979e0ea2015-02-12 13:20:08 -0800165 }
166 SkASSERT(false);
Herb Derbyacef51f2016-12-14 14:20:08 -0500167 return nullptr;
mtklein979e0ea2015-02-12 13:20:08 -0800168 }
169
170 void resize(int capacity) {
171 int oldCapacity = fCapacity;
172 SkDEBUGCODE(int oldCount = fCount);
173
Herb Derbyacef51f2016-12-14 14:20:08 -0500174 fCount = 0;
mtklein979e0ea2015-02-12 13:20:08 -0800175 fCapacity = capacity;
176 SkAutoTArray<Slot> oldSlots(capacity);
177 oldSlots.swap(fSlots);
178
179 for (int i = 0; i < oldCapacity; i++) {
Mike Kleindb402ca2016-12-13 12:46:05 -0500180 Slot& s = oldSlots[i];
Herb Derbyacef51f2016-12-14 14:20:08 -0500181 if (!s.empty()) {
Mike Kleindb402ca2016-12-13 12:46:05 -0500182 this->uncheckedSet(std::move(s.val));
mtklein979e0ea2015-02-12 13:20:08 -0800183 }
184 }
185 SkASSERT(fCount == oldCount);
186 }
187
Herb Derbyacef51f2016-12-14 14:20:08 -0500188 int next(int index) const {
189 index--;
190 if (index < 0) { index += fCapacity; }
191 return index;
mtklein979e0ea2015-02-12 13:20:08 -0800192 }
193
fmalita79ca0812015-02-12 17:32:49 -0800194 static uint32_t Hash(const K& key) {
mtklein979e0ea2015-02-12 13:20:08 -0800195 uint32_t hash = Traits::Hash(key);
Herb Derbyacef51f2016-12-14 14:20:08 -0500196 return hash ? hash : 1; // We reserve hash 0 to mark empty.
mtklein979e0ea2015-02-12 13:20:08 -0800197 }
198
199 struct Slot {
200 Slot() : hash(0) {}
Herb Derbyacef51f2016-12-14 14:20:08 -0500201 Slot(T&& v, uint32_t h) : val(std::move(v)), hash(h) {}
202 Slot(Slot&& o) { *this = std::move(o); }
203 Slot& operator=(Slot&& o) {
204 val = std::move(o.val);
205 hash = o.hash;
206 return *this;
207 }
mtklein33d73c32015-04-21 06:53:56 -0700208
Herb Derbyacef51f2016-12-14 14:20:08 -0500209 bool empty() const { return this->hash == 0; }
mtklein979e0ea2015-02-12 13:20:08 -0800210
Herb Derbyacef51f2016-12-14 14:20:08 -0500211 T val;
mtklein979e0ea2015-02-12 13:20:08 -0800212 uint32_t hash;
213 };
214
Herb Derbyacef51f2016-12-14 14:20:08 -0500215 int fCount, fCapacity;
mtklein979e0ea2015-02-12 13:20:08 -0800216 SkAutoTArray<Slot> fSlots;
217};
218
219// Maps K->V. A more user-friendly wrapper around SkTHashTable, suitable for most use cases.
220// K and V are treated as ordinary copyable C++ types, with no assumed relationship between the two.
mtkleinc8d1dd42015-10-15 12:23:01 -0700221template <typename K, typename V, typename HashK = SkGoodHash>
mtklein979e0ea2015-02-12 13:20:08 -0800222class SkTHashMap : SkNoncopyable {
223public:
224 SkTHashMap() {}
225
mtklein2aa1f7e2015-02-20 12:35:32 -0800226 // Clear the map.
227 void reset() { fTable.reset(); }
228
mtklein979e0ea2015-02-12 13:20:08 -0800229 // How many key/value pairs are in the table?
230 int count() const { return fTable.count(); }
231
mtklein469a3fe2015-08-07 09:33:37 -0700232 // Approximately how many bytes of memory do we use beyond sizeof(*this)?
233 size_t approxBytesUsed() const { return fTable.approxBytesUsed(); }
234
mtklein979e0ea2015-02-12 13:20:08 -0800235 // N.B. The pointers returned by set() and find() are valid only until the next call to set().
236
237 // Set key to val in the table, replacing any previous value with the same key.
238 // 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 -0500239 V* set(K key, V val) {
Mike Kleindb402ca2016-12-13 12:46:05 -0500240 Pair* out = fTable.set({std::move(key), std::move(val)});
mtklein979e0ea2015-02-12 13:20:08 -0800241 return &out->val;
242 }
243
244 // 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 -0500245 // If not, return null.
fmalita79ca0812015-02-12 17:32:49 -0800246 V* find(const K& key) const {
mtklein979e0ea2015-02-12 13:20:08 -0800247 if (Pair* p = fTable.find(key)) {
248 return &p->val;
249 }
Herb Derbyacef51f2016-12-14 14:20:08 -0500250 return nullptr;
mtklein979e0ea2015-02-12 13:20:08 -0800251 }
252
mtklein33d73c32015-04-21 06:53:56 -0700253 // Remove the key/value entry in the table with this key.
254 void remove(const K& key) {
255 SkASSERT(this->find(key));
256 fTable.remove(key);
257 }
258
mtklein979e0ea2015-02-12 13:20:08 -0800259 // 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 -0700260 template <typename Fn> // f(K, V*) or f(const K&, V*)
261 void foreach(Fn&& fn) {
262 fTable.foreach([&fn](Pair* p){ fn(p->key, &p->val); });
263 }
264
265 // Call fn on every key/value pair in the table. You may not mutate anything.
266 template <typename Fn> // f(K, V), f(const K&, V), f(K, const V&) or f(const K&, const V&).
267 void foreach(Fn&& fn) const {
268 fTable.foreach([&fn](const Pair& p){ fn(p.key, p.val); });
269 }
mtklein979e0ea2015-02-12 13:20:08 -0800270
271private:
272 struct Pair {
273 K key;
274 V val;
fmalita79ca0812015-02-12 17:32:49 -0800275 static const K& GetKey(const Pair& p) { return p.key; }
mtkleinc8d1dd42015-10-15 12:23:01 -0700276 static uint32_t Hash(const K& key) { return HashK()(key); }
mtklein979e0ea2015-02-12 13:20:08 -0800277 };
mtklein979e0ea2015-02-12 13:20:08 -0800278
279 SkTHashTable<Pair, K> fTable;
280};
281
282// A set of T. T is treated as an ordiary copyable C++ type.
mtkleinc8d1dd42015-10-15 12:23:01 -0700283template <typename T, typename HashT = SkGoodHash>
mtklein979e0ea2015-02-12 13:20:08 -0800284class SkTHashSet : SkNoncopyable {
285public:
286 SkTHashSet() {}
287
mtklein2aa1f7e2015-02-20 12:35:32 -0800288 // Clear the set.
289 void reset() { fTable.reset(); }
290
mtklein979e0ea2015-02-12 13:20:08 -0800291 // How many items are in the set?
292 int count() const { return fTable.count(); }
293
mtklein469a3fe2015-08-07 09:33:37 -0700294 // Approximately how many bytes of memory do we use beyond sizeof(*this)?
295 size_t approxBytesUsed() const { return fTable.approxBytesUsed(); }
296
mtklein979e0ea2015-02-12 13:20:08 -0800297 // Copy an item into the set.
Mike Klein6b00a072016-12-15 15:13:13 -0500298 void add(T item) { fTable.set(std::move(item)); }
mtklein979e0ea2015-02-12 13:20:08 -0800299
300 // Is this item in the set?
mtkleinfb8307c2015-04-01 11:21:27 -0700301 bool contains(const T& item) const { return SkToBool(this->find(item)); }
302
303 // If an item equal to this is in the set, return a pointer to it, otherwise null.
304 // This pointer remains valid until the next call to add().
305 const T* find(const T& item) const { return fTable.find(item); }
mtklein979e0ea2015-02-12 13:20:08 -0800306
mtklein33d73c32015-04-21 06:53:56 -0700307 // Remove the item in the set equal to this.
308 void remove(const T& item) {
309 SkASSERT(this->contains(item));
310 fTable.remove(item);
311 }
312
halcanarybe27a112015-04-01 13:31:19 -0700313 // Call fn on every item in the set. You may not mutate anything.
314 template <typename Fn> // f(T), f(const T&)
315 void foreach (Fn&& fn) const {
mtklein33d73c32015-04-21 06:53:56 -0700316 fTable.foreach(fn);
halcanarybe27a112015-04-01 13:31:19 -0700317 }
318
mtklein979e0ea2015-02-12 13:20:08 -0800319private:
320 struct Traits {
fmalita79ca0812015-02-12 17:32:49 -0800321 static const T& GetKey(const T& item) { return item; }
mtkleinc8d1dd42015-10-15 12:23:01 -0700322 static uint32_t Hash(const T& item) { return HashT()(item); }
mtklein979e0ea2015-02-12 13:20:08 -0800323 };
324 SkTHashTable<T, T, Traits> fTable;
325};
326
327#endif//SkTHash_DEFINED