summaryrefslogtreecommitdiff
path: root/compiler/hashmap.c
blob: e567224039c64e7466fc41ddcd856e9cdac60c84 (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
/*
 * Tiny hashmap implementation.
 * Copyright (c) 2023-2024, Quinn Stephens and the OSMORA team.
 * Provided under the BSD 3-Clause license.
 */

#include <stddef.h>
#include <stdlib.h>
#include "hashmap.h"

void
hashmap_add(struct hashmap *map, struct hashmap_entry *entry)
{
    list_prepend(&map->rows[entry->hash % map->n_rows], &entry->list_entry);
}

struct hashmap_entry *
hashmap_find(struct hashmap *map, hash_t hash)
{
    struct hashmap_entry *entry;

    entry = (struct hashmap_entry*)map->rows[hash % map->n_rows].head;
    while (entry != (struct hashmap_entry*)&map->rows[hash % map->n_rows]) {
        if (entry->hash == hash) {
            return entry;
        }

        entry = (struct hashmap_entry*)entry->list_entry.next;
    }

    return NULL;
}

void
hashmap_free_entries(struct hashmap *map)
{
    struct hashmap_entry *ent, *next;

    for (size_t r = 0; r < map->n_rows; r++) {
        ent = (struct hashmap_entry*)map->rows[r].head;
        while (ent != (struct hashmap_entry*)&map->rows[r]) {
            next = (struct hashmap_entry*)ent->list_entry.next;
            free(ent);
            ent = next;
        }
    }
}

void
hashmap_init(struct hashmap *map)
{
    for (size_t r = 0; r < map->n_rows; r++) {
        list_init(&map->rows[r]);
    }
}