nserver

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

commit 49edbb003a0aef0fd864e5f2a12228807618a175
parent 550c619a4ae80cd160260452369f0dcf7e7a0421
Author: rsiddharth <s@ricketyspace.net>
Date:   Sat, 11 Apr 2020 11:27:21 -0400

nserver: Add db_load.

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

Diffstat:
nserver/src/db.c | 40+++++++++++++++++++++++++++++++++++++---
nserver/src/db.h | 1+
nserver/tests/db_tests.c | 17+++++++++++++++++
3 files changed, 55 insertions(+), 3 deletions(-)

diff --git a/nserver/src/db.c b/nserver/src/db.c @@ -22,13 +22,11 @@ datum *mk_datum(char *data) return NULL; } - GDBM_FILE db_open(int flags) { return gdbm_open(DB_FILE, 0,flags, S_IRUSR|S_IWUSR, NULL); } - int db_init() { // Create DB if it's not already created. @@ -44,7 +42,6 @@ int db_init() return -1; } - int db_store(char *key, char *value) { datum *k_datum = NULL, *v_datum = NULL; @@ -93,3 +90,40 @@ int db_store(char *key, char *value) } return -1; } + +char *db_load(char *key) +{ + datum *k_datum = NULL; + GDBM_FILE gf = NULL; + + check(key != NULL && strlen(key) > 0, "key invalid"); + + // make key datum + k_datum = mk_datum(key); + check(k_datum != NULL, "key datum init failed"); + + // init db. + int rc = db_init(); + check(rc == 0, "db init failed"); + + // open the gdbm data in read mode + gf = db_open(GDBM_READER|GDBM_SYNC); + check(gf != NULL, "unable to open db in read mode"); + + // try to fetch value for key. + datum v_datum = gdbm_fetch(gf, *k_datum); + check(v_datum.dptr != NULL, "key not found"); + + // clean up. + free(k_datum); + + return v_datum.dptr; + error: + if (k_datum) { + free(k_datum); + } + if (gf) { + gdbm_close(gf); + } + return NULL; +} diff --git a/nserver/src/db.h b/nserver/src/db.h @@ -9,6 +9,7 @@ int db_init(); int db_store(char *key, char *value); +char *db_load(char *key); #endif diff --git a/nserver/tests/db_tests.c b/nserver/tests/db_tests.c @@ -20,12 +20,29 @@ char *test_db_store() return NULL; } +char *test_db_load() +{ + char *k = "hello"; + char *expected_v = "kirk"; + + char *v = db_load(k); + mu_assert(v != NULL, "key not found"); + mu_assert(strncmp(v, expected_v, strlen(expected_v)) == 0, + "incorrect value for key"); + + // cleanup. + free(v); + + return NULL; +} + char *all_tests() { mu_suite_start(); mu_run_test(test_db_init); mu_run_test(test_db_store); + mu_run_test(test_db_load); return NULL; }