-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap2.h
71 lines (60 loc) · 2.21 KB
/
map2.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Separate Chaining map using linked lists.
* From https://www.andreinc.net/2021/10/02/implementing-hash-tables-in-c-part-1
* This is a naive implementation, it is not cache friendly since it use a linked list.
*/
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#ifndef MAP2_H
#define MAP2_H
#define HASH_CAPACITY_INIT 32
#define HASH_CAPACITY_MULT 2
#define HASH_GROWTH 1
typedef struct MapNode
{
uint32_t hash;
void *key;
void *val;
struct MapNode *next;
} MapNode;
/* MapNodeKeyOps and MapNodeValOps are traits that allow users to
specify how the hash is computed, how its copied and how memory is managed. */
typedef struct MapNodeKeyOps
{
uint32_t (*hash)(const void *data, void *arg);
void *(*cp)(const void *data, void *arg);
void (*free)(void *data, void *arg);
bool (*eq)(const void *data1, const void *data2, void *arg);
void *arg;
} MapNodeKeyOps;
typedef struct MapNodeValOps
{
void *(*cp)(const void *data, void *arg);
void (*free)(void *data, void *arg);
bool (*eq)(const void *data1, const void *data2, void *arg);
void *arg;
} MapNodeValOps;
typedef struct MapHashTable {
size_t capacity; /* total number of available buckets */
size_t size; /* The total number of elements */
MapNode** buckets;
MapNodeKeyOps key_ops;
MapNodeValOps val_ops;
} MapHashTable;
extern MapHashTable* create_MapHashTable(MapNodeKeyOps key_ops, MapNodeValOps val_ops);
extern void free_MapHashTable(MapHashTable* hashtable);
extern void* get_MapHashTable(MapHashTable* hashtable, const void* key);
extern bool contains_MapHashTable(MapHashTable* hashtable, const void* key);
extern void put_MapHashTable(MapHashTable* hashtable, const void* key, const void* val);
extern void print_MapHashTable(MapHashTable* hashtable, void (*print_key)(const void* key), void (*print_val)(const void* val));
extern uint32_t numCol_MapHashTable(MapHashTable* hashtable);
/* String Operations */
uint32_t string_hash(const void *data, void *arg);
void* string_cp(const void *data, void *arg);
bool string_eq(const void *data1, const void *data2, void *arg);
void string_free(void *data, void *arg);
void string_print(const void *data);
extern MapNodeKeyOps key_ops_string;
extern MapNodeValOps val_ops_string;
#endif