hash-set, linkedhash-set: Reduce code duplication.
[gnulib.git] / lib / gl_anyhash2.h
blobd4c543002518d2be5e2e589e9daa3a7c51bb445e
1 /* Hash table for sequential list, set, and map data type.
2 Copyright (C) 2006, 2009-2018 Free Software Foundation, Inc.
3 Written by Bruno Haible <bruno@clisp.org>, 2006.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 /* Common code of
19 gl_linkedhash_list.c, gl_avltreehash_list.c, gl_rbtreehash_list.c,
20 gl_linkedhash_set.c, gl_hash_set.c. */
22 #include "gl_anyhash_primes.h"
24 /* Resize the hash table with a new estimated size. */
25 static void
26 hash_resize (CONTAINER_T container, size_t estimate)
28 size_t new_size = next_prime (estimate);
30 if (new_size > container->table_size)
32 gl_hash_entry_t *old_table = container->table;
33 /* Allocate the new table. */
34 gl_hash_entry_t *new_table;
35 size_t i;
37 if (size_overflow_p (xtimes (new_size, sizeof (gl_hash_entry_t))))
38 goto fail;
39 new_table =
40 (gl_hash_entry_t *) calloc (new_size, sizeof (gl_hash_entry_t));
41 if (new_table == NULL)
42 goto fail;
44 /* Iterate through the entries of the old table. */
45 for (i = container->table_size; i > 0; )
47 gl_hash_entry_t node = old_table[--i];
49 while (node != NULL)
51 gl_hash_entry_t next = node->hash_next;
52 /* Add the entry to the new table. */
53 size_t bucket = node->hashcode % new_size;
54 node->hash_next = new_table[bucket];
55 new_table[bucket] = node;
57 node = next;
61 container->table = new_table;
62 container->table_size = new_size;
63 free (old_table);
65 return;
67 fail:
68 /* Just continue without resizing the table. */
69 return;
72 /* Resize the hash table if needed, after CONTAINER_COUNT (container) was
73 incremented. */
74 static void
75 hash_resize_after_add (CONTAINER_T container)
77 size_t count = CONTAINER_COUNT (container);
78 size_t estimate = xsum (count, count / 2); /* 1.5 * count */
79 if (estimate > container->table_size)
80 hash_resize (container, estimate);