From becc37649c55bf7d673efc2d96bb099824032f42 Mon Sep 17 00:00:00 2001 From: tlatorre Date: Thu, 7 Mar 2019 16:31:34 -0600 Subject: update fit to automatically load DQXX file based on run number --- src/db.c | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) (limited to 'src/db.c') diff --git a/src/db.c b/src/db.c index d364503..5b29b66 100644 --- a/src/db.c +++ b/src/db.c @@ -35,7 +35,22 @@ static dictType titleDB = { /* Add a bank to the database. * - * Returns 0 on success, -1 on error. */ + * If a bank with the same name and id already exists, it will be replaced. */ +void replace_bank(dict *db, const char name[4], uint32_t id, dbval *data) +{ + uint32_t *buf = malloc(sizeof(uint32_t)*2); + + memcpy(buf,name,4); + buf[1] = id; + + /* If the bank already exists, dictReplace will keep the old key, so we + * have to free `buf`. */ + if (!dictReplace(db, buf, data)) free(buf); +} + +/* Add a bank to the database. + * + * Returns 0 on success, -1 if the key already exists. */ int add_bank(dict *db, const char name[4], uint32_t id, dbval *data) { uint32_t *buf = malloc(sizeof(uint32_t)*2); @@ -124,9 +139,12 @@ void db_free(dict *db) } /* Load a title bank file into the database `db`. + * + * If `replace` is 0, then loading an already existing bank will cause an + * error. Otherwise, the bank will be replaced. * * Returns 0 on success, -1 on error. */ -int load_file(dict *db, const char *filename) +int load_file(dict *db, const char *filename, int replace) { int i, index; char *item, *s; @@ -152,6 +170,7 @@ int load_file(dict *db, const char *filename) if (!f) { sprintf(db_err, "unable to open file '%s': %s", filename, strerror(errno)); + free(buf); return -1; } @@ -186,7 +205,9 @@ int load_file(dict *db, const char *filename) /* Save previous bank. */ buf = realloc(buf,sizeof(dbval)*index); - if (add_bank(db, idh, idn, buf) == DICT_ERR) { + if (replace) { + replace_bank(db, idh, idn, buf); + } else if (add_bank(db, idh, idn, buf) == DICT_ERR) { sprintf(db_err, "bank '%.4s' already exists in the database", idh); goto err; } @@ -240,7 +261,9 @@ int load_file(dict *db, const char *filename) buf = realloc(buf,sizeof(dbval)*index); - if (add_bank(db, idh, idn, buf) == DICT_ERR) { + if (replace) { + replace_bank(db, idh, idn, buf); + } else if (add_bank(db, idh, idn, buf) == DICT_ERR) { sprintf(db_err, "bank '%.4s' already exists in the database", idh); goto err; } -- cgit