xref: /sqlite-3.40.0/src/hash.c (revision c023e03e)
1 /*
2 ** 2001 September 22
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This is the implementation of generic hash-tables
13 ** used in SQLite.
14 **
15 ** $Id: hash.c,v 1.10 2003/05/12 23:06:53 drh Exp $
16 */
17 #include "sqliteInt.h"
18 #include <assert.h>
19 
20 /* Turn bulk memory into a hash table object by initializing the
21 ** fields of the Hash structure.
22 **
23 ** "new" is a pointer to the hash table that is to be initialized.
24 ** keyClass is one of the constants SQLITE_HASH_INT, SQLITE_HASH_POINTER,
25 ** SQLITE_HASH_BINARY, or SQLITE_HASH_STRING.  The value of keyClass
26 ** determines what kind of key the hash table will use.  "copyKey" is
27 ** true if the hash table should make its own private copy of keys and
28 ** false if it should just use the supplied pointer.  CopyKey only makes
29 ** sense for SQLITE_HASH_STRING and SQLITE_HASH_BINARY and is ignored
30 ** for other key classes.
31 */
32 void sqliteHashInit(Hash *new, int keyClass, int copyKey){
33   assert( new!=0 );
34   assert( keyClass>=SQLITE_HASH_INT && keyClass<=SQLITE_HASH_BINARY );
35   new->keyClass = keyClass;
36   new->copyKey = copyKey &&
37                 (keyClass==SQLITE_HASH_STRING || keyClass==SQLITE_HASH_BINARY);
38   new->first = 0;
39   new->count = 0;
40   new->htsize = 0;
41   new->ht = 0;
42 }
43 
44 /* Remove all entries from a hash table.  Reclaim all memory.
45 ** Call this routine to delete a hash table or to reset a hash table
46 ** to the empty state.
47 */
48 void sqliteHashClear(Hash *pH){
49   HashElem *elem;         /* For looping over all elements of the table */
50 
51   assert( pH!=0 );
52   elem = pH->first;
53   pH->first = 0;
54   if( pH->ht ) sqliteFree(pH->ht);
55   pH->ht = 0;
56   pH->htsize = 0;
57   while( elem ){
58     HashElem *next_elem = elem->next;
59     if( pH->copyKey && elem->pKey ){
60       sqliteFree(elem->pKey);
61     }
62     sqliteFree(elem);
63     elem = next_elem;
64   }
65   pH->count = 0;
66 }
67 
68 /*
69 ** Hash and comparison functions when the mode is SQLITE_HASH_INT
70 */
71 static int intHash(const void *pKey, int nKey){
72   return nKey ^ (nKey<<8) ^ (nKey>>8);
73 }
74 static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2){
75   return n2 - n1;
76 }
77 
78 /*
79 ** Hash and comparison functions when the mode is SQLITE_HASH_POINTER
80 */
81 static int ptrHash(const void *pKey, int nKey){
82   uptr x = Addr(pKey);
83   return x ^ (x<<8) ^ (x>>8);
84 }
85 static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
86   if( pKey1==pKey2 ) return 0;
87   if( pKey1<pKey2 ) return -1;
88   return 1;
89 }
90 
91 /*
92 ** Hash and comparison functions when the mode is SQLITE_HASH_STRING
93 */
94 static int strHash(const void *pKey, int nKey){
95   return sqliteHashNoCase((const char*)pKey, nKey);
96 }
97 static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
98   if( n1!=n2 ) return n2-n1;
99   return sqliteStrNICmp((const char*)pKey1,(const char*)pKey2,n1);
100 }
101 
102 /*
103 ** Hash and comparison functions when the mode is SQLITE_HASH_BINARY
104 */
105 static int binHash(const void *pKey, int nKey){
106   int h = 0;
107   const char *z = (const char *)pKey;
108   while( nKey-- > 0 ){
109     h = (h<<3) ^ h ^ *(z++);
110   }
111   return h & 0x7fffffff;
112 }
113 static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
114   if( n1!=n2 ) return n2-n1;
115   return memcmp(pKey1,pKey2,n1);
116 }
117 
118 /*
119 ** Return a pointer to the appropriate hash function given the key class.
120 **
121 ** The C syntax in this function definition may be unfamilar to some
122 ** programmers, so we provide the following additional explanation:
123 **
124 ** The name of the function is "hashFunction".  The function takes a
125 ** single parameter "keyClass".  The return value of hashFunction()
126 ** is a pointer to another function.  Specifically, the return value
127 ** of hashFunction() is a pointer to a function that takes two parameters
128 ** with types "const void*" and "int" and returns an "int".
129 */
130 static int (*hashFunction(int keyClass))(const void*,int){
131   switch( keyClass ){
132     case SQLITE_HASH_INT:     return &intHash;
133     case SQLITE_HASH_POINTER: return &ptrHash;
134     case SQLITE_HASH_STRING:  return &strHash;
135     case SQLITE_HASH_BINARY:  return &binHash;;
136     default: break;
137   }
138   return 0;
139 }
140 
141 /*
142 ** Return a pointer to the appropriate hash function given the key class.
143 **
144 ** For help in interpreted the obscure C code in the function definition,
145 ** see the header comment on the previous function.
146 */
147 static int (*compareFunction(int keyClass))(const void*,int,const void*,int){
148   switch( keyClass ){
149     case SQLITE_HASH_INT:     return &intCompare;
150     case SQLITE_HASH_POINTER: return &ptrCompare;
151     case SQLITE_HASH_STRING:  return &strCompare;
152     case SQLITE_HASH_BINARY:  return &binCompare;
153     default: break;
154   }
155   return 0;
156 }
157 
158 
159 /* Resize the hash table so that it cantains "new_size" buckets.
160 ** "new_size" must be a power of 2.  The hash table might fail
161 ** to resize if sqliteMalloc() fails.
162 */
163 static void rehash(Hash *pH, int new_size){
164   struct _ht *new_ht;            /* The new hash table */
165   HashElem *elem, *next_elem;    /* For looping over existing elements */
166   HashElem *x;                   /* Element being copied to new hash table */
167   int (*xHash)(const void*,int); /* The hash function */
168 
169   assert( (new_size & (new_size-1))==0 );
170   new_ht = (struct _ht *)sqliteMalloc( new_size*sizeof(struct _ht) );
171   if( new_ht==0 ) return;
172   if( pH->ht ) sqliteFree(pH->ht);
173   pH->ht = new_ht;
174   pH->htsize = new_size;
175   xHash = hashFunction(pH->keyClass);
176   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
177     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
178     next_elem = elem->next;
179     x = new_ht[h].chain;
180     if( x ){
181       elem->next = x;
182       elem->prev = x->prev;
183       if( x->prev ) x->prev->next = elem;
184       else          pH->first = elem;
185       x->prev = elem;
186     }else{
187       elem->next = pH->first;
188       if( pH->first ) pH->first->prev = elem;
189       elem->prev = 0;
190       pH->first = elem;
191     }
192     new_ht[h].chain = elem;
193     new_ht[h].count++;
194   }
195 }
196 
197 /* This function (for internal use only) locates an element in an
198 ** hash table that matches the given key.  The hash for this key has
199 ** already been computed and is passed as the 4th parameter.
200 */
201 static HashElem *findElementGivenHash(
202   const Hash *pH,     /* The pH to be searched */
203   const void *pKey,   /* The key we are searching for */
204   int nKey,
205   int h               /* The hash for this key. */
206 ){
207   HashElem *elem;                /* Used to loop thru the element list */
208   int count;                     /* Number of elements left to test */
209   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
210 
211   if( pH->ht ){
212     elem = pH->ht[h].chain;
213     count = pH->ht[h].count;
214     xCompare = compareFunction(pH->keyClass);
215     while( count-- && elem ){
216       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
217         return elem;
218       }
219       elem = elem->next;
220     }
221   }
222   return 0;
223 }
224 
225 /* Remove a single entry from the hash table given a pointer to that
226 ** element and a hash on the element's key.
227 */
228 static void removeElementGivenHash(
229   Hash *pH,         /* The pH containing "elem" */
230   HashElem* elem,   /* The element to be removed from the pH */
231   int h             /* Hash value for the element */
232 ){
233   if( elem->prev ){
234     elem->prev->next = elem->next;
235   }else{
236     pH->first = elem->next;
237   }
238   if( elem->next ){
239     elem->next->prev = elem->prev;
240   }
241   if( pH->ht[h].chain==elem ){
242     pH->ht[h].chain = elem->next;
243   }
244   pH->ht[h].count--;
245   if( pH->ht[h].count<=0 ){
246     pH->ht[h].chain = 0;
247   }
248   if( pH->copyKey && elem->pKey ){
249     sqliteFree(elem->pKey);
250   }
251   sqliteFree( elem );
252   pH->count--;
253 }
254 
255 /* Attempt to locate an element of the hash table pH with a key
256 ** that matches pKey,nKey.  Return the data for this element if it is
257 ** found, or NULL if there is no match.
258 */
259 void *sqliteHashFind(const Hash *pH, const void *pKey, int nKey){
260   int h;             /* A hash on key */
261   HashElem *elem;    /* The element that matches key */
262   int (*xHash)(const void*,int);  /* The hash function */
263 
264   if( pH==0 || pH->ht==0 ) return 0;
265   xHash = hashFunction(pH->keyClass);
266   assert( xHash!=0 );
267   h = (*xHash)(pKey,nKey);
268   assert( (pH->htsize & (pH->htsize-1))==0 );
269   elem = findElementGivenHash(pH,pKey,nKey, h & (pH->htsize-1));
270   return elem ? elem->data : 0;
271 }
272 
273 /* Insert an element into the hash table pH.  The key is pKey,nKey
274 ** and the data is "data".
275 **
276 ** If no element exists with a matching key, then a new
277 ** element is created.  A copy of the key is made if the copyKey
278 ** flag is set.  NULL is returned.
279 **
280 ** If another element already exists with the same key, then the
281 ** new data replaces the old data and the old data is returned.
282 ** The key is not copied in this instance.  If a malloc fails, then
283 ** the new data is returned and the hash table is unchanged.
284 **
285 ** If the "data" parameter to this function is NULL, then the
286 ** element corresponding to "key" is removed from the hash table.
287 */
288 void *sqliteHashInsert(Hash *pH, const void *pKey, int nKey, void *data){
289   int hraw;             /* Raw hash value of the key */
290   int h;                /* the hash of the key modulo hash table size */
291   HashElem *elem;       /* Used to loop thru the element list */
292   HashElem *new_elem;   /* New element added to the pH */
293   int (*xHash)(const void*,int);  /* The hash function */
294 
295   assert( pH!=0 );
296   xHash = hashFunction(pH->keyClass);
297   assert( xHash!=0 );
298   hraw = (*xHash)(pKey, nKey);
299   assert( (pH->htsize & (pH->htsize-1))==0 );
300   h = hraw & (pH->htsize-1);
301   elem = findElementGivenHash(pH,pKey,nKey,h);
302   if( elem ){
303     void *old_data = elem->data;
304     if( data==0 ){
305       removeElementGivenHash(pH,elem,h);
306     }else{
307       elem->data = data;
308     }
309     return old_data;
310   }
311   if( data==0 ) return 0;
312   new_elem = (HashElem*)sqliteMalloc( sizeof(HashElem) );
313   if( new_elem==0 ) return data;
314   if( pH->copyKey && pKey!=0 ){
315     new_elem->pKey = sqliteMallocRaw( nKey );
316     if( new_elem->pKey==0 ){
317       sqliteFree(new_elem);
318       return data;
319     }
320     memcpy((void*)new_elem->pKey, pKey, nKey);
321   }else{
322     new_elem->pKey = (void*)pKey;
323   }
324   new_elem->nKey = nKey;
325   pH->count++;
326   if( pH->htsize==0 ) rehash(pH,8);
327   if( pH->htsize==0 ){
328     pH->count = 0;
329     sqliteFree(new_elem);
330     return data;
331   }
332   if( pH->count > pH->htsize ){
333     rehash(pH,pH->htsize*2);
334   }
335   assert( (pH->htsize & (pH->htsize-1))==0 );
336   h = hraw & (pH->htsize-1);
337   elem = pH->ht[h].chain;
338   if( elem ){
339     new_elem->next = elem;
340     new_elem->prev = elem->prev;
341     if( elem->prev ){ elem->prev->next = new_elem; }
342     else            { pH->first = new_elem; }
343     elem->prev = new_elem;
344   }else{
345     new_elem->next = pH->first;
346     new_elem->prev = 0;
347     if( pH->first ){ pH->first->prev = new_elem; }
348     pH->first = new_elem;
349   }
350   pH->ht[h].count++;
351   pH->ht[h].chain = new_elem;
352   new_elem->data = data;
353   return 0;
354 }
355