-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.c
153 lines (120 loc) · 2.93 KB
/
map.c
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#include "map.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
map *new_map_sized(uint64_t size)
{
map *m = malloc(sizeof(map));
/*
* Calloc zeroes the memory, which is what we want.
*/
map_node empty = EMPTY_NODE;
m->items = calloc(size, sizeof(map_node));
m->len = MAP_ALLOC_SIZE;
m->full = 0;
for (int i = 0 ; i < m->len; i++)
{
m->items[i] = empty;
}
return m;
}
map *new_map()
{
return new_map_sized(MAP_ALLOC_SIZE);
}
void free_map(map *m)
{
/* gotta be a more efficient way to do this kek */
for (int i = 0; i < m->len; i++)
{
if (m->items[i].key != NULL)
{
free(m->items[i].key);
free(m->items[i].val);
}
}
free(m->items);
free(m);
}
void map_set(map *m, char *k, void *v)
{
uint64_t h = hash(k);
uint32_t i = h % m->len;
printf("hash %u i %u\n", h, i);
m->count++;
if (m->full++ < m->len)
{
puts("not full");
map_node val =
{
malloc(strlen(k)),
v,
0,
h,
};
strcpy(val.key, k);
uint32_t current = i;
while (MAP_USED_AT(m->items, current))
if (current == m->len - 1)
current = 0;
else
current++;
printf("Current %d\n", current);
m->items[current] = val;
printf("val %d\n", *(int *)m->items[current].val);
}
else
{
puts("resizing");
/* resize map */
map *n_m = new_map_sized(m->len * 2);
for (uint64_t j = 0; j < m->len; j++)
{
if (!MAP_USED_AT(m->items, j))
continue;
uint32_t current = m->items[j].h;
while (MAP_USED_AT(m->items, current))
if (current == m->len - 1)
current = 0;
else
current++;
n_m->items[current] = m->items[j];
}
free_map(m);
m = n_m;
}
}
void *map_get(map *m, char *k)
{
uint64_t h = hash(k);
uint32_t i = h % m->len;
uint32_t current = i;
printf("%s should be %s\n", m->items[current].key, k);
printf("streq %d\n", strcmp(m->items[current].key, k));
printf("Current get %d\n", current);
while (strcmp(m->items[current].key, k) != 0)
{
printf("While at %d\n", current);
if (current >= m->len - 1)
{
current = 0;
printf("Current reset to 0\n");
}
else
{
current++;
printf("Incrementing current\n");
}
}
printf("val %d\n", *(int *)m->items[current].val);
return m->items[current].val;
//return 1;
}
void map_debug(map *m)
{
for (int i = 0; i < m->len; i++)
{
if (m->items[i].val != NULL)
printf("i = %d, k = %s, v = %d\n", i, m->items[i].key, *(int *)m->items[i].val);
}
}