aboutsummaryrefslogtreecommitdiff
path: root/src/db.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/db.c')
-rw-r--r--src/db.c31
1 files changed, 27 insertions, 4 deletions
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);
@@ -125,8 +140,11 @@ 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;
}