nserver

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | LICENSE

commit 550c619a4ae80cd160260452369f0dcf7e7a0421
parent 239aec3926ca588d7e0c04ed3005741f4224b630
Author: rsiddharth <s@ricketyspace.net>
Date:   Sat, 11 Apr 2020 11:24:32 -0400

nserver: Add db_store.

* nserver/src/db.c (db_store): New function definition.
* nserver/src/db.h (db_store): New function declaration.
* nserver/tests/db_tests.c (test_db_store): New test.

Diffstat:
nserver/src/db.c | 50++++++++++++++++++++++++++++++++++++++++++++++++++
nserver/src/db.h | 3+++
nserver/tests/db_tests.c | 12++++++++++++
3 files changed, 65 insertions(+), 0 deletions(-)

diff --git a/nserver/src/db.c b/nserver/src/db.c @@ -43,3 +43,53 @@ int db_init() error: return -1; } + + +int db_store(char *key, char *value) +{ + datum *k_datum = NULL, *v_datum = NULL; + GDBM_FILE gf = NULL; + + check(key != NULL && strlen(key) > 0, "key invalid"); + check(value != NULL && strlen(value) > 0, "data invalid"); + + // make key value datum + k_datum = mk_datum(key); + check(k_datum != NULL, "key datum init failed"); + + v_datum = mk_datum(value); + check(v_datum != NULL, "value datum init failed"); + + // init db. + int rc = db_init(); + check(rc == 0, "db init failed"); + + // open the gdbm data in write mode + gf = db_open(GDBM_WRITER|GDBM_SYNC); + check(gf != NULL, "unable to open db in write mode"); + + // write key -> data to db. + rc = gdbm_store(gf, *k_datum, *v_datum, GDBM_REPLACE); + check(rc == 0, "gdbm store failed"); + + // close db + rc = gdbm_close(gf); + check(rc == 0, "gdbm close failed"); + + // cleanup. + free(k_datum); + free(v_datum); + + return 0; + error: + if (k_datum) { + free(k_datum); + } + if (v_datum) { + free(v_datum); + } + if (gf) { + gdbm_close(gf); + } + return -1; +} diff --git a/nserver/src/db.h b/nserver/src/db.h @@ -3,9 +3,12 @@ #include <gdbm.h> #include <dbg.h> +#include <stdlib.h> +#include <string.h> #include <sys/stat.h> int db_init(); +int db_store(char *key, char *value); #endif diff --git a/nserver/tests/db_tests.c b/nserver/tests/db_tests.c @@ -9,11 +9,23 @@ char *test_db_init() return NULL; } +char *test_db_store() +{ + char *k = "hello"; + char *v = "kirk"; + + int rc = db_store(k, v); + mu_assert(rc == 0, "db store failed"); + + return NULL; +} + char *all_tests() { mu_suite_start(); mu_run_test(test_db_init); + mu_run_test(test_db_store); return NULL; }