add caching API for rc_find

This commit is contained in:
Enno Rehling 2016-09-19 06:55:32 +02:00
parent f8167ed62c
commit 96d6abdc5a
3 changed files with 21 additions and 3 deletions

View File

@ -59,7 +59,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
/** external variables **/
race *races;
int num_races = 0;
static int cache_breaker;
static int rc_changes = 1;
static const char *racenames[MAXRACES] = {
"dwarf", "elf", NULL, "goblin", "human", "troll", "demon", "insect",
@ -132,6 +132,7 @@ void free_races(void) {
races = rc;
}
num_races = 0;
++rc_changes;
}
static race *rc_find_i(const char *name)
@ -153,6 +154,15 @@ const race * rc_find(const char *name) {
return rc_find_i(name);
}
bool rc_changed(int *cache) {
assert(cache);
if (*cache != rc_changes) {
*cache = rc_changes;
return true;
}
return false;
}
race *rc_get_or_create(const char *zName)
{
race *rc;
@ -180,7 +190,7 @@ race *rc_get_or_create(const char *zName)
for (i = 1; i < RACE_ATTACKS; ++i)
rc->attack[i].type = AT_NONE;
rc->index = num_races++;
++cache_breaker;
++rc_changes;
rc->next = races;
return races = rc;
}

View File

@ -180,6 +180,7 @@ extern "C" {
race_t old_race(const struct race *);
race *rc_get_or_create(const char *name);
bool rc_changed(int *cache);
const race *rc_find(const char *);
void free_races(void);

View File

@ -50,11 +50,18 @@ static void test_rc_find(CuTest *tc) {
}
static void test_race_get(CuTest *tc) {
int cache;
race *rc;
test_setup();
CuAssertTrue(tc, rc_changed(&cache));
CuAssertTrue(tc, !rc_changed(&cache));
rc = get_race(RC_ELF);
CuAssertPtrEquals(tc, rc, (void *)rc_find("elf"));
CuAssertPtrEquals(tc, rc, (void *)rc_get_or_create("elf"));
CuAssertTrue(tc, rc_changed(&cache));
CuAssertTrue(tc, !rc_changed(&cache));
CuAssertPtrEquals(tc, rc, (void *)rc_find("elf"));
free_races();
CuAssertTrue(tc, rc_changed(&cache));
test_cleanup();
}