rewrite the device subsystem interfaces (#48)
[lunaix-os.git] / lunaix-os / includes / lunaix / ds / hashtable.h
1 /**
2  * @file hashtable.h Simple hash table implementation.
3  * Based on
4  * https://elixir.bootlin.com/linux/v5.18.12/source/include/linux/hashtable.h
5  * @author Lunaixsky (zelong56@gmail.com)
6  * @brief
7  * @version 0.1
8  * @date 2022-07-20
9  *
10  * @copyright Copyright (c) 2022
11  *
12  */
13 #ifndef __LUNAIX_HASHTABLE_H
14 #define __LUNAIX_HASHTABLE_H
15
16 #include <klibc/hash.h>
17 #include <lunaix/ds/llist.h>
18
19 struct hbucket
20 {
21     struct hlist_node* head;
22 };
23
24 #define __hashkey(table, hash) ((hash) % (sizeof(table) / sizeof(table[0])))
25
26 #define DECLARE_HASHTABLE(name, bucket_num) struct hbucket name[(bucket_num)];
27
28 #define hashtable_bucket_foreach(bucket, pos, n, member)                       \
29     for (pos = list_entry((bucket)->head, typeof(*pos), member);               \
30          pos && ({                                                             \
31              n = list_entry(pos->member.next, typeof(*pos), member);           \
32              1;                                                                \
33          });                                                                   \
34          pos = n)
35
36 #define hashtable_hash_foreach(table, hash, pos, n, member)                    \
37     hashtable_bucket_foreach(&table[__hashkey(table, hash)], pos, n, member)
38
39 #define hashtable_init(table)                                                  \
40     {                                                                          \
41         for (u32_t i = 0; i < (sizeof(table) / sizeof(table[0])); i++) {       \
42             table[i].head = 0;                                                 \
43         }                                                                      \
44     }
45
46 #define hashtable_hash_in(table, list_node, hash)                              \
47     hlist_add(&table[__hashkey(table, hash)].head, list_node)
48
49 #endif /* __LUNAIX_HASHTABLE_H */