gl_anyhash2.h 2.6 KB

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