shash: Refactor shash_add_nocopy(), shash_find().
authorBen Pfaff <blp@nicira.com>
Wed, 30 Jun 2010 20:22:28 +0000 (13:22 -0700)
committerBen Pfaff <blp@nicira.com>
Wed, 30 Jun 2010 23:49:00 +0000 (16:49 -0700)
By breaking out the hash calculation we can enable operations that need
to do both to avoid duplicating the hash calculations.  A following commit
will add such an operation.

lib/shash.c

index c4d3ccb..e2b1fe2 100644 (file)
@@ -19,6 +19,9 @@
 #include <assert.h>
 #include "hash.h"
 
+static struct shash_node *shash_find__(const struct shash *,
+                                       const char *name, size_t hash);
+
 static size_t
 hash_name(const char *name)
 {
@@ -100,18 +103,24 @@ shash_count(const struct shash *shash)
     return hmap_count(&shash->map);
 }
 
-/* It is the caller's responsibility to avoid duplicate names, if that is
- * desirable. */
-struct shash_node *
-shash_add_nocopy(struct shash *sh, char *name, const void *data)
+static struct shash_node *
+shash_add_nocopy__(struct shash *sh, char *name, const void *data, size_t hash)
 {
     struct shash_node *node = xmalloc(sizeof *node);
     node->name = name;
     node->data = (void *) data;
-    hmap_insert(&sh->map, &node->node, hash_name(name));
+    hmap_insert(&sh->map, &node->node, hash);
     return node;
 }
 
+/* It is the caller's responsibility to avoid duplicate names, if that is
+ * desirable. */
+struct shash_node *
+shash_add_nocopy(struct shash *sh, char *name, const void *data)
+{
+    return shash_add_nocopy__(sh, name, data, hash_name(name));
+}
+
 /* It is the caller's responsibility to avoid duplicate names, if that is
  * desirable. */
 struct shash_node *
@@ -146,14 +155,12 @@ shash_delete(struct shash *sh, struct shash_node *node)
     free(node);
 }
 
-/* If there are duplicates, returns a random element. */
-struct shash_node *
-shash_find(const struct shash *sh, const char *name)
+static struct shash_node *
+shash_find__(const struct shash *sh, const char *name, size_t hash)
 {
     struct shash_node *node;
 
-    HMAP_FOR_EACH_WITH_HASH (node, struct shash_node, node,
-                             hash_name(name), &sh->map) {
+    HMAP_FOR_EACH_WITH_HASH (node, struct shash_node, node, hash, &sh->map) {
         if (!strcmp(node->name, name)) {
             return node;
         }
@@ -161,6 +168,13 @@ shash_find(const struct shash *sh, const char *name)
     return NULL;
 }
 
+/* If there are duplicates, returns a random element. */
+struct shash_node *
+shash_find(const struct shash *sh, const char *name)
+{
+    return shash_find__(sh, name, hash_name(name));
+}
+
 void *
 shash_find_data(const struct shash *sh, const char *name)
 {