libbpf: Extract generic string hashing function for reuse
authorAndrii Nakryiko <andriin@fb.com>
Sat, 26 Sep 2020 01:13:52 +0000 (18:13 -0700)
committerAlexei Starovoitov <ast@kernel.org>
Tue, 29 Sep 2020 00:27:31 +0000 (17:27 -0700)
Calculating a hash of zero-terminated string is a common need when using
hashmap, so extract it for reuse.

Signed-off-by: Andrii Nakryiko <andriin@fb.com>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Acked-by: John Fastabend <john.fastabend@gmail.com>
Link: https://lore.kernel.org/bpf/20200926011357.2366158-5-andriin@fb.com
tools/lib/bpf/btf_dump.c
tools/lib/bpf/hashmap.h

index 6c079b3..91310e5 100644 (file)
@@ -90,14 +90,7 @@ struct btf_dump {
 
 static size_t str_hash_fn(const void *key, void *ctx)
 {
-       const char *s = key;
-       size_t h = 0;
-
-       while (*s) {
-               h = h * 31 + *s;
-               s++;
-       }
-       return h;
+       return str_hash(key);
 }
 
 static bool str_equal_fn(const void *a, const void *b, void *ctx)
index e0af36b..d9b385f 100644 (file)
@@ -25,6 +25,18 @@ static inline size_t hash_bits(size_t h, int bits)
 #endif
 }
 
+/* generic C-string hashing function */
+static inline size_t str_hash(const char *s)
+{
+       size_t h = 0;
+
+       while (*s) {
+               h = h * 31 + *s;
+               s++;
+       }
+       return h;
+}
+
 typedef size_t (*hashmap_hash_fn)(const void *key, void *ctx);
 typedef bool (*hashmap_equal_fn)(const void *key1, const void *key2, void *ctx);