Skip to content

Commit

Permalink
htable: use precalculated list of primes (#3739)
Browse files Browse the repository at this point in the history
  • Loading branch information
dtikhonov authored May 31, 2023
1 parent 1765d0c commit 7731536
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 12 deletions.
19 changes: 19 additions & 0 deletions extra-cmds/utiltest.c
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,24 @@ static void test_htable_update(void)
hashTableDelete(htable);
}

static void test_htable_grow(void)
{
hashTable *htable;
int i;
char keyBuf[20];

htable = hashTableNew (3, hashCstrhash, hashCstreq, eFree, NULL);

for (i = 0; i < 1000; ++i)
{
snprintf(keyBuf, sizeof(keyBuf), "str_%d", i);
hashTablePutItem (htable, strdup(keyBuf), strdup(keyBuf));
}

TEST_CHECK (strcmp (hashTableGetItem (htable, "str_123"), "str_123") == 0);
hashTableDelete(htable);
}

static void test_routines_strrstr(void)
{
TEST_CHECK(strcmp(strrstr("abcdcdb", "cd"), "cdb") == 0);
Expand All @@ -225,6 +243,7 @@ TEST_LIST = {
{ "fname/absolute+cache", test_fname_absolute_with_cache },
{ "fname/relative", test_fname_relative },
{ "htable/update", test_htable_update },
{ "htable/grow", test_htable_grow },
{ "routines/strrstr", test_routines_strrstr },
{ NULL, NULL } /* zeroed record marking the end of the list */
};
25 changes: 13 additions & 12 deletions main/htable.c
Original file line number Diff line number Diff line change
Expand Up @@ -258,24 +258,25 @@ static void hashTablePutItem00 (hashTable *htable, void *key, void *val
htable->count++;
}

/* TODO: A pre-calculated array can be used instead of
* finding a new one at runtume. */
/* "doubling" primes smaller than 2^32 */
static const unsigned int primes[] = {
3, 7, 17, 37, 79, 163, 331, 673, 1361, 2729, 5471, 10949, 21911,
43853, 87719, 175447, 350899, 701819, 1403641, 2807303, 5614657,
11229331, 22458671, 44917381, 89834777, 179669557, 359339171,
718678369, 1437356741, 2874713497,
};

static unsigned int
prime_double(unsigned int i)
{
unsigned int j;

Assert (i > 2);
Assert (i % 2);

for (unsigned int c = 2 * i + 1; ; c += 2)
{
for (unsigned int i0 = 3; i0 < i; i0 += 2)
{
if ((c % i0) == 0)
goto next;
}
return c;
next:;
}
for (j = 0; j < sizeof(primes) / sizeof(primes[0]); ++j)
if (primes[j] > i)
return primes[j];

return i;
}
Expand Down

0 comments on commit 7731536

Please sign in to comment.