Skip to content

Commit

Permalink
Merge pull request #149 from visitorckw/trie-tail-call-optimization
Browse files Browse the repository at this point in the history
Optimize trie operations by replacing tail recursion with iteration
  • Loading branch information
jserv authored Aug 14, 2024
2 parents 2b9ad5d + 0cbfc78 commit 1586eb1
Showing 1 changed file with 37 additions and 25 deletions.
62 changes: 37 additions & 25 deletions src/globals.c
Original file line number Diff line number Diff line change
Expand Up @@ -87,25 +87,31 @@ char *elf_section;
*/
int insert_trie(trie_t *trie, char *name, int funcs_index)
{
char first_char = *name;
int fc = first_char;
if (!fc) {
if (!trie->index)
trie->index = funcs_index;
return trie->index;
}
if (!trie->next[fc]) {
/* FIXME: The func_tries_idx variable may exceed the maximum number,
* which can lead to a segmentation fault. This issue is affected by the
* number of functions and the length of their names. The proper way to
* handle this is to dynamically allocate a new element.
*/
trie->next[fc] = func_tries_idx++;
for (int i = 0; i < 128; i++)
FUNC_TRIES[trie->next[fc]].next[i] = 0;
FUNC_TRIES[trie->next[fc]].index = 0;
char first_char;
int fc;

while (1) {
first_char = *name;
fc = first_char;
if (!fc) {
if (!trie->index)
trie->index = funcs_index;
return trie->index;
}
if (!trie->next[fc]) {
/* FIXME: The func_tries_idx variable may exceed the maximum number,
* which can lead to a segmentation fault. This issue is affected by
* the number of functions and the length of their names. The proper
* way to handle this is to dynamically allocate a new element.
*/
trie->next[fc] = func_tries_idx++;
for (int i = 0; i < 128; i++)
FUNC_TRIES[trie->next[fc]].next[i] = 0;
FUNC_TRIES[trie->next[fc]].index = 0;
}
trie = &FUNC_TRIES[trie->next[fc]];
name = name + 1;
}
return insert_trie(&FUNC_TRIES[trie->next[fc]], name + 1, funcs_index);
}

/**
Expand All @@ -120,13 +126,19 @@ int insert_trie(trie_t *trie, char *name, int funcs_index)
*/
int find_trie(trie_t *trie, char *name)
{
char first_char = *name;
int fc = first_char;
if (!fc)
return trie->index;
if (!trie->next[fc])
return 0;
return find_trie(&FUNC_TRIES[trie->next[fc]], name + 1);
char first_char;
int fc;

while (1) {
first_char = *name;
fc = first_char;
if (!fc)
return trie->index;
if (!trie->next[fc])
return 0;
trie = &FUNC_TRIES[trie->next[fc]];
name = name + 1;
}
}

/* options */
Expand Down

0 comments on commit 1586eb1

Please sign in to comment.