prepared deprecation of GMemChunk and GAllocator. added g_slice_*() API to
[platform/upstream/glib.git] / glib / ghash.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 /* 
28  * MT safe
29  */
30
31 #include "config.h"
32
33 #include "glib.h"
34 #include "galias.h"
35
36
37 #define HASH_TABLE_MIN_SIZE 11
38 #define HASH_TABLE_MAX_SIZE 13845163
39
40
41 typedef struct _GHashNode      GHashNode;
42
43 struct _GHashNode
44 {
45   gpointer   key;
46   gpointer   value;
47   GHashNode *next;
48 };
49
50 struct _GHashTable
51 {
52   gint             size;
53   gint             nnodes;
54   GHashNode      **nodes;
55   GHashFunc        hash_func;
56   GEqualFunc       key_equal_func;
57   GDestroyNotify   key_destroy_func;
58   GDestroyNotify   value_destroy_func;
59 };
60
61 #define G_HASH_TABLE_RESIZE(hash_table)                         \
62    G_STMT_START {                                               \
63      if ((hash_table->size >= 3 * hash_table->nnodes &&         \
64           hash_table->size > HASH_TABLE_MIN_SIZE) ||            \
65          (3 * hash_table->size <= hash_table->nnodes &&         \
66           hash_table->size < HASH_TABLE_MAX_SIZE))              \
67            g_hash_table_resize (hash_table);                    \
68    } G_STMT_END
69
70 static void             g_hash_table_resize       (GHashTable     *hash_table);
71 static GHashNode**      g_hash_table_lookup_node  (GHashTable     *hash_table,
72                                                    gconstpointer   key);
73 static GHashNode*       g_hash_node_new           (gpointer        key,
74                                                    gpointer        value);
75 static void             g_hash_node_destroy       (GHashNode      *hash_node,
76                                                    GDestroyNotify  key_destroy_func,
77                                                    GDestroyNotify  value_destroy_func);
78 static void             g_hash_nodes_destroy      (GHashNode      *hash_node,
79                                                   GDestroyNotify   key_destroy_func,
80                                                   GDestroyNotify   value_destroy_func);
81 static guint g_hash_table_foreach_remove_or_steal (GHashTable     *hash_table,
82                                                    GHRFunc         func,
83                                                    gpointer        user_data,
84                                                    gboolean        notify);
85
86
87 /**
88  * g_hash_table_new:
89  * @hash_func: a function to create a hash value from a key.
90  *   Hash values are used to determine where keys are stored within the
91  *   #GHashTable data structure. The g_direct_hash(), g_int_hash() and 
92  *   g_str_hash() functions are provided for some common types of keys. 
93  *   If hash_func is %NULL, g_direct_hash() is used.
94  * @key_equal_func: a function to check two keys for equality.  This is
95  *   used when looking up keys in the #GHashTable.  The g_direct_equal(),
96  *   g_int_equal() and g_str_equal() functions are provided for the most
97  *   common types of keys. If @key_equal_func is %NULL, keys are compared
98  *   directly in a similar fashion to g_direct_equal(), but without the
99  *   overhead of a function call.
100  *
101  * Creates a new #GHashTable.
102  * 
103  * Return value: a new #GHashTable.
104  **/
105 GHashTable*
106 g_hash_table_new (GHashFunc    hash_func,
107                   GEqualFunc   key_equal_func)
108 {
109   return g_hash_table_new_full (hash_func, key_equal_func, NULL, NULL);
110 }
111
112
113 /**
114  * g_hash_table_new_full:
115  * @hash_func: a function to create a hash value from a key.
116  * @key_equal_func: a function to check two keys for equality.
117  * @key_destroy_func: a function to free the memory allocated for the key 
118  *   used when removing the entry from the #GHashTable or %NULL if you 
119  *   don't want to supply such a function.
120  * @value_destroy_func: a function to free the memory allocated for the 
121  *   value used when removing the entry from the #GHashTable or %NULL if 
122  *   you don't want to supply such a function.
123  * 
124  * Creates a new #GHashTable like g_hash_table_new() and allows to specify
125  * functions to free the memory allocated for the key and value that get 
126  * called when removing the entry from the #GHashTable.
127  * 
128  * Return value: a new #GHashTable.
129  **/
130 GHashTable*
131 g_hash_table_new_full (GHashFunc       hash_func,
132                        GEqualFunc      key_equal_func,
133                        GDestroyNotify  key_destroy_func,
134                        GDestroyNotify  value_destroy_func)
135 {
136   GHashTable *hash_table;
137   guint i;
138   
139   hash_table = g_slice_new (GHashTable);
140   hash_table->size               = HASH_TABLE_MIN_SIZE;
141   hash_table->nnodes             = 0;
142   hash_table->hash_func          = hash_func ? hash_func : g_direct_hash;
143   hash_table->key_equal_func     = key_equal_func;
144   hash_table->key_destroy_func   = key_destroy_func;
145   hash_table->value_destroy_func = value_destroy_func;
146   hash_table->nodes              = g_new (GHashNode*, hash_table->size);
147   
148   for (i = 0; i < hash_table->size; i++)
149     hash_table->nodes[i] = NULL;
150   
151   return hash_table;
152 }
153
154 /**
155  * g_hash_table_destroy:
156  * @hash_table: a #GHashTable.
157  * 
158  * Destroys the #GHashTable. If keys and/or values are dynamically 
159  * allocated, you should either free them first or create the #GHashTable
160  * using g_hash_table_new_full(). In the latter case the destroy functions 
161  * you supplied will be called on all keys and values before destroying 
162  * the #GHashTable.
163  **/
164 void
165 g_hash_table_destroy (GHashTable *hash_table)
166 {
167   guint i;
168   
169   g_return_if_fail (hash_table != NULL);
170   
171   for (i = 0; i < hash_table->size; i++)
172     g_hash_nodes_destroy (hash_table->nodes[i], 
173                           hash_table->key_destroy_func,
174                           hash_table->value_destroy_func);
175   
176   g_free (hash_table->nodes);
177   g_slice_free (GHashTable, hash_table);
178 }
179
180 static inline GHashNode**
181 g_hash_table_lookup_node (GHashTable    *hash_table,
182                           gconstpointer  key)
183 {
184   GHashNode **node;
185   
186   node = &hash_table->nodes
187     [(* hash_table->hash_func) (key) % hash_table->size];
188   
189   /* Hash table lookup needs to be fast.
190    *  We therefore remove the extra conditional of testing
191    *  whether to call the key_equal_func or not from
192    *  the inner loop.
193    */
194   if (hash_table->key_equal_func)
195     while (*node && !(*hash_table->key_equal_func) ((*node)->key, key))
196       node = &(*node)->next;
197   else
198     while (*node && (*node)->key != key)
199       node = &(*node)->next;
200   
201   return node;
202 }
203
204 /**
205  * g_hash_table_lookup:
206  * @hash_table: a #GHashTable.
207  * @key: the key to look up.
208  * 
209  * Looks up a key in a #GHashTable. Note that this function cannot
210  * distinguish between a key that is not present and one which is present
211  * and has the value %NULL. If you need this distinction, use
212  * g_hash_table_lookup_extended().
213  * 
214  * Return value: the associated value, or %NULL if the key is not found.
215  **/
216 gpointer
217 g_hash_table_lookup (GHashTable   *hash_table,
218                      gconstpointer key)
219 {
220   GHashNode *node;
221   
222   g_return_val_if_fail (hash_table != NULL, NULL);
223   
224   node = *g_hash_table_lookup_node (hash_table, key);
225   
226   return node ? node->value : NULL;
227 }
228
229 /**
230  * g_hash_table_lookup_extended:
231  * @hash_table: a #GHashTable.
232  * @lookup_key: the key to look up.
233  * @orig_key: returns the original key.
234  * @value: returns the value associated with the key.
235  * 
236  * Looks up a key in the #GHashTable, returning the original key and the
237  * associated value and a #gboolean which is %TRUE if the key was found. This 
238  * is useful if you need to free the memory allocated for the original key, 
239  * for example before calling g_hash_table_remove().
240  * 
241  * Return value: %TRUE if the key was found in the #GHashTable.
242  **/
243 gboolean
244 g_hash_table_lookup_extended (GHashTable    *hash_table,
245                               gconstpointer  lookup_key,
246                               gpointer      *orig_key,
247                               gpointer      *value)
248 {
249   GHashNode *node;
250   
251   g_return_val_if_fail (hash_table != NULL, FALSE);
252   
253   node = *g_hash_table_lookup_node (hash_table, lookup_key);
254   
255   if (node)
256     {
257       if (orig_key)
258         *orig_key = node->key;
259       if (value)
260         *value = node->value;
261       return TRUE;
262     }
263   else
264     return FALSE;
265 }
266
267 /**
268  * g_hash_table_insert:
269  * @hash_table: a #GHashTable.
270  * @key: a key to insert.
271  * @value: the value to associate with the key.
272  * 
273  * Inserts a new key and value into a #GHashTable.
274  * 
275  * If the key already exists in the #GHashTable its current value is replaced
276  * with the new value. If you supplied a @value_destroy_func when creating the 
277  * #GHashTable, the old value is freed using that function. If you supplied
278  * a @key_destroy_func when creating the #GHashTable, the passed key is freed 
279  * using that function.
280  **/
281 void
282 g_hash_table_insert (GHashTable *hash_table,
283                      gpointer    key,
284                      gpointer    value)
285 {
286   GHashNode **node;
287   
288   g_return_if_fail (hash_table != NULL);
289   
290   node = g_hash_table_lookup_node (hash_table, key);
291   
292   if (*node)
293     {
294       /* do not reset node->key in this place, keeping
295        * the old key is the intended behaviour. 
296        * g_hash_table_replace() can be used instead.
297        */
298
299       /* free the passed key */
300       if (hash_table->key_destroy_func)
301         hash_table->key_destroy_func (key);
302       
303       if (hash_table->value_destroy_func)
304         hash_table->value_destroy_func ((*node)->value);
305
306       (*node)->value = value;
307     }
308   else
309     {
310       *node = g_hash_node_new (key, value);
311       hash_table->nnodes++;
312       G_HASH_TABLE_RESIZE (hash_table);
313     }
314 }
315
316 /**
317  * g_hash_table_replace:
318  * @hash_table: a #GHashTable.
319  * @key: a key to insert.
320  * @value: the value to associate with the key.
321  * 
322  * Inserts a new key and value into a #GHashTable similar to 
323  * g_hash_table_insert(). The difference is that if the key already exists 
324  * in the #GHashTable, it gets replaced by the new key. If you supplied a 
325  * @value_destroy_func when creating the #GHashTable, the old value is freed 
326  * using that function. If you supplied a @key_destroy_func when creating the 
327  * #GHashTable, the old key is freed using that function. 
328  **/
329 void
330 g_hash_table_replace (GHashTable *hash_table,
331                       gpointer    key,
332                       gpointer    value)
333 {
334   GHashNode **node;
335   
336   g_return_if_fail (hash_table != NULL);
337   
338   node = g_hash_table_lookup_node (hash_table, key);
339   
340   if (*node)
341     {
342       if (hash_table->key_destroy_func)
343         hash_table->key_destroy_func ((*node)->key);
344       
345       if (hash_table->value_destroy_func)
346         hash_table->value_destroy_func ((*node)->value);
347
348       (*node)->key   = key;
349       (*node)->value = value;
350     }
351   else
352     {
353       *node = g_hash_node_new (key, value);
354       hash_table->nnodes++;
355       G_HASH_TABLE_RESIZE (hash_table);
356     }
357 }
358
359 /**
360  * g_hash_table_remove:
361  * @hash_table: a #GHashTable.
362  * @key: the key to remove.
363  * 
364  * Removes a key and its associated value from a #GHashTable.
365  *
366  * If the #GHashTable was created using g_hash_table_new_full(), the
367  * key and value are freed using the supplied destroy functions, otherwise
368  * you have to make sure that any dynamically allocated values are freed 
369  * yourself.
370  * 
371  * Return value: %TRUE if the key was found and removed from the #GHashTable.
372  **/
373 gboolean
374 g_hash_table_remove (GHashTable    *hash_table,
375                      gconstpointer  key)
376 {
377   GHashNode **node, *dest;
378   
379   g_return_val_if_fail (hash_table != NULL, FALSE);
380   
381   node = g_hash_table_lookup_node (hash_table, key);
382   if (*node)
383     {
384       dest = *node;
385       (*node) = dest->next;
386       g_hash_node_destroy (dest, 
387                            hash_table->key_destroy_func,
388                            hash_table->value_destroy_func);
389       hash_table->nnodes--;
390   
391       G_HASH_TABLE_RESIZE (hash_table);
392
393       return TRUE;
394     }
395
396   return FALSE;
397 }
398
399 /**
400  * g_hash_table_steal:
401  * @hash_table: a #GHashTable.
402  * @key: the key to remove.
403  * 
404  * Removes a key and its associated value from a #GHashTable without
405  * calling the key and value destroy functions.
406  *
407  * Return value: %TRUE if the key was found and removed from the #GHashTable.
408  **/
409 gboolean
410 g_hash_table_steal (GHashTable    *hash_table,
411                     gconstpointer  key)
412 {
413   GHashNode **node, *dest;
414   
415   g_return_val_if_fail (hash_table != NULL, FALSE);
416   
417   node = g_hash_table_lookup_node (hash_table, key);
418   if (*node)
419     {
420       dest = *node;
421       (*node) = dest->next;
422       g_hash_node_destroy (dest, NULL, NULL);
423       hash_table->nnodes--;
424   
425       G_HASH_TABLE_RESIZE (hash_table);
426
427       return TRUE;
428     }
429
430   return FALSE;
431 }
432
433 /**
434  * g_hash_table_foreach_remove:
435  * @hash_table: a #GHashTable.
436  * @func: the function to call for each key/value pair.
437  * @user_data: user data to pass to the function.
438  * 
439  * Calls the given function for each key/value pair in the #GHashTable.
440  * If the function returns %TRUE, then the key/value pair is removed from the
441  * #GHashTable. If you supplied key or value destroy functions when creating
442  * the #GHashTable, they are used to free the memory allocated for the removed
443  * keys and values.
444  * 
445  * Return value: the number of key/value pairs removed.
446  **/
447 guint
448 g_hash_table_foreach_remove (GHashTable *hash_table,
449                              GHRFunc     func,
450                              gpointer    user_data)
451 {
452   g_return_val_if_fail (hash_table != NULL, 0);
453   g_return_val_if_fail (func != NULL, 0);
454   
455   return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, TRUE);
456 }
457
458 /**
459  * g_hash_table_foreach_steal:
460  * @hash_table: a #GHashTable.
461  * @func: the function to call for each key/value pair.
462  * @user_data: user data to pass to the function.
463  * 
464  * Calls the given function for each key/value pair in the #GHashTable.
465  * If the function returns %TRUE, then the key/value pair is removed from the
466  * #GHashTable, but no key or value destroy functions are called.
467  * 
468  * Return value: the number of key/value pairs removed.
469  **/
470 guint
471 g_hash_table_foreach_steal (GHashTable *hash_table,
472                             GHRFunc     func,
473                             gpointer    user_data)
474 {
475   g_return_val_if_fail (hash_table != NULL, 0);
476   g_return_val_if_fail (func != NULL, 0);
477   
478   return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, FALSE);
479 }
480
481 static guint
482 g_hash_table_foreach_remove_or_steal (GHashTable *hash_table,
483                                       GHRFunc     func,
484                                       gpointer    user_data,
485                                       gboolean    notify)
486 {
487   GHashNode *node, *prev;
488   guint i;
489   guint deleted = 0;
490   
491   for (i = 0; i < hash_table->size; i++)
492     {
493     restart:
494       
495       prev = NULL;
496       
497       for (node = hash_table->nodes[i]; node; prev = node, node = node->next)
498         {
499           if ((* func) (node->key, node->value, user_data))
500             {
501               deleted += 1;
502               
503               hash_table->nnodes -= 1;
504               
505               if (prev)
506                 {
507                   prev->next = node->next;
508                   g_hash_node_destroy (node,
509                                        notify ? hash_table->key_destroy_func : NULL,
510                                        notify ? hash_table->value_destroy_func : NULL);
511                   node = prev;
512                 }
513               else
514                 {
515                   hash_table->nodes[i] = node->next;
516                   g_hash_node_destroy (node,
517                                        notify ? hash_table->key_destroy_func : NULL,
518                                        notify ? hash_table->value_destroy_func : NULL);
519                   goto restart;
520                 }
521             }
522         }
523     }
524   
525   G_HASH_TABLE_RESIZE (hash_table);
526   
527   return deleted;
528 }
529
530 /**
531  * g_hash_table_foreach:
532  * @hash_table: a #GHashTable.
533  * @func: the function to call for each key/value pair.
534  * @user_data: user data to pass to the function.
535  * 
536  * Calls the given function for each of the key/value pairs in the
537  * #GHashTable.  The function is passed the key and value of each
538  * pair, and the given @user_data parameter.  The hash table may not
539  * be modified while iterating over it (you can't add/remove
540  * items). To remove all items matching a predicate, use
541  * g_hash_table_foreach_remove().
542  **/
543 void
544 g_hash_table_foreach (GHashTable *hash_table,
545                       GHFunc      func,
546                       gpointer    user_data)
547 {
548   GHashNode *node;
549   gint i;
550   
551   g_return_if_fail (hash_table != NULL);
552   g_return_if_fail (func != NULL);
553   
554   for (i = 0; i < hash_table->size; i++)
555     for (node = hash_table->nodes[i]; node; node = node->next)
556       (* func) (node->key, node->value, user_data);
557 }
558
559 /**
560  * g_hash_table_find:
561  * @hash_table: a #GHashTable.
562  * @predicate:  function to test the key/value pairs for a certain property.
563  * @user_data:  user data to pass to the function.
564  * 
565  * Calls the given function for key/value pairs in the #GHashTable until 
566  * @predicate returns %TRUE.  The function is passed the key and value of 
567  * each pair, and the given @user_data parameter. The hash table may not
568  * be modified while iterating over it (you can't add/remove items). 
569  *
570  * Return value: The value of the first key/value pair is returned, for which 
571  * func evaluates to %TRUE. If no pair with the requested property is found, 
572  * %NULL is returned.
573  *
574  * Since: 2.4
575  **/
576 gpointer
577 g_hash_table_find (GHashTable      *hash_table,
578                    GHRFunc          predicate,
579                    gpointer         user_data)
580 {
581   GHashNode *node;
582   gint i;
583   
584   g_return_val_if_fail (hash_table != NULL, NULL);
585   g_return_val_if_fail (predicate != NULL, NULL);
586   
587   for (i = 0; i < hash_table->size; i++)
588     for (node = hash_table->nodes[i]; node; node = node->next)
589       if (predicate (node->key, node->value, user_data))
590         return node->value;       
591   return NULL;
592 }
593
594 /**
595  * g_hash_table_size:
596  * @hash_table: a #GHashTable.
597  * 
598  * Returns the number of elements contained in the #GHashTable.
599  * 
600  * Return value: the number of key/value pairs in the #GHashTable.
601  **/
602 guint
603 g_hash_table_size (GHashTable *hash_table)
604 {
605   g_return_val_if_fail (hash_table != NULL, 0);
606   
607   return hash_table->nnodes;
608 }
609
610 static void
611 g_hash_table_resize (GHashTable *hash_table)
612 {
613   GHashNode **new_nodes;
614   GHashNode *node;
615   GHashNode *next;
616   guint hash_val;
617   gint new_size;
618   gint i;
619
620   new_size = g_spaced_primes_closest (hash_table->nnodes);
621   new_size = CLAMP (new_size, HASH_TABLE_MIN_SIZE, HASH_TABLE_MAX_SIZE);
622  
623   new_nodes = g_new0 (GHashNode*, new_size);
624   
625   for (i = 0; i < hash_table->size; i++)
626     for (node = hash_table->nodes[i]; node; node = next)
627       {
628         next = node->next;
629
630         hash_val = (* hash_table->hash_func) (node->key) % new_size;
631
632         node->next = new_nodes[hash_val];
633         new_nodes[hash_val] = node;
634       }
635   
636   g_free (hash_table->nodes);
637   hash_table->nodes = new_nodes;
638   hash_table->size = new_size;
639 }
640
641 static GHashNode*
642 g_hash_node_new (gpointer key,
643                  gpointer value)
644 {
645   GHashNode *hash_node = g_slice_new (GHashNode);
646   
647   hash_node->key = key;
648   hash_node->value = value;
649   hash_node->next = NULL;
650   
651   return hash_node;
652 }
653
654 static void
655 g_hash_node_destroy (GHashNode      *hash_node,
656                      GDestroyNotify  key_destroy_func,
657                      GDestroyNotify  value_destroy_func)
658 {
659   if (key_destroy_func)
660     key_destroy_func (hash_node->key);
661   if (value_destroy_func)
662     value_destroy_func (hash_node->value);
663   
664 #ifdef ENABLE_GC_FRIENDLY
665   hash_node->key = NULL;
666   hash_node->value = NULL;
667 #endif /* ENABLE_GC_FRIENDLY */
668
669   g_slice_free (GHashNode, hash_node);
670 }
671
672 static void
673 g_hash_nodes_destroy (GHashNode *hash_node,
674                       GFreeFunc  key_destroy_func,
675                       GFreeFunc  value_destroy_func)
676 {
677   while (hash_node)
678     {
679       GHashNode *next = hash_node->next;
680       if (key_destroy_func)
681         key_destroy_func (hash_node->key);
682       if (value_destroy_func)
683         value_destroy_func (hash_node->value);
684       g_slice_free (GHashNode, hash_node);
685       hash_node = next;
686     }
687 }
688
689 #define __G_HASH_C__
690 #include "galiasdef.c"