autoupdate
[gnulib.git] / lib / hash.c
index 4de1069..3ab7136 100644 (file)
 #include <config.h>
 
 #include "hash.h"
+
+#include "bitrotate.h"
 #include "xalloc.h"
 
-#include <limits.h>
+#include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
 
 # endif
 #endif
 
-#ifndef SIZE_MAX
-# define SIZE_MAX ((size_t) -1)
-#endif
-
 struct hash_entry
   {
     void *data;
@@ -263,7 +261,7 @@ hash_lookup (const Hash_table *table, const void *entry)
     return NULL;
 
   for (cursor = bucket; cursor; cursor = cursor->next)
-    if (table->comparator (entry, cursor->data))
+    if (entry == cursor->data || table->comparator (entry, cursor->data))
       return cursor->data;
 
   return NULL;
@@ -373,7 +371,7 @@ hash_do_for_each (const Hash_table *table, Hash_processor processor,
        {
          for (cursor = bucket; cursor; cursor = cursor->next)
            {
-             if (!(*processor) (cursor->data, processor_data))
+             if (! processor (cursor->data, processor_data))
                return counter;
              counter++;
            }
@@ -399,10 +397,8 @@ hash_do_for_each (const Hash_table *table, Hash_processor processor,
 size_t
 hash_string (const char *string, size_t n_buckets)
 {
-# define ROTATE_LEFT(Value, Shift) \
-  ((Value) << (Shift) | (Value) >> ((sizeof (size_t) * CHAR_BIT) - (Shift)))
 # define HASH_ONE_CHAR(Value, Byte) \
-  ((Byte) + ROTATE_LEFT (Value, 7))
+  ((Byte) + rotl_sz (Value, 7))
 
   size_t value = 0;
   unsigned char ch;
@@ -411,7 +407,6 @@ hash_string (const char *string, size_t n_buckets)
     value = HASH_ONE_CHAR (value, ch);
   return value % n_buckets;
 
-# undef ROTATE_LEFT
 # undef HASH_ONE_CHAR
 }
 
@@ -467,7 +462,7 @@ next_prime (size_t candidate)
   /* Make it definitely odd.  */
   candidate |= 1;
 
-  while (!is_prime (candidate))
+  while (SIZE_MAX != candidate && !is_prime (candidate))
     candidate += 2;
 
   return candidate;
@@ -479,6 +474,27 @@ hash_reset_tuning (Hash_tuning *tuning)
   *tuning = default_tuning;
 }
 
+/* If the user passes a NULL hasher, we hash the raw pointer.  */
+static size_t
+raw_hasher (const void *data, size_t n)
+{
+  /* When hashing unique pointers, it is often the case that they were
+     generated by malloc and thus have the property that the low-order
+     bits are 0.  As this tends to give poorer performance with small
+     tables, we rotate the pointer value before performing division,
+     in an attempt to improve hash quality.  */
+  size_t val = rotr_sz ((size_t) data, 3);
+  return val % n;
+}
+
+/* If the user passes a NULL comparator, we use pointer comparison.  */
+static bool
+raw_comparator (const void *a, const void *b)
+{
+  return a == b;
+}
+
+
 /* For the given hash TABLE, check the user supplied tuning structure for
    reasonable values, and return true if there is no gross error with it.
    Otherwise, definitively reset the TUNING field to some acceptable default
@@ -489,6 +505,7 @@ static bool
 check_tuning (Hash_table *table)
 {
   const Hash_tuning *tuning = table->tuning;
+  float epsilon;
   if (tuning == &default_tuning)
     return true;
 
@@ -497,7 +514,7 @@ check_tuning (Hash_table *table)
      fail to grow or shrink as they should.  The smallest allocation
      is 11 (due to next_prime's algorithm), so an epsilon of 0.1
      should be good enough.  */
-  float epsilon = 0.1f;
+  epsilon = 0.1f;
 
   if (epsilon < tuning->growth_threshold
       && tuning->growth_threshold < 1 - epsilon
@@ -512,6 +529,26 @@ check_tuning (Hash_table *table)
   return false;
 }
 
+/* Compute the size of the bucket array for the given CANDIDATE and
+   TUNING, or return 0 if there is no possible way to allocate that
+   many entries.  */
+
+static size_t
+compute_bucket_size (size_t candidate, const Hash_tuning *tuning)
+{
+  if (!tuning->is_n_buckets)
+    {
+      float new_candidate = candidate / tuning->growth_threshold;
+      if (SIZE_MAX <= new_candidate)
+       return 0;
+      candidate = new_candidate;
+    }
+  candidate = next_prime (candidate);
+  if (xalloc_oversized (candidate, sizeof (struct hash_entry *)))
+    return 0;
+  return candidate;
+}
+
 /* Allocate and return a new hash table, or NULL upon failure.  The initial
    number of buckets is automatically selected so as to _guarantee_ that you
    may insert at least CANDIDATE different user entries before any growth of
@@ -527,15 +564,16 @@ check_tuning (Hash_table *table)
    provided but the values requested are out of bounds or might cause
    rounding errors, return NULL.
 
-   The user-supplied HASHER function should be provided.  It accepts two
+   The user-supplied HASHER function, when not NULL, accepts two
    arguments ENTRY and TABLE_SIZE.  It computes, by hashing ENTRY contents, a
    slot number for that entry which should be in the range 0..TABLE_SIZE-1.
    This slot number is then returned.
 
-   The user-supplied COMPARATOR function should be provided.  It accepts two
+   The user-supplied COMPARATOR function, when not NULL, accepts two
    arguments pointing to user data, it then returns true for a pair of entries
    that compare equal, or false otherwise.  This function is internally called
-   on entries which are already known to hash to the same bucket index.
+   on entries which are already known to hash to the same bucket index,
+   but which are distinct pointers.
 
    The user-supplied DATA_FREER function, when not NULL, may be later called
    with the user data as an argument, just before the entry containing the
@@ -552,8 +590,10 @@ hash_initialize (size_t candidate, const Hash_tuning *tuning,
 {
   Hash_table *table;
 
-  if (hasher == NULL || comparator == NULL)
-    return NULL;
+  if (hasher == NULL)
+    hasher = raw_hasher;
+  if (comparator == NULL)
+    comparator = raw_comparator;
 
   table = malloc (sizeof *table);
   if (table == NULL)
@@ -572,18 +612,8 @@ hash_initialize (size_t candidate, const Hash_tuning *tuning,
       goto fail;
     }
 
-  if (!tuning->is_n_buckets)
-    {
-      float new_candidate = candidate / tuning->growth_threshold;
-      if (SIZE_MAX <= new_candidate)
-       goto fail;
-      candidate = new_candidate;
-    }
-
-  if (xalloc_oversized (candidate, sizeof *table->bucket))
-    goto fail;
-  table->n_buckets = next_prime (candidate);
-  if (xalloc_oversized (table->n_buckets, sizeof *table->bucket))
+  table->n_buckets = compute_bucket_size (candidate, tuning);
+  if (!table->n_buckets)
     goto fail;
 
   table->bucket = calloc (table->n_buckets, sizeof *table->bucket);
@@ -628,7 +658,7 @@ hash_clear (Hash_table *table)
          for (cursor = bucket->next; cursor; cursor = next)
            {
              if (table->data_freer)
-               (*table->data_freer) (cursor->data);
+               table->data_freer (cursor->data);
              cursor->data = NULL;
 
              next = cursor->next;
@@ -640,7 +670,7 @@ hash_clear (Hash_table *table)
 
          /* Free the bucket head.  */
          if (table->data_freer)
-           (*table->data_freer) (bucket->data);
+           table->data_freer (bucket->data);
          bucket->data = NULL;
          bucket->next = NULL;
        }
@@ -670,9 +700,7 @@ hash_free (Hash_table *table)
          if (bucket->data)
            {
              for (cursor = bucket; cursor; cursor = cursor->next)
-               {
-                 (*table->data_freer) (cursor->data);
-               }
+               table->data_freer (cursor->data);
            }
        }
     }
@@ -769,7 +797,7 @@ hash_find_entry (Hash_table *table, const void *entry,
     return NULL;
 
   /* See if the entry is the first in the bucket.  */
-  if ((*table->comparator) (entry, bucket->data))
+  if (entry == bucket->data || table->comparator (entry, bucket->data))
     {
       void *data = bucket->data;
 
@@ -796,7 +824,8 @@ hash_find_entry (Hash_table *table, const void *entry,
   /* Scan the bucket overflow.  */
   for (cursor = bucket; cursor->next; cursor = cursor->next)
     {
-      if ((*table->comparator) (entry, cursor->next->data))
+      if (entry == cursor->next->data
+         || table->comparator (entry, cursor->next->data))
        {
          void *data = cursor->next->data;
 
@@ -818,6 +847,93 @@ hash_find_entry (Hash_table *table, const void *entry,
   return NULL;
 }
 
+/* Internal helper, to move entries from SRC to DST.  Both tables must
+   share the same free entry list.  If SAFE, only move overflow
+   entries, saving bucket heads for later, so that no allocations will
+   occur.  Return false if the free entry list is exhausted and an
+   allocation fails.  */
+
+static bool
+transfer_entries (Hash_table *dst, Hash_table *src, bool safe)
+{
+  struct hash_entry *bucket;
+  struct hash_entry *cursor;
+  struct hash_entry *next;
+  for (bucket = src->bucket; bucket < src->bucket_limit; bucket++)
+    if (bucket->data)
+      {
+       void *data;
+       struct hash_entry *new_bucket;
+
+       /* Within each bucket, transfer overflow entries first and
+          then the bucket head, to minimize memory pressure.  After
+          all, the only time we might allocate is when moving the
+          bucket head, but moving overflow entries first may create
+          free entries that can be recycled by the time we finally
+          get to the bucket head.  */
+       for (cursor = bucket->next; cursor; cursor = next)
+         {
+           data = cursor->data;
+           new_bucket = (dst->bucket + dst->hasher (data, dst->n_buckets));
+
+           if (! (new_bucket < dst->bucket_limit))
+             abort ();
+
+           next = cursor->next;
+
+           if (new_bucket->data)
+             {
+               /* Merely relink an existing entry, when moving from a
+                  bucket overflow into a bucket overflow.  */
+               cursor->next = new_bucket->next;
+               new_bucket->next = cursor;
+             }
+           else
+             {
+               /* Free an existing entry, when moving from a bucket
+                  overflow into a bucket header.  */
+               new_bucket->data = data;
+               dst->n_buckets_used++;
+               free_entry (dst, cursor);
+             }
+         }
+       /* Now move the bucket head.  Be sure that if we fail due to
+          allocation failure that the src table is in a consistent
+          state.  */
+       data = bucket->data;
+       bucket->next = NULL;
+       if (safe)
+         continue;
+       new_bucket = (dst->bucket + dst->hasher (data, dst->n_buckets));
+
+       if (! (new_bucket < dst->bucket_limit))
+         abort ();
+
+       if (new_bucket->data)
+         {
+           /* Allocate or recycle an entry, when moving from a bucket
+              header into a bucket overflow.  */
+           struct hash_entry *new_entry = allocate_entry (dst);
+
+           if (new_entry == NULL)
+             return false;
+
+           new_entry->data = data;
+           new_entry->next = new_bucket->next;
+           new_bucket->next = new_entry;
+         }
+       else
+         {
+           /* Move from one bucket header to another.  */
+           new_bucket->data = data;
+           dst->n_buckets_used++;
+         }
+       bucket->data = NULL;
+       src->n_buckets_used--;
+      }
+  return true;
+}
+
 /* For an already existing hash table, change the number of buckets through
    specifying CANDIDATE.  The contents of the hash table are preserved.  The
    new number of buckets is automatically selected so as to _guarantee_ that
@@ -829,86 +945,80 @@ hash_find_entry (Hash_table *table, const void *entry,
 bool
 hash_rehash (Hash_table *table, size_t candidate)
 {
+  Hash_table storage;
   Hash_table *new_table;
-  struct hash_entry *bucket;
-  struct hash_entry *cursor;
-  struct hash_entry *next;
+  size_t new_size = compute_bucket_size (candidate, table->tuning);
 
-  new_table = hash_initialize (candidate, table->tuning, table->hasher,
-                              table->comparator, table->data_freer);
-  if (new_table == NULL)
+  if (!new_size)
     return false;
+  if (new_size == table->n_buckets)
+    return true;
+  new_table = &storage;
+  new_table->bucket = calloc (new_size, sizeof *new_table->bucket);
+  if (new_table->bucket == NULL)
+    return false;
+  new_table->n_buckets = new_size;
+  new_table->bucket_limit = new_table->bucket + new_size;
+  new_table->n_buckets_used = 0;
+  new_table->n_entries = 0;
+  new_table->tuning = table->tuning;
+  new_table->hasher = table->hasher;
+  new_table->comparator = table->comparator;
+  new_table->data_freer = table->data_freer;
+
+  /* In order for the transfer to successfully complete, we need
+     additional overflow entries when distinct buckets in the old
+     table collide into a common bucket in the new table.  The worst
+     case possible is a hasher that gives a good spread with the old
+     size, but returns a constant with the new size; if we were to
+     guarantee table->n_buckets_used-1 free entries in advance, then
+     the transfer would be guaranteed to not allocate memory.
+     However, for large tables, a guarantee of no further allocation
+     introduces a lot of extra memory pressure, all for an unlikely
+     corner case (most rehashes reduce, rather than increase, the
+     number of overflow entries needed).  So, we instead ensure that
+     the transfer process can be reversed if we hit a memory
+     allocation failure mid-transfer.  */
 
   /* Merely reuse the extra old space into the new table.  */
 #if USE_OBSTACK
-  obstack_free (&new_table->entry_stack, NULL);
   new_table->entry_stack = table->entry_stack;
 #endif
   new_table->free_entry_list = table->free_entry_list;
 
-  for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
-    if (bucket->data)
-      for (cursor = bucket; cursor; cursor = next)
-       {
-         void *data = cursor->data;
-         struct hash_entry *new_bucket
-           = (new_table->bucket
-              + new_table->hasher (data, new_table->n_buckets));
-
-         if (! (new_bucket < new_table->bucket_limit))
-           abort ();
-
-         next = cursor->next;
-
-         if (new_bucket->data)
-           {
-             if (cursor == bucket)
-               {
-                 /* Allocate or recycle an entry, when moving from a bucket
-                    header into a bucket overflow.  */
-                 struct hash_entry *new_entry = allocate_entry (new_table);
-
-                 if (new_entry == NULL)
-                   return false;
-
-                 new_entry->data = data;
-                 new_entry->next = new_bucket->next;
-                 new_bucket->next = new_entry;
-               }
-             else
-               {
-                 /* Merely relink an existing entry, when moving from a
-                    bucket overflow into a bucket overflow.  */
-                 cursor->next = new_bucket->next;
-                 new_bucket->next = cursor;
-               }
-           }
-         else
-           {
-             /* Free an existing entry, when moving from a bucket
-                overflow into a bucket header.  Also take care of the
-                simple case of moving from a bucket header into a bucket
-                header.  */
-             new_bucket->data = data;
-             new_table->n_buckets_used++;
-             if (cursor != bucket)
-               free_entry (new_table, cursor);
-           }
-       }
+  if (transfer_entries (new_table, table, false))
+    {
+      /* Entries transferred successfully; tie up the loose ends.  */
+      free (table->bucket);
+      table->bucket = new_table->bucket;
+      table->bucket_limit = new_table->bucket_limit;
+      table->n_buckets = new_table->n_buckets;
+      table->n_buckets_used = new_table->n_buckets_used;
+      table->free_entry_list = new_table->free_entry_list;
+      /* table->n_entries and table->entry_stack already hold their value.  */
+      return true;
+    }
 
-  free (table->bucket);
-  table->bucket = new_table->bucket;
-  table->bucket_limit = new_table->bucket_limit;
-  table->n_buckets = new_table->n_buckets;
-  table->n_buckets_used = new_table->n_buckets_used;
+  /* We've allocated new_table->bucket (and possibly some entries),
+     exhausted the free list, and moved some but not all entries into
+     new_table.  We must undo the partial move before returning
+     failure.  The only way to get into this situation is if new_table
+     uses fewer buckets than the old table, so we will reclaim some
+     free entries as overflows in the new table are put back into
+     distinct buckets in the old table.
+
+     There are some pathological cases where a single pass through the
+     table requires more intermediate overflow entries than using two
+     passes.  Two passes give worse cache performance and takes
+     longer, but at this point, we're already out of memory, so slow
+     and safe is better than failure.  */
   table->free_entry_list = new_table->free_entry_list;
+  if (! (transfer_entries (table, new_table, true)
+        && transfer_entries (table, new_table, false)))
+    abort ();
   /* table->n_entries already holds its value.  */
-#if USE_OBSTACK
-  table->entry_stack = new_table->entry_stack;
-#endif
-  free (new_table);
-
-  return true;
+  free (new_table->bucket);
+  return false;
 }
 
 /* If ENTRY matches an entry already in the hash table, return the pointer
@@ -1030,7 +1140,25 @@ hash_delete (Hash_table *table, const void *entry)
                 : (table->n_buckets * tuning->shrink_factor
                    * tuning->growth_threshold));
 
-             hash_rehash (table, candidate);
+             if (!hash_rehash (table, candidate))
+               {
+                 /* Failure to allocate memory in an attempt to
+                    shrink the table is not fatal.  But since memory
+                    is low, we can at least be kind and free any
+                    spare entries, rather than keeping them tied up
+                    in the free entry list.  */
+#if ! USE_OBSTACK
+                 struct hash_entry *cursor = table->free_entry_list;
+                 struct hash_entry *next;
+                 while (cursor)
+                   {
+                     next = cursor->next;
+                     free (cursor);
+                     cursor = next;
+                   }
+                 table->free_entry_list = NULL;
+#endif
+               }
            }
        }
     }
@@ -1045,9 +1173,9 @@ hash_delete (Hash_table *table, const void *entry)
 void
 hash_print (const Hash_table *table)
 {
-  struct hash_entry const *bucket;
+  struct hash_entry *bucket = (struct hash_entry *) table->bucket;
 
-  for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
+  for ( ; bucket < table->bucket_limit; bucket++)
     {
       struct hash_entry *cursor;