-
Notifications
You must be signed in to change notification settings - Fork 1
/
CirName.c
70 lines (58 loc) · 1.38 KB
/
CirName.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
#include "cir_internal.h"
#include <stdalign.h>
#define TABLE_SIZE 104729U
#define MAX_NAMES 806597U
struct Item {
const char *key;
uint32_t value;
};
static struct Item hashTable[TABLE_SIZE];
static const char *names[MAX_NAMES] = { "<name0>" };
static uint32_t numNames = 1;
static struct Item *
findItem(const char *name)
{
for (size_t i = CirHash_str(name) % TABLE_SIZE; hashTable[i].key; i = (i + 1) % TABLE_SIZE) {
if (!strcmp(hashTable[i].key, name)) {
return &hashTable[i];
}
}
return NULL;
}
static void
insertItem(const char *key, uint32_t value)
{
size_t i;
for (i = CirHash_str(key) % TABLE_SIZE; hashTable[i].key; i = (i + 1) % TABLE_SIZE);
hashTable[i].key = key;
hashTable[i].value = value;
}
CirName
CirName_of(const char *name)
{
const struct Item *item;
item = findItem(name);
if (item) {
return item->value;
}
if (numNames >= MAX_NAMES)
cir_fatal("too many names");
// Copy name
size_t nameLen = strlen(name);
char *nameMem = CirMem_balloc(nameLen + 1, alignof(char));
memcpy(nameMem, name, nameLen + 1);
uint32_t nameIdx = numNames++;
names[nameIdx] = nameMem;
insertItem(nameMem, nameIdx);
return nameIdx;
}
const char *
CirName_cstr(CirName name)
{
return names[name];
}
void
CirName_log(CirName name)
{
CirLog_print(CirName_cstr(name));
}