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 **/ /** external variables **/
race *races; race *races;
int num_races = 0; int num_races = 0;
static int cache_breaker; static int rc_changes = 1;
static const char *racenames[MAXRACES] = { static const char *racenames[MAXRACES] = {
"dwarf", "elf", NULL, "goblin", "human", "troll", "demon", "insect", "dwarf", "elf", NULL, "goblin", "human", "troll", "demon", "insect",
@ -132,6 +132,7 @@ void free_races(void) {
races = rc; races = rc;
} }
num_races = 0; num_races = 0;
++rc_changes;
} }
static race *rc_find_i(const char *name) static race *rc_find_i(const char *name)
@ -153,6 +154,15 @@ const race * rc_find(const char *name) {
return rc_find_i(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_get_or_create(const char *zName)
{ {
race *rc; race *rc;
@ -180,7 +190,7 @@ race *rc_get_or_create(const char *zName)
for (i = 1; i < RACE_ATTACKS; ++i) for (i = 1; i < RACE_ATTACKS; ++i)
rc->attack[i].type = AT_NONE; rc->attack[i].type = AT_NONE;
rc->index = num_races++; rc->index = num_races++;
++cache_breaker; ++rc_changes;
rc->next = races; rc->next = races;
return races = rc; return races = rc;
} }

View file

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

View file

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