1 /*
2  * Copyright 2006 The Android Open Source Project
3  *
4  * Hash table.  The dominant calls are add and lookup, with removals
5  * happening very infrequently.  We use probing, and don't worry much
6  * about tombstone removal.
7  */
8 #include <stdlib.h>
9 #include <assert.h>
10 
11 #define LOG_TAG "minzip"
12 #include "Log.h"
13 #include "Hash.h"
14 
15 /* table load factor, i.e. how full can it get before we resize */
16 //#define LOAD_NUMER  3       // 75%
17 //#define LOAD_DENOM  4
18 #define LOAD_NUMER  5       // 62.5%
19 #define LOAD_DENOM  8
20 //#define LOAD_NUMER  1       // 50%
21 //#define LOAD_DENOM  2
22 
23 /*
24  * Compute the capacity needed for a table to hold "size" elements.
25  */
mzHashSize(size_t size)26 size_t mzHashSize(size_t size) {
27     return (size * LOAD_DENOM) / LOAD_NUMER +1;
28 }
29 
30 /*
31  * Round up to the next highest power of 2.
32  *
33  * Found on http://graphics.stanford.edu/~seander/bithacks.html.
34  */
roundUpPower2(unsigned int val)35 unsigned int roundUpPower2(unsigned int val)
36 {
37     val--;
38     val |= val >> 1;
39     val |= val >> 2;
40     val |= val >> 4;
41     val |= val >> 8;
42     val |= val >> 16;
43     val++;
44 
45     return val;
46 }
47 
48 /*
49  * Create and initialize a hash table.
50  */
mzHashTableCreate(size_t initialSize,HashFreeFunc freeFunc)51 HashTable* mzHashTableCreate(size_t initialSize, HashFreeFunc freeFunc)
52 {
53     HashTable* pHashTable;
54 
55     assert(initialSize > 0);
56 
57     pHashTable = (HashTable*) malloc(sizeof(*pHashTable));
58     if (pHashTable == NULL)
59         return NULL;
60 
61     pHashTable->tableSize = roundUpPower2(initialSize);
62     pHashTable->numEntries = pHashTable->numDeadEntries = 0;
63     pHashTable->freeFunc = freeFunc;
64     pHashTable->pEntries =
65         (HashEntry*) calloc((size_t)pHashTable->tableSize, sizeof(HashTable));
66     if (pHashTable->pEntries == NULL) {
67         free(pHashTable);
68         return NULL;
69     }
70 
71     return pHashTable;
72 }
73 
74 /*
75  * Clear out all entries.
76  */
mzHashTableClear(HashTable * pHashTable)77 void mzHashTableClear(HashTable* pHashTable)
78 {
79     HashEntry* pEnt;
80     int i;
81 
82     pEnt = pHashTable->pEntries;
83     for (i = 0; i < pHashTable->tableSize; i++, pEnt++) {
84         if (pEnt->data == HASH_TOMBSTONE) {
85             // nuke entry
86             pEnt->data = NULL;
87         } else if (pEnt->data != NULL) {
88             // call free func then nuke entry
89             if (pHashTable->freeFunc != NULL)
90                 (*pHashTable->freeFunc)(pEnt->data);
91             pEnt->data = NULL;
92         }
93     }
94 
95     pHashTable->numEntries = 0;
96     pHashTable->numDeadEntries = 0;
97 }
98 
99 /*
100  * Free the table.
101  */
mzHashTableFree(HashTable * pHashTable)102 void mzHashTableFree(HashTable* pHashTable)
103 {
104     if (pHashTable == NULL)
105         return;
106     mzHashTableClear(pHashTable);
107     free(pHashTable->pEntries);
108     free(pHashTable);
109 }
110 
111 #ifndef NDEBUG
112 /*
113  * Count up the number of tombstone entries in the hash table.
114  */
countTombStones(HashTable * pHashTable)115 static int countTombStones(HashTable* pHashTable)
116 {
117     int i, count;
118 
119     for (count = i = 0; i < pHashTable->tableSize; i++) {
120         if (pHashTable->pEntries[i].data == HASH_TOMBSTONE)
121             count++;
122     }
123     return count;
124 }
125 #endif
126 
127 /*
128  * Resize a hash table.  We do this when adding an entry increased the
129  * size of the table beyond its comfy limit.
130  *
131  * This essentially requires re-inserting all elements into the new storage.
132  *
133  * If multiple threads can access the hash table, the table's lock should
134  * have been grabbed before issuing the "lookup+add" call that led to the
135  * resize, so we don't have a synchronization problem here.
136  */
resizeHash(HashTable * pHashTable,int newSize)137 static bool resizeHash(HashTable* pHashTable, int newSize)
138 {
139     HashEntry* pNewEntries;
140     int i;
141 
142     assert(countTombStones(pHashTable) == pHashTable->numDeadEntries);
143 
144     pNewEntries = (HashEntry*) calloc(newSize, sizeof(HashTable));
145     if (pNewEntries == NULL)
146         return false;
147 
148     for (i = 0; i < pHashTable->tableSize; i++) {
149         void* data = pHashTable->pEntries[i].data;
150         if (data != NULL && data != HASH_TOMBSTONE) {
151             int hashValue = pHashTable->pEntries[i].hashValue;
152             int newIdx;
153 
154             /* probe for new spot, wrapping around */
155             newIdx = hashValue & (newSize-1);
156             while (pNewEntries[newIdx].data != NULL)
157                 newIdx = (newIdx + 1) & (newSize-1);
158 
159             pNewEntries[newIdx].hashValue = hashValue;
160             pNewEntries[newIdx].data = data;
161         }
162     }
163 
164     free(pHashTable->pEntries);
165     pHashTable->pEntries = pNewEntries;
166     pHashTable->tableSize = newSize;
167     pHashTable->numDeadEntries = 0;
168 
169     assert(countTombStones(pHashTable) == 0);
170     return true;
171 }
172 
173 /*
174  * Look up an entry.
175  *
176  * We probe on collisions, wrapping around the table.
177  */
mzHashTableLookup(HashTable * pHashTable,unsigned int itemHash,void * item,HashCompareFunc cmpFunc,bool doAdd)178 void* mzHashTableLookup(HashTable* pHashTable, unsigned int itemHash, void* item,
179     HashCompareFunc cmpFunc, bool doAdd)
180 {
181     HashEntry* pEntry;
182     HashEntry* pEnd;
183     void* result = NULL;
184 
185     assert(pHashTable->tableSize > 0);
186     assert(item != HASH_TOMBSTONE);
187     assert(item != NULL);
188 
189     /* jump to the first entry and probe for a match */
190     pEntry = &pHashTable->pEntries[itemHash & (pHashTable->tableSize-1)];
191     pEnd = &pHashTable->pEntries[pHashTable->tableSize];
192     while (pEntry->data != NULL) {
193         if (pEntry->data != HASH_TOMBSTONE &&
194             pEntry->hashValue == itemHash &&
195             (*cmpFunc)(pEntry->data, item) == 0)
196         {
197             /* match */
198             break;
199         }
200 
201         pEntry++;
202         if (pEntry == pEnd) {     /* wrap around to start */
203             if (pHashTable->tableSize == 1)
204                 break;      /* edge case - single-entry table */
205             pEntry = pHashTable->pEntries;
206         }
207     }
208 
209     if (pEntry->data == NULL) {
210         if (doAdd) {
211             pEntry->hashValue = itemHash;
212             pEntry->data = item;
213             pHashTable->numEntries++;
214 
215             /*
216              * We've added an entry.  See if this brings us too close to full.
217              */
218             if ((pHashTable->numEntries+pHashTable->numDeadEntries) * LOAD_DENOM
219                 > pHashTable->tableSize * LOAD_NUMER)
220             {
221                 if (!resizeHash(pHashTable, pHashTable->tableSize * 2)) {
222                     /* don't really have a way to indicate failure */
223                     LOGE("Dalvik hash resize failure\n");
224                     abort();
225                 }
226                 /* note "pEntry" is now invalid */
227             }
228 
229             /* full table is bad -- search for nonexistent never halts */
230             assert(pHashTable->numEntries < pHashTable->tableSize);
231             result = item;
232         } else {
233             assert(result == NULL);
234         }
235     } else {
236         result = pEntry->data;
237     }
238 
239     return result;
240 }
241 
242 /*
243  * Remove an entry from the table.
244  *
245  * Does NOT invoke the "free" function on the item.
246  */
mzHashTableRemove(HashTable * pHashTable,unsigned int itemHash,void * item)247 bool mzHashTableRemove(HashTable* pHashTable, unsigned int itemHash, void* item)
248 {
249     HashEntry* pEntry;
250     HashEntry* pEnd;
251 
252     assert(pHashTable->tableSize > 0);
253 
254     /* jump to the first entry and probe for a match */
255     pEntry = &pHashTable->pEntries[itemHash & (pHashTable->tableSize-1)];
256     pEnd = &pHashTable->pEntries[pHashTable->tableSize];
257     while (pEntry->data != NULL) {
258         if (pEntry->data == item) {
259             pEntry->data = HASH_TOMBSTONE;
260             pHashTable->numEntries--;
261             pHashTable->numDeadEntries++;
262             return true;
263         }
264 
265         pEntry++;
266         if (pEntry == pEnd) {     /* wrap around to start */
267             if (pHashTable->tableSize == 1)
268                 break;      /* edge case - single-entry table */
269             pEntry = pHashTable->pEntries;
270         }
271     }
272 
273     return false;
274 }
275 
276 /*
277  * Execute a function on every entry in the hash table.
278  *
279  * If "func" returns a nonzero value, terminate early and return the value.
280  */
mzHashForeach(HashTable * pHashTable,HashForeachFunc func,void * arg)281 int mzHashForeach(HashTable* pHashTable, HashForeachFunc func, void* arg)
282 {
283     int i, val;
284 
285     for (i = 0; i < pHashTable->tableSize; i++) {
286         HashEntry* pEnt = &pHashTable->pEntries[i];
287 
288         if (pEnt->data != NULL && pEnt->data != HASH_TOMBSTONE) {
289             val = (*func)(pEnt->data, arg);
290             if (val != 0)
291                 return val;
292         }
293     }
294 
295     return 0;
296 }
297 
298 
299 /*
300  * Look up an entry, counting the number of times we have to probe.
301  *
302  * Returns -1 if the entry wasn't found.
303  */
countProbes(HashTable * pHashTable,unsigned int itemHash,const void * item,HashCompareFunc cmpFunc)304 int countProbes(HashTable* pHashTable, unsigned int itemHash, const void* item,
305     HashCompareFunc cmpFunc)
306 {
307     HashEntry* pEntry;
308     HashEntry* pEnd;
309     int count = 0;
310 
311     assert(pHashTable->tableSize > 0);
312     assert(item != HASH_TOMBSTONE);
313     assert(item != NULL);
314 
315     /* jump to the first entry and probe for a match */
316     pEntry = &pHashTable->pEntries[itemHash & (pHashTable->tableSize-1)];
317     pEnd = &pHashTable->pEntries[pHashTable->tableSize];
318     while (pEntry->data != NULL) {
319         if (pEntry->data != HASH_TOMBSTONE &&
320             pEntry->hashValue == itemHash &&
321             (*cmpFunc)(pEntry->data, item) == 0)
322         {
323             /* match */
324             break;
325         }
326 
327         pEntry++;
328         if (pEntry == pEnd) {     /* wrap around to start */
329             if (pHashTable->tableSize == 1)
330                 break;      /* edge case - single-entry table */
331             pEntry = pHashTable->pEntries;
332         }
333 
334         count++;
335     }
336     if (pEntry->data == NULL)
337         return -1;
338 
339     return count;
340 }
341 
342 /*
343  * Evaluate the amount of probing required for the specified hash table.
344  *
345  * We do this by running through all entries in the hash table, computing
346  * the hash value and then doing a lookup.
347  *
348  * The caller should lock the table before calling here.
349  */
mzHashTableProbeCount(HashTable * pHashTable,HashCalcFunc calcFunc,HashCompareFunc cmpFunc)350 void mzHashTableProbeCount(HashTable* pHashTable, HashCalcFunc calcFunc,
351     HashCompareFunc cmpFunc)
352 {
353     int numEntries, minProbe, maxProbe, totalProbe;
354     HashIter iter;
355 
356     numEntries = maxProbe = totalProbe = 0;
357     minProbe = 65536*32767;
358 
359     for (mzHashIterBegin(pHashTable, &iter); !mzHashIterDone(&iter);
360         mzHashIterNext(&iter))
361     {
362         const void* data = (const void*)mzHashIterData(&iter);
363         int count;
364 
365         count = countProbes(pHashTable, (*calcFunc)(data), data, cmpFunc);
366 
367         numEntries++;
368 
369         if (count < minProbe)
370             minProbe = count;
371         if (count > maxProbe)
372             maxProbe = count;
373         totalProbe += count;
374     }
375 
376     LOGV("Probe: min=%d max=%d, total=%d in %d (%d), avg=%.3f\n",
377         minProbe, maxProbe, totalProbe, numEntries, pHashTable->tableSize,
378         (float) totalProbe / (float) numEntries);
379 }
380