Skip to content

Commit 7d9c71e

Browse files
anakryikoAlexei Starovoitov
authored andcommitted
libbpf: Extract generic string hashing function for reuse
Calculating a hash of zero-terminated string is a common need when using hashmap, so extract it for reuse. Signed-off-by: Andrii Nakryiko <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Acked-by: John Fastabend <[email protected]> Link: https://lore.kernel.org/bpf/[email protected]
1 parent 192f5a1 commit 7d9c71e

File tree

2 files changed

+13
-8
lines changed

2 files changed

+13
-8
lines changed

tools/lib/bpf/btf_dump.c

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -90,14 +90,7 @@ struct btf_dump {
9090

9191
static size_t str_hash_fn(const void *key, void *ctx)
9292
{
93-
const char *s = key;
94-
size_t h = 0;
95-
96-
while (*s) {
97-
h = h * 31 + *s;
98-
s++;
99-
}
100-
return h;
93+
return str_hash(key);
10194
}
10295

10396
static bool str_equal_fn(const void *a, const void *b, void *ctx)

tools/lib/bpf/hashmap.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,18 @@ static inline size_t hash_bits(size_t h, int bits)
2525
#endif
2626
}
2727

28+
/* generic C-string hashing function */
29+
static inline size_t str_hash(const char *s)
30+
{
31+
size_t h = 0;
32+
33+
while (*s) {
34+
h = h * 31 + *s;
35+
s++;
36+
}
37+
return h;
38+
}
39+
2840
typedef size_t (*hashmap_hash_fn)(const void *key, void *ctx);
2941
typedef bool (*hashmap_equal_fn)(const void *key1, const void *key2, void *ctx);
3042

0 commit comments

Comments
 (0)