blob: 11cb469e979fe6cfd8d7c1533ab70fb05f07703b [file] [log] [blame]
Bram Moolenaar6abd8e92005-01-19 22:21:15 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * hashtable.c: Handling of a hashtable with Vim-specific properties.
12 *
13 * Each item in a hashtable has a NUL terminated string key. A key can appear
14 * only once in the table.
15 *
16 * A hash number is computed from the key for quick lookup. When the hashes
17 * of two different keys point to the same entry an algorithm is used to
18 * iterate over other entries in the table until the right one is found.
19 * To make the iteration work removed keys are different from entries where a
20 * key was never present.
21 *
22 * The mechanism has been partly based on how Python Dictionaries are
23 * implemented. The algorithm is from Knuth Vol. 3, Sec. 6.4.
24 *
25 * The hashtable grows to accommodate more entries when needed. At least 1/3
26 * of the entries is empty to keep the lookup efficient (at the cost of extra
27 * memory).
28 */
29
30#include "vim.h"
31
32#if defined(FEAT_EVAL) || defined(FEAT_SYN_HL) || defined(PROTO)
33
34#if 1
35# define HT_DEBUG /* extra checks for table consistency */
36#endif
37
38/* Magic value for algorithm that walks through the array. */
39#define PERTURB_SHIFT 5
40
41static hashitem *hash_lookup __ARGS((hashtable *ht, char_u *key, long_u hash));
42static int hash_add_item __ARGS((hashtable *ht, hashitem *hi, char_u *key, long_u hash));
43static int hash_may_resize __ARGS((hashtable *ht));
44static long_u hash_hash __ARGS((char_u *key));
45
46#if 0 /* not used */
47/*
48 * Create an empty hash table.
49 * Returns NULL when out of memory.
50 */
51 hashtable *
52hash_create()
53{
54 hashtable *ht;
55
56 ht = (hashtable *)alloc(sizeof(hashtable));
57 if (ht != NULL)
58 hash_init(ht);
59 return ht;
60}
61#endif
62
63/*
64 * Initialize an empty hash table.
65 */
66 void
67hash_init(ht)
68 hashtable *ht;
69{
70 /* This zeroes all "ht_" entries and all the "hi_key" in "ht_smallarray". */
71 vim_memset(ht, 0, sizeof(hashtable));
72 ht->ht_array = ht->ht_smallarray;
73 ht->ht_mask = HT_INIT_SIZE - 1;
74}
75
Bram Moolenaar6abd8e92005-01-19 22:21:15 +000076/*
Bram Moolenaardcaf10e2005-01-21 11:55:25 +000077 * Free the array of a hash table. Does not free the items it contains!
78 * If "ht" is not freed then you should call hash_init() next!
Bram Moolenaar6abd8e92005-01-19 22:21:15 +000079 */
80 void
Bram Moolenaardcaf10e2005-01-21 11:55:25 +000081hash_clear(ht)
Bram Moolenaar6abd8e92005-01-19 22:21:15 +000082 hashtable *ht;
83{
84 if (ht->ht_array != ht->ht_smallarray)
85 vim_free(ht->ht_array);
Bram Moolenaar6abd8e92005-01-19 22:21:15 +000086}
Bram Moolenaar6abd8e92005-01-19 22:21:15 +000087
88/*
89 * Find "key" in hashtable "ht". "key" must not be NULL.
90 * Always returns a pointer to a hashitem. If the item was not found then
91 * HASHITEM_EMPTY() is TRUE. The pointer is then the place where the key
92 * would be added.
93 * WARNING: The returned pointer becomes invalid when the hashtable is changed
94 * (adding, setting or removing an item)!
95 */
96 hashitem *
97hash_find(ht, key)
98 hashtable *ht;
99 char_u *key;
100{
101 return hash_lookup(ht, key, hash_hash(key));
102}
103
104/*
105 * Like hash_find(), but caller computes "hash".
106 */
107 static hashitem *
108hash_lookup(ht, key, hash)
109 hashtable *ht;
110 char_u *key;
111 long_u hash;
112{
113 long_u perturb;
114 hashitem *freeitem;
115 hashitem *hi;
116 int idx;
117
118 /*
119 * Quickly handle the most common situations:
120 * - return if there is no item at all
121 * - skip over a removed item
122 * - return if the item matches
123 */
124 idx = hash & ht->ht_mask;
125 hi = &ht->ht_array[idx];
126
127 if (hi->hi_key == NULL)
128 return hi;
129 if (hi->hi_key == HI_KEY_REMOVED)
130 freeitem = hi;
131 else if (hi->hi_hash == hash && STRCMP(hi->hi_key, key) == 0)
132 return hi;
133 else
134 freeitem = NULL;
135
136 /*
137 * Need to search through the table to find the key. The algorithm
138 * to step through the table starts with large steps, gradually becoming
139 * smaller down to (1/4 table size + 1). This means it goes through all
140 * table entries in the end.
141 * When we run into a NULL key it's clear that the key isn't there.
142 * Return the first available slot found (can be a slot of a removed
143 * item).
144 */
145 for (perturb = hash; ; perturb >>= PERTURB_SHIFT)
146 {
147 idx = (idx << 2) + idx + perturb + 1;
148 hi = &ht->ht_array[idx & ht->ht_mask];
149 if (hi->hi_key == NULL)
150 return freeitem == NULL ? hi : freeitem;
151 if (hi->hi_hash == hash
152 && hi->hi_key != HI_KEY_REMOVED
153 && STRCMP(hi->hi_key, key) == 0)
154 return hi;
155 if (hi->hi_key == HI_KEY_REMOVED && freeitem == NULL)
156 freeitem = hi;
157 }
158}
159
160/*
161 * Add item with key "key" to hashtable "ht".
162 * Returns FAIL when out of memory or the key is already present.
163 */
164 int
165hash_add(ht, key)
166 hashtable *ht;
167 char_u *key;
168{
169 long_u hash = hash_hash(key);
170 hashitem *hi;
171
172 hi = hash_lookup(ht, key, hash);
173 if (!HASHITEM_EMPTY(hi))
174 {
175 EMSG2(_(e_intern2), "hash_add()");
176 return FAIL;
177 }
178 return hash_add_item(ht, hi, key, hash);
179}
180
181/*
182 * Add item "hi" with "key" to hashtable "ht". "key" must not be NULL and
183 * "hi" must have been obtained with hash_lookup() and point to an empty item.
184 * "hi" is invalid after this!
185 * Returns OK or FAIL (out of memory).
186 */
187 static int
188hash_add_item(ht, hi, key, hash)
189 hashtable *ht;
190 hashitem *hi;
191 char_u *key;
192 long_u hash;
193{
194 /* If resizing failed before and it fails again we can't add an item. */
195 if (ht->ht_error && hash_may_resize(ht) == FAIL)
196 return FAIL;
197
198 ++ht->ht_used;
199 if (hi->hi_key == NULL)
200 ++ht->ht_filled;
201 hi->hi_key = key;
202 hi->hi_hash = hash;
203
204 /* When the space gets low may resize the array. */
205 return hash_may_resize(ht);
206}
207
208#if 0 /* not used */
209/*
210 * Overwrite hashtable item "hi" with "key". "hi" must point to the item that
211 * is to be overwritten. Thus the number of items in the hashtable doesn't
212 * change.
213 * Although the key must be identical, the pointer may be different, thus it's
214 * set anyway (the key is part of an item with that key).
215 * The caller must take care of freeing the old item.
216 * "hi" is invalid after this!
217 */
218 void
219hash_set(hi, key)
220 hashitem *hi;
221 char_u *key;
222{
223 hi->hi_key = key;
224}
225#endif
226
227/*
228 * Remove item "hi" from hashtable "ht". "hi" must have been obtained with
Bram Moolenaardcaf10e2005-01-21 11:55:25 +0000229 * hash_lookup() and point to an empty item.
230 * The caller must take care of freeing the item itself.
Bram Moolenaar6abd8e92005-01-19 22:21:15 +0000231 */
232 void
233hash_remove(ht, hi)
234 hashtable *ht;
235 hashitem *hi;
236{
237 --ht->ht_used;
238 hi->hi_key = HI_KEY_REMOVED;
239 hash_may_resize(ht);
240}
241
242/*
Bram Moolenaardcaf10e2005-01-21 11:55:25 +0000243 * Lock a hashtable: prevent that ht_array changes.
244 * Don't use this when items are to be added!
245 * Must call hash_unlock() later.
246 */
247 void
248hash_lock(ht)
249 hashtable *ht;
250{
251 ++ht->ht_locked;
252}
253
254/*
255 * Unlock a hashtable: allow ht_array changes again.
256 * Table will be resized (shrink) when necessary.
257 * This must balance a call to hash_lock().
258 */
259 void
260hash_unlock(ht)
261 hashtable *ht;
262{
263 --ht->ht_locked;
264 (void)hash_may_resize(ht);
265}
266
267/*
Bram Moolenaar6abd8e92005-01-19 22:21:15 +0000268 * Shrink a hashtable when there is too much empty space.
269 * Grow a hashtable when there is not enough empty space.
270 * Returns OK or FAIL (out of memory).
271 */
272 static int
273hash_may_resize(ht)
274 hashtable *ht;
275{
276 hashitem temparray[HT_INIT_SIZE];
277 hashitem *oldarray, *newarray;
278 hashitem *olditem, *newitem;
279 int newi;
280 int todo;
281 long_u oldsize, newsize;
282 long_u minsize;
283 long_u newmask;
284 long_u perturb;
285
Bram Moolenaardcaf10e2005-01-21 11:55:25 +0000286 /* Don't resize a locked table. */
287 if (ht->ht_locked > 0)
288 return OK;
289
Bram Moolenaar6abd8e92005-01-19 22:21:15 +0000290#ifdef HT_DEBUG
291 if (ht->ht_used > ht->ht_filled)
292 EMSG("hash_may_resize(): more used than filled");
293 if (ht->ht_filled >= ht->ht_mask + 1)
294 EMSG("hash_may_resize(): table completely filled");
295#endif
296
297 /* Return quickly for small tables with at least two NULL items. NULL
298 * items are required for the lookup to decide a key isn't there. */
299 if (ht->ht_filled < HT_INIT_SIZE - 1 && ht->ht_array == ht->ht_smallarray)
300 return OK;
301
302 /*
303 * Grow or refill the array when it's more than 2/3 full (including
304 * removed items, so that they get cleaned up).
305 * Shrink the array when it's less than 1/5 full. When growing it is at
306 * least 1/4 full (avoids repeated grow-shrink operations)
307 */
308 oldsize = ht->ht_mask + 1;
309 if (ht->ht_filled * 3 < oldsize * 2 && ht->ht_used > oldsize / 5)
310 return OK;
311
Bram Moolenaardcaf10e2005-01-21 11:55:25 +0000312 if (ht->ht_used > 1000)
Bram Moolenaar6abd8e92005-01-19 22:21:15 +0000313 minsize = ht->ht_used * 2; /* it's big, don't make too much room */
314 else
315 minsize = ht->ht_used * 4; /* make plenty of room */
316 newsize = HT_INIT_SIZE;
317 while (newsize < minsize)
318 {
319 newsize <<= 1; /* make sure it's always a power of 2 */
320 if (newsize == 0)
321 return FAIL; /* overflow */
322 }
323
324 if (newsize == HT_INIT_SIZE)
325 {
326 /* Use the small array inside the hashdict structure. */
327 newarray = ht->ht_smallarray;
328 if (ht->ht_array == newarray)
329 {
330 /* Moving from ht_smallarray to ht_smallarray! Happens when there
331 * are many removed items. Copy the items to be able to clean up
332 * removed items. */
333 mch_memmove(temparray, newarray, sizeof(temparray));
334 oldarray = temparray;
335 }
336 else
337 oldarray = ht->ht_array;
338 }
339 else
340 {
341 /* Allocate an array. */
342 newarray = (hashitem *)alloc((unsigned)(sizeof(hashitem) * newsize));
343 if (newarray == NULL)
344 {
345 /* Out of memory. When there are NULL items still return OK.
346 * Otherwise set ht_error, because lookup may result in a hang if
347 * we add another item. */
348 if (ht->ht_filled < ht->ht_mask)
349 return OK;
350 ht->ht_error = TRUE;
351 return FAIL;
352 }
353 oldarray = ht->ht_array;
354 }
355 vim_memset(newarray, 0, (size_t)(sizeof(hashitem) * newsize));
356
357 /*
358 * Move all the items from the old array to the new one, placing them in
359 * the right spot. The new array won't have any removed items, thus this
360 * is also a cleanup action.
361 */
362 newmask = newsize - 1;
363 todo = ht->ht_used;
364 for (olditem = oldarray; todo > 0; ++olditem)
365 if (olditem->hi_key != NULL && olditem->hi_key != HI_KEY_REMOVED)
366 {
367 /*
368 * The algorithm to find the spot to add the item is identical to
369 * the algorithm to find an item in hash_lookup(). But we only
370 * need to search for a NULL key, thus it's simpler.
371 */
372 newi = olditem->hi_hash & newmask;
373 newitem = &newarray[newi];
374
375 if (newitem->hi_key != NULL)
376 for (perturb = olditem->hi_hash; ; perturb >>= PERTURB_SHIFT)
377 {
378 newi = (newi << 2) + newi + perturb + 1;
379 newitem = &newarray[newi & newmask];
380 if (newitem->hi_key == NULL)
381 break;
382 }
383 *newitem = *olditem;
384 --todo;
385 }
386
387 if (ht->ht_array != ht->ht_smallarray)
388 vim_free(ht->ht_array);
389 ht->ht_array = newarray;
390 ht->ht_mask = newmask;
391 ht->ht_filled = ht->ht_used;
392 ht->ht_error = FALSE;
393
394 return OK;
395}
396
397/*
398 * Get the hash number for a key. Uses the ElfHash algorithm, which is
399 * supposed to have an even distribution (suggested by Charles Campbell).
400 */
401 static long_u
402hash_hash(key)
403 char_u *key;
404{
405 long_u hash = 0;
406 long_u g;
407 char_u *p = key;
408
409 while (*p != NUL)
410 {
411 hash = (hash << 4) + *p++; /* clear low 4 bits of hash, add char */
412 g = hash & 0xf0000000L; /* g has high 4 bits of hash only */
413 if (g != 0)
414 hash ^= g >> 24; /* xor g's high 4 bits into hash */
415 }
416
417 return hash;
418}
419
420#endif