summaryrefslogtreecommitdiff
path: root/lib/esan/esan_hashtable.h
blob: 7bd8297404003db120715b2bd47a7fd55973de8f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
//===-- esan_hashtable.h ----------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of EfficiencySanitizer, a family of performance tuners.
//
// Generic resizing hashtable.
//===----------------------------------------------------------------------===//

#include "sanitizer_common/sanitizer_allocator_internal.h"
#include "sanitizer_common/sanitizer_internal_defs.h"
#include "sanitizer_common/sanitizer_mutex.h"
#include <stddef.h>

namespace __esan {

//===----------------------------------------------------------------------===//
// Default hash and comparison functions
//===----------------------------------------------------------------------===//

template <typename T> struct DefaultHash {
  size_t operator()(const T &Key) const {
    return (size_t)Key;
  }
};

template <typename T> struct DefaultEqual {
  bool operator()(const T &Key1, const T &Key2) const {
    return Key1 == Key2;
  }
};

//===----------------------------------------------------------------------===//
// HashTable declaration
//===----------------------------------------------------------------------===//

// A simple resizing and mutex-locked hashtable.
//
// If the default hash functor is used, KeyTy must have an operator size_t().
// If the default comparison functor is used, KeyTy must have an operator ==.
//
// By default all operations are internally-synchronized with a mutex, with no
// synchronization for payloads once hashtable functions return.  If
// ExternalLock is set to true, the caller should call the lock() and unlock()
// routines around all hashtable operations and subsequent manipulation of
// payloads.
template <typename KeyTy, typename DataTy, bool ExternalLock = false,
          typename HashFuncTy = DefaultHash<KeyTy>,
          typename EqualFuncTy = DefaultEqual<KeyTy> >
class HashTable {
public:
  // InitialCapacity must be a power of 2.
  // ResizeFactor must be between 1 and 99 and indicates the
  // maximum percentage full that the table should ever be.
  HashTable(u32 InitialCapacity = 2048, u32 ResizeFactor = 70);
  ~HashTable();
  bool lookup(const KeyTy &Key, DataTy &Payload); // Const except for Mutex.
  bool add(const KeyTy &Key, const DataTy &Payload);
  bool remove(const KeyTy &Key);
  u32 size(); // Const except for Mutex.
  // If the table is internally-synchronized, this lock must not be held
  // while a hashtable function is called as it will deadlock: the lock
  // is not recursive.  This is meant for use with externally-synchronized
  // tables or with an iterator.
  void lock();
  void unlock();

private:
  struct HashEntry {
    KeyTy Key;
    DataTy Payload;
    HashEntry *Next;
  };

public:
  struct HashPair {
    HashPair(KeyTy Key, DataTy Data) : Key(Key), Data(Data) {}
    KeyTy Key;
    DataTy Data;
  };

  // This iterator does not perform any synchronization.
  // It expects the caller to lock the table across the whole iteration.
  // Calling HashTable functions while using the iterator is not supported.
  // The iterator returns copies of the keys and data.
  class iterator {
  public:
    iterator(
        HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy> *Table);
    iterator(const iterator &Src) = default;
    iterator &operator=(const iterator &Src) = default;
    HashPair operator*();
    iterator &operator++();
    iterator &operator++(int);
    bool operator==(const iterator &Cmp) const;
    bool operator!=(const iterator &Cmp) const;

  private:
    iterator(
        HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy> *Table,
        int Idx);
    friend HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>;
    HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy> *Table;
    int Idx;
    HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::HashEntry
        *Entry;
  };

  // No erase or insert iterator supported
  iterator begin();
  iterator end();

private:
  void resize();

  HashEntry **Table;
  u32 Capacity;
  u32 Entries;
  const u32 ResizeFactor;
  BlockingMutex Mutex;
  const HashFuncTy HashFunc;
  const EqualFuncTy EqualFunc;
};

//===----------------------------------------------------------------------===//
// Hashtable implementation
//===----------------------------------------------------------------------===//

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::HashTable(
    u32 InitialCapacity, u32 ResizeFactor)
    : Capacity(InitialCapacity), Entries(0), ResizeFactor(ResizeFactor),
      HashFunc(HashFuncTy()), EqualFunc(EqualFuncTy()) {
  CHECK(IsPowerOfTwo(Capacity));
  CHECK(ResizeFactor >= 1 && ResizeFactor <= 99);
  Table = (HashEntry **)InternalAlloc(Capacity * sizeof(HashEntry *));
  internal_memset(Table, 0, Capacity * sizeof(HashEntry *));
}

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::~HashTable() {
  for (u32 i = 0; i < Capacity; ++i) {
    HashEntry *Entry = Table[i];
    while (Entry != nullptr) {
      HashEntry *Next = Entry->Next;
      Entry->Payload.~DataTy();
      InternalFree(Entry);
      Entry = Next;
    }
  }
  InternalFree(Table);
}

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
u32 HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::size() {
  u32 Res;
  if (!ExternalLock)
    Mutex.Lock();
  Res = Entries;
  if (!ExternalLock)
    Mutex.Unlock();
  return Res;
}

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
bool HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::lookup(
    const KeyTy &Key, DataTy &Payload) {
  if (!ExternalLock)
    Mutex.Lock();
  bool Found = false;
  size_t Hash = HashFunc(Key) % Capacity;
  HashEntry *Entry = Table[Hash];
  for (; Entry != nullptr; Entry = Entry->Next) {
    if (EqualFunc(Entry->Key, Key)) {
      Payload = Entry->Payload;
      Found = true;
      break;
    }
  }
  if (!ExternalLock)
    Mutex.Unlock();
  return Found;
}

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
void HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::resize() {
  if (!ExternalLock)
    Mutex.CheckLocked();
  size_t OldCapacity = Capacity;
  HashEntry **OldTable = Table;
  Capacity *= 2;
  Table = (HashEntry **)InternalAlloc(Capacity * sizeof(HashEntry *));
  internal_memset(Table, 0, Capacity * sizeof(HashEntry *));
  // Re-hash
  for (u32 i = 0; i < OldCapacity; ++i) {
    HashEntry *OldEntry = OldTable[i];
    while (OldEntry != nullptr) {
      HashEntry *Next = OldEntry->Next;
      size_t Hash = HashFunc(OldEntry->Key) % Capacity;
      OldEntry->Next = Table[Hash];
      Table[Hash] = OldEntry;
      OldEntry = Next;
    }
  }
}

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
bool HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::add(
    const KeyTy &Key, const DataTy &Payload) {
  if (!ExternalLock)
    Mutex.Lock();
  bool Exists = false;
  size_t Hash = HashFunc(Key) % Capacity;
  HashEntry *Entry = Table[Hash];
  for (; Entry != nullptr; Entry = Entry->Next) {
    if (EqualFunc(Entry->Key, Key)) {
      Exists = true;
      break;
    }
  }
  if (!Exists) {
    Entries++;
    if (Entries * 100 >= Capacity * ResizeFactor) {
      resize();
      Hash = HashFunc(Key) % Capacity;
    }
    HashEntry *Add = (HashEntry *)InternalAlloc(sizeof(*Add));
    Add->Key = Key;
    Add->Payload = Payload;
    Add->Next = Table[Hash];
    Table[Hash] = Add;
  }
  if (!ExternalLock)
    Mutex.Unlock();
  return !Exists;
}

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
bool HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::remove(
    const KeyTy &Key) {
  if (!ExternalLock)
    Mutex.Lock();
  bool Found = false;
  size_t Hash = HashFunc(Key) % Capacity;
  HashEntry *Entry = Table[Hash];
  HashEntry *Prev = nullptr;
  for (; Entry != nullptr; Prev = Entry, Entry = Entry->Next) {
    if (EqualFunc(Entry->Key, Key)) {
      Found = true;
      Entries--;
      if (Prev == nullptr)
        Table[Hash] = Entry->Next;
      else
        Prev->Next = Entry->Next;
      Entry->Payload.~DataTy();
      InternalFree(Entry);
      break;
    }
  }
  if (!ExternalLock)
    Mutex.Unlock();
  return Found;
}

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
void HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::lock() {
  Mutex.Lock();
}

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
void HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::unlock() {
  Mutex.Unlock();
}

//===----------------------------------------------------------------------===//
// Iterator implementation
//===----------------------------------------------------------------------===//

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::iterator::
    iterator(
        HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy> *Table)
    : Table(Table), Idx(-1), Entry(nullptr) {
  operator++();
}

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::iterator::
    iterator(
        HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy> *Table,
        int Idx)
    : Table(Table), Idx(Idx), Entry(nullptr) {
  CHECK(Idx >= (int)Table->Capacity); // Only used to create end().
}

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
typename HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy,
                   EqualFuncTy>::HashPair
    HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::iterator::
    operator*() {
  CHECK(Idx >= 0 && Idx < (int)Table->Capacity);
  CHECK(Entry != nullptr);
  return HashPair(Entry->Key, Entry->Payload);
}

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
typename HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy,
                   EqualFuncTy>::iterator &
    HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::iterator::
    operator++() {
  if (Entry != nullptr)
    Entry = Entry->Next;
  while (Entry == nullptr) {
    ++Idx;
    if (Idx >= (int)Table->Capacity)
      break; // At end().
    Entry = Table->Table[Idx];
  }
  return *this;
}

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
typename HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy,
                   EqualFuncTy>::iterator &
    HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::iterator::
    operator++(int) {
  iterator Temp(*this);
  operator++();
  return Temp;
}

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
bool HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::iterator::
operator==(const iterator &Cmp) const {
  return Cmp.Table == Table && Cmp.Idx == Idx && Cmp.Entry == Entry;
}

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
bool HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::iterator::
operator!=(const iterator &Cmp) const {
  return Cmp.Table != Table || Cmp.Idx != Idx || Cmp.Entry != Entry;
}

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
typename HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy,
                   EqualFuncTy>::iterator
HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::begin() {
  return iterator(this);
}

template <typename KeyTy, typename DataTy, bool ExternalLock,
          typename HashFuncTy, typename EqualFuncTy>
typename HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy,
                   EqualFuncTy>::iterator
HashTable<KeyTy, DataTy, ExternalLock, HashFuncTy, EqualFuncTy>::end() {
  return iterator(this, Capacity);
}

} // namespace __esan