-
Notifications
You must be signed in to change notification settings - Fork 0
/
fixed_set.h
79 lines (61 loc) · 1.63 KB
/
fixed_set.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
72
73
74
75
76
77
78
79
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include "../allocators/scratch.h"
#include "hashes.h"
typedef struct {
char **entries;
uint64_t capacity;
ScratchAlloc *scr;
} FixedSet;
void fixed_set_clear(FixedSet *s) {
for (int i = 0; i < s->capacity; i++) {
s->entries[i] = NULL;
}
}
FixedSet fixed_set_init(ScratchAlloc *scr, int elem_count) {
FixedSet s;
int start_count = elem_count;
if (start_count == 0) {
start_count = 8;
}
s.entries = scratch_alloc(scr, sizeof(char *) * start_count);
s.capacity = start_count;
fixed_set_clear(&s);
return s;
}
bool fixed_set_insert(FixedSet *s, char *str) {
uint64_t hash_val = murmur32(str, strlen(str)) % s->capacity;
for (uint64_t i = 0; i < s->capacity; i++) {
uint64_t cur_idx = (hash_val + i) % s->capacity;
char *cur_entry = s->entries[cur_idx];
// Did we find an empty slot?
if (cur_entry == NULL) {
s->entries[cur_idx] = str;
return true;
// If the string is already in our set, we're all good
} else if (strcmp(cur_entry, str) == 0) {
return true;
}
}
// Our hashset is completely full?
return false;
}
bool fixed_set_contains(FixedSet *s, char *str) {
uint64_t hash_val = murmur32(str, strlen(str)) % s->capacity;
for (uint64_t i = 0; i < s->capacity; i++) {
uint64_t cur_idx = (hash_val + i) % s->capacity;
char *cur_entry = s->entries[cur_idx];
// Did we find an empty slot?
if (cur_entry == NULL) {
return false;
// If the string is already in our set, we're all good
} else if (strcmp(cur_entry, str) == 0) {
return true;
}
}
// The hashset is completely full?
return false;
}