4d111033e71ee63870664b4749069b1f5d9257ee
[framework/graphics/cairo.git] / util / cairo-script / cairo-script-hash.c
1 /* cairo - a vector graphics library with display and print output
2  *
3  * Copyright © 2004 Red Hat, Inc.
4  * Copyright © 2005 Red Hat, Inc.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it either under the terms of the GNU Lesser General Public
8  * License version 2.1 as published by the Free Software Foundation
9  * (the "LGPL") or, at your option, under the terms of the Mozilla
10  * Public License Version 1.1 (the "MPL"). If you do not alter this
11  * notice, a recipient may use your version of this file under either
12  * the MPL or the LGPL.
13  *
14  * You should have received a copy of the LGPL along with this library
15  * in the file COPYING-LGPL-2.1; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA
17  * You should have received a copy of the MPL along with this library
18  * in the file COPYING-MPL-1.1
19  *
20  * The contents of this file are subject to the Mozilla Public License
21  * Version 1.1 (the "License"); you may not use this file except in
22  * compliance with the License. You may obtain a copy of the License at
23  * http://www.mozilla.org/MPL/
24  *
25  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
26  * OF ANY KIND, either express or implied. See the LGPL or the MPL for
27  * the specific language governing rights and limitations.
28  *
29  * The Original Code is the cairo graphics library.
30  *
31  * The Initial Developer of the Original Code is Red Hat, Inc.
32  *
33  * Contributor(s):
34  *      Keith Packard <keithp@keithp.com>
35  *      Graydon Hoare <graydon@redhat.com>
36  *      Carl Worth <cworth@cworth.org>
37  *      Karl Tomlinson <karlt+@karlt.net>, Mozilla Corporation
38  */
39
40 #include "cairo-script-private.h"
41
42 #include <stdlib.h>
43
44 /*
45  * An entry can be in one of three states:
46  *
47  * FREE: Entry has never been used, terminates all searches.
48  *       Appears in the table as a %NULL pointer.
49  *
50  * DEAD: Entry had been live in the past. A dead entry can be reused
51  *       but does not terminate a search for an exact entry.
52  *       Appears in the table as a pointer to DEAD_ENTRY.
53  *
54  * LIVE: Entry is currently being used.
55  *       Appears in the table as any non-%NULL, non-DEAD_ENTRY pointer.
56  */
57
58 #define DEAD_ENTRY ((csi_hash_entry_t *) 0x1)
59
60 #define ENTRY_IS_FREE(entry) ((entry) == NULL)
61 #define ENTRY_IS_DEAD(entry) ((entry) == DEAD_ENTRY)
62 #define ENTRY_IS_LIVE(entry) ((entry) >  DEAD_ENTRY)
63
64
65 /* This table is open-addressed with double hashing. Each table size is a
66  * prime chosen to be a little more than double the high water mark for a
67  * given arrangement, so the tables should remain < 50% full. The table
68  * size makes for the "first" hash modulus; a second prime (2 less than the
69  * first prime) serves as the "second" hash modulus, which is co-prime and
70  * thus guarantees a complete permutation of table indices.
71  *
72  * This structure, and accompanying table, is borrowed/modified from the
73  * file xserver/render/glyph.c in the freedesktop.org x server, with
74  * permission (and suggested modification of doubling sizes) by Keith
75  * Packard.
76  */
77
78 static const csi_hash_table_arrangement_t hash_table_arrangements [] = {
79     { 16,               43,             41              },
80     { 32,               73,             71              },
81     { 64,               151,            149             },
82     { 128,              283,            281             },
83     { 256,              571,            569             },
84     { 512,              1153,           1151            },
85     { 1024,             2269,           2267            },
86     { 2048,             4519,           4517            },
87     { 4096,             9013,           9011            },
88     { 8192,             18043,          18041           },
89     { 16384,            36109,          36107           },
90     { 32768,            72091,          72089           },
91     { 65536,            144409,         144407          },
92     { 131072,           288361,         288359          },
93     { 262144,           576883,         576881          },
94     { 524288,           1153459,        1153457         },
95     { 1048576,          2307163,        2307161         },
96     { 2097152,          4613893,        4613891         },
97     { 4194304,          9227641,        9227639         },
98     { 8388608,          18455029,       18455027        },
99     { 16777216,         36911011,       36911009        },
100     { 33554432,         73819861,       73819859        },
101     { 67108864,         147639589,      147639587       },
102     { 134217728,        295279081,      295279079       },
103     { 268435456,        590559793,      590559791       }
104 };
105
106 #define NUM_HASH_TABLE_ARRANGEMENTS ARRAY_LENGTH (hash_table_arrangements)
107
108 /**
109  * _csi_hash_table_create:
110  * @keys_equal: a function to return %TRUE if two keys are equal
111  *
112  * Creates a new hash table which will use the keys_equal() function
113  * to compare hash keys. Data is provided to the hash table in the
114  * form of user-derived versions of #csi_hash_entry_t. A hash entry
115  * must be able to hold both a key (including a hash code) and a
116  * value. Sometimes only the key will be necessary, (as in
117  * _csi_hash_table_remove), and other times both a key and a value
118  * will be necessary, (as in _csi_hash_table_insert).
119  *
120  * See #csi_hash_entry_t for more details.
121  *
122  * Return value: the new hash table or %NULL if out of memory.
123  **/
124 csi_status_t
125 _csi_hash_table_init (csi_hash_table_t *hash_table,
126                       csi_hash_keys_equal_func_t keys_equal)
127 {
128     hash_table->keys_equal = keys_equal;
129
130     hash_table->arrangement = &hash_table_arrangements[0];
131
132     hash_table->entries = calloc (hash_table->arrangement->size,
133                                   sizeof(csi_hash_entry_t *));
134     if (hash_table->entries == NULL)
135         return _csi_error (CAIRO_STATUS_NO_MEMORY);
136
137     hash_table->live_entries = 0;
138     hash_table->used_entries = 0;
139     hash_table->iterating = 0;
140
141     return CSI_STATUS_SUCCESS;
142 }
143
144 /**
145  * _csi_hash_table_destroy:
146  * @hash_table: an empty hash table to destroy
147  *
148  * Immediately destroys the given hash table, freeing all resources
149  * associated with it.
150  *
151  * WARNING: The hash_table must have no live entries in it before
152  * _csi_hash_table_destroy is called. It is a fatal error otherwise,
153  * and this function will halt. The rationale for this behavior is to
154  * avoid memory leaks and to avoid needless complication of the API
155  * with destroy notifiy callbacks.
156  *
157  * WARNING: The hash_table must have no running iterators in it when
158  * _csi_hash_table_destroy is called. It is a fatal error otherwise,
159  * and this function will halt.
160  **/
161 void
162 _csi_hash_table_fini (csi_hash_table_t *hash_table)
163 {
164     free (hash_table->entries);
165 }
166
167 static csi_hash_entry_t **
168 _csi_hash_table_lookup_unique_key (csi_hash_table_t *hash_table,
169                                      csi_hash_entry_t *key)
170 {
171     unsigned long table_size, i, idx, step;
172     csi_hash_entry_t **entry;
173
174     table_size = hash_table->arrangement->size;
175     idx = key->hash % table_size;
176
177     entry = &hash_table->entries[idx];
178     if (! ENTRY_IS_LIVE (*entry))
179         return entry;
180
181     i = 1;
182     step = key->hash % hash_table->arrangement->rehash;
183     if (step == 0)
184         step = 1;
185     do {
186         idx += step;
187         if (idx >= table_size)
188             idx -= table_size;
189
190         entry = &hash_table->entries[idx];
191         if (! ENTRY_IS_LIVE (*entry))
192             return entry;
193     } while (++i < table_size);
194
195     return NULL;
196 }
197
198 /**
199  * _csi_hash_table_manage:
200  * @hash_table: a hash table
201  *
202  * Resize the hash table if the number of entries has gotten much
203  * bigger or smaller than the ideal number of entries for the current
204  * size, or control the number of dead entries by moving the entries
205  * within the table.
206  *
207  * Return value: %CAIRO_STATUS_SUCCESS if successful or
208  * %CAIRO_STATUS_NO_MEMORY if out of memory.
209  **/
210 static csi_status_t
211 _csi_hash_table_manage (csi_hash_table_t *hash_table)
212 {
213     csi_hash_table_t tmp;
214     csi_boolean_t realloc = TRUE;
215     unsigned long i;
216
217     /* This keeps the size of the hash table between 2 and approximately 8
218      * times the number of live entries and keeps the proportion of free
219      * entries (search-terminations) > 25%.
220      */
221     unsigned long high = hash_table->arrangement->high_water_mark;
222     unsigned long low = high >> 2;
223     unsigned long max_used = high  + high / 2;
224
225     tmp = *hash_table;
226
227     if (hash_table->live_entries > high) {
228         tmp.arrangement = hash_table->arrangement + 1;
229         /* This code is being abused if we can't make a table big enough. */
230     } else if (hash_table->live_entries < low &&
231                /* Can't shrink if we're at the smallest size */
232                hash_table->arrangement != &hash_table_arrangements[0])
233     {
234         tmp.arrangement = hash_table->arrangement - 1;
235     }
236     else if (hash_table->used_entries > max_used)
237     {
238         /* Clean out dead entries to prevent lookups from becoming too slow. */
239         for (i = 0; i < hash_table->arrangement->size; ++i) {
240             if (ENTRY_IS_DEAD (hash_table->entries[i]))
241                 hash_table->entries[i] = NULL;
242         }
243         hash_table->used_entries = hash_table->live_entries;
244
245         /* There is no need to reallocate but some entries may need to be
246          * moved.  Typically the proportion of entries needing to be moved is
247          * small, but, if the moving should leave a large number of dead
248          * entries, they will be cleaned out next time this code is
249          * executed. */
250         realloc = FALSE;
251     }
252     else
253     {
254         return CAIRO_STATUS_SUCCESS;
255     }
256
257     if (realloc) {
258         tmp.entries = calloc (tmp.arrangement->size,
259                               sizeof (csi_hash_entry_t*));
260         if (tmp.entries == NULL)
261             return _csi_error (CAIRO_STATUS_NO_MEMORY);
262
263         hash_table->used_entries = 0;
264     }
265
266     for (i = 0; i < hash_table->arrangement->size; ++i) {
267         csi_hash_entry_t *entry, **pos;
268
269         entry = hash_table->entries[i];
270         if (ENTRY_IS_LIVE (entry)) {
271             hash_table->entries[i] = DEAD_ENTRY;
272
273             pos = _csi_hash_table_lookup_unique_key (&tmp, entry);
274             if (ENTRY_IS_FREE (*pos))
275                 hash_table->used_entries++;
276
277             *pos = entry;
278         }
279     }
280
281     if (realloc) {
282         free (hash_table->entries);
283         hash_table->entries = tmp.entries;
284         hash_table->arrangement = tmp.arrangement;
285     }
286
287     return CAIRO_STATUS_SUCCESS;
288 }
289
290 /**
291  * _csi_hash_table_lookup:
292  * @hash_table: a hash table
293  * @key: the key of interest
294  *
295  * Performs a lookup in @hash_table looking for an entry which has a
296  * key that matches @key, (as determined by the keys_equal() function
297  * passed to _csi_hash_table_create).
298  *
299  * Return value: the matching entry, of %NULL if no match was found.
300  **/
301 void *
302 _csi_hash_table_lookup (csi_hash_table_t *hash_table,
303                         csi_hash_entry_t *key)
304 {
305     csi_hash_entry_t **entry;
306     unsigned long table_size, i, idx, step;
307
308     table_size = hash_table->arrangement->size;
309     idx = key->hash % table_size;
310     entry = &hash_table->entries[idx];
311
312     if (ENTRY_IS_LIVE (*entry)) {
313         if ((*entry)->hash == key->hash && hash_table->keys_equal (key, *entry))
314             return *entry;
315     } else if (ENTRY_IS_FREE (*entry))
316         return NULL;
317
318     i = 1;
319     step = key->hash % hash_table->arrangement->rehash;
320     if (step == 0)
321         step = 1;
322     do {
323         idx += step;
324         if (idx >= table_size)
325             idx -= table_size;
326
327         entry = &hash_table->entries[idx];
328         if (ENTRY_IS_LIVE (*entry)) {
329             if ((*entry)->hash == key->hash &&
330                 hash_table->keys_equal (key, *entry))
331             {
332                 return *entry;
333             }
334         } else if (ENTRY_IS_FREE (*entry))
335             return NULL;
336     } while (++i < table_size);
337
338     return NULL;
339 }
340
341 /**
342  * _csi_hash_table_insert:
343  * @hash_table: a hash table
344  * @key_and_value: an entry to be inserted
345  *
346  * Insert the entry #key_and_value into the hash table.
347  *
348  * WARNING: There must not be an existing entry in the hash table
349  * with a matching key.
350  *
351  * WARNING: It is a fatal error to insert an element while
352  * an iterator is running
353  *
354  * Instead of using insert to replace an entry, consider just editing
355  * the entry obtained with _csi_hash_table_lookup. Or if absolutely
356  * necessary, use _csi_hash_table_remove first.
357  *
358  * Return value: %CAIRO_STATUS_SUCCESS if successful or
359  * %CAIRO_STATUS_NO_MEMORY if insufficient memory is available.
360  **/
361 csi_status_t
362 _csi_hash_table_insert (csi_hash_table_t *hash_table,
363                           csi_hash_entry_t *key_and_value)
364 {
365     csi_status_t status;
366     csi_hash_entry_t **entry;
367
368     hash_table->live_entries++;
369     status = _csi_hash_table_manage (hash_table);
370     if (_csi_unlikely (status)) {
371         /* abort the insert... */
372         hash_table->live_entries--;
373         return status;
374     }
375
376     entry = _csi_hash_table_lookup_unique_key (hash_table,
377                                                key_and_value);
378     if (ENTRY_IS_FREE (*entry))
379         hash_table->used_entries++;
380
381     *entry = key_and_value;
382     return CAIRO_STATUS_SUCCESS;
383 }
384
385 static csi_hash_entry_t **
386 _csi_hash_table_lookup_exact_key (csi_hash_table_t *hash_table,
387                                     csi_hash_entry_t *key)
388 {
389     unsigned long table_size, i, idx, step;
390     csi_hash_entry_t **entry;
391
392     table_size = hash_table->arrangement->size;
393     idx = key->hash % table_size;
394
395     entry = &hash_table->entries[idx];
396     if (*entry == key)
397         return entry;
398
399     i = 1;
400     step = key->hash % hash_table->arrangement->rehash;
401     if (step == 0)
402         step = 1;
403     do {
404         idx += step;
405         if (idx >= table_size)
406             idx -= table_size;
407
408         entry = &hash_table->entries[idx];
409         if (*entry == key)
410             return entry;
411     } while (++i < table_size);
412
413     return NULL;
414 }
415 /**
416  * _csi_hash_table_remove:
417  * @hash_table: a hash table
418  * @key: key of entry to be removed
419  *
420  * Remove an entry from the hash table which points to @key.
421  *
422  * Return value: %CAIRO_STATUS_SUCCESS if successful or
423  * %CAIRO_STATUS_NO_MEMORY if out of memory.
424  **/
425 void
426 _csi_hash_table_remove (csi_hash_table_t *hash_table,
427                           csi_hash_entry_t *key)
428 {
429     *_csi_hash_table_lookup_exact_key (hash_table, key) = DEAD_ENTRY;
430     hash_table->live_entries--;
431
432     /* Check for table resize. Don't do this when iterating as this will
433      * reorder elements of the table and cause the iteration to potentially
434      * skip some elements. */
435     if (hash_table->iterating == 0) {
436         /* This call _can_ fail, but only in failing to allocate new
437          * memory to shrink the hash table. It does leave the table in a
438          * consistent state, and we've already succeeded in removing the
439          * entry, so we don't examine the failure status of this call. */
440         _csi_hash_table_manage (hash_table);
441     }
442 }
443
444 /**
445  * _csi_hash_table_foreach:
446  * @hash_table: a hash table
447  * @hash_callback: function to be called for each live entry
448  * @closure: additional argument to be passed to @hash_callback
449  *
450  * Call @hash_callback for each live entry in the hash table, in a
451  * non-specified order.
452  *
453  * Entries in @hash_table may be removed by code executed from @hash_callback.
454  *
455  * Entries may not be inserted to @hash_table, nor may @hash_table
456  * be destroyed by code executed from @hash_callback. The relevant
457  * functions will halt in these cases.
458  **/
459 void
460 _csi_hash_table_foreach (csi_hash_table_t             *hash_table,
461                          csi_hash_callback_func_t  hash_callback,
462                          void                         *closure)
463 {
464     unsigned long i;
465     csi_hash_entry_t *entry;
466
467     /* Mark the table for iteration */
468     ++hash_table->iterating;
469     for (i = 0; i < hash_table->arrangement->size; i++) {
470         entry = hash_table->entries[i];
471         if (ENTRY_IS_LIVE(entry))
472             hash_callback (entry, closure);
473     }
474     /* If some elements were deleted during the iteration,
475      * the table may need resizing. Just do this every time
476      * as the check is inexpensive.
477      */
478     if (--hash_table->iterating == 0) {
479         /* Should we fail to shrink the hash table, it is left unaltered,
480          * and we don't need to propagate the error status. */
481         _csi_hash_table_manage (hash_table);
482     }
483 }