aboutsummaryrefslogtreecommitdiff
path: root/include/std_gc/hash_map.h
blob: fb6221bc9547422802a74689389f05d08f2f2d77 (plain)
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
#ifndef TSL_HASH_MAP_H
#define TSL_HASH_MAP_H

#include "../forward_decl.h"
#include "../value.h"
#include <stdint.h>
#include <stddef.h>

typedef struct TslHashMapNode TslHashMapNode;
struct TslHashMapNode {
    uint64_t hash;
    TslValue key;
    TslValue value;
    TslHashMapNode *next;
};

/* TODO: Optimize small hash map by using the members of the struct instead of allocating on heap */
struct TslHashMap {
    void *buckets_data; /* value=TslHashMapNode */
    size_t buckets_size;
    size_t buckets_capacity;
};

typedef struct {
    TslHashMap *hash_map;
    size_t index;
    TslHashMapNode *node;
} TslHashMapIterator;

void tsl_hash_map_init(TslHashMap *self);

int tsl_hash_map_insert(TslHashMap *self, const TslValue *key, TslValue *value);
/*
    Get a reference to the value by key @key, or NULL if it doesn't exist.
    The returned pointer is only valid until until reallocation after after insert inserting a new value into the hash map.
*/
TslValue* tsl_hash_map_get(TslHashMap *self, const TslValue *key);
/*
    Get a reference to the value by key @key, or insert a new value for the key (a TslValue).
    Returns NULL on failure.
    The returned pointer is only valid until until reallocation after after insert inserting a new value into the hash map.
*/
TslValue* tsl_hash_map_get_or_create(TslHashMap *self, const TslValue *key);

/*
    How to use the iterator:

    TslHashMapIterator iterator;
    tsl_hash_map_create_iterator(hash_map, &iterator);
    while(tsl_hash_map_iterator_next(&iterator)) {
        TslValue *key = &iterator.node->key;
        TslValue *value = &iterator.node->value;
    }
*/

void tsl_hash_map_create_iterator(TslHashMap *self, TslHashMapIterator *iterator);
int tsl_hash_map_iterator_next(TslHashMapIterator *self);

#endif /* TSL_HASH_MAP_H */