-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringstore.cpp
More file actions
45 lines (39 loc) · 1.53 KB
/
stringstore.cpp
File metadata and controls
45 lines (39 loc) · 1.53 KB
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
struct Stringstore {
Hashmap<s64> string_map;
Array_dyn<Offset<u8>> strings;
Array_dyn<u8> string_data;
bool c_str = false;
s64 size = 0;
};
void stringstore_free(Stringstore* store) {
hashmap_free(&store->string_map);
array_free(&store->strings);
array_free(&store->string_data);
}
s64 stringstore_get_id(Stringstore* store, Array<u8> str, bool nocreate=false) {
u64 hash_base = hash_str(str);
hash_base += hash_base == 0;
for (u64 adj = 0;; ++adj) {
auto* ptr = hashmap_getcreate(&store->string_map, hash_base + adj, (s64)-1);
if (*ptr == -1) {
if (nocreate) return -1;
*ptr = store->strings.size;
array_push(&store->strings, array_append(&store->string_data, str));
if (store->c_str) array_push(&store->string_data, 0);
++store->size;
return *ptr;
} else {
auto str_stored = array_suboffset(store->string_data, store->strings[*ptr]);
if (array_equal(str_stored, str)) return *ptr;
}
}
}
// Deprecated! This used to return 0 on non-existence. Instead call stringstore_get_id(..., nocreate=true) and check for -1.
//u64 stringstore_get_id_if_exists(Stringstore* store, Array<u8> str);
Array<u8> stringstore_get_str(Stringstore* store, s64 id) {
return array_suboffset(store->string_data, store->strings[id]);
}
char* stringstore_get_cstr(Stringstore* store, s64 id) {
assert(store->c_str);
return (char*)array_suboffset(store->string_data, store->strings[id]).data;
}