From 8e16263ad2bf6c8e319c0ecf1bad9cf5f597e2df Mon Sep 17 00:00:00 2001 From: Alex 'AdUser' Z Date: Wed, 28 Dec 2016 17:41:56 +1000 Subject: [PATCH] * more error codes --- src/database.c | 13 +++++++++---- src/database.h | 2 ++ tests/database.c | 4 ++-- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/database.c b/src/database.c index 5e41b8b..fa579fc 100644 --- a/src/database.c +++ b/src/database.c @@ -152,6 +152,10 @@ imdb_error(int error) { return "database corrupted"; } else if (error == IMDB_ERR_WRONGVERS) { return "database version differs from library version"; + } else if (error == IMDB_ERR_READONLY) { + return "database opened in read-only mode"; + } else if (error == IMDB_ERR_NXRECORD) { + return "no such record in database"; } return "unknown error"; } @@ -167,7 +171,7 @@ int imdb_read_rec(imdb_db_t *db, imdb_rec_t *rec) DB_READ(db, rec->data, IMDB_REC_LEN, rec->num * IMDB_REC_LEN); if (bytes != IMDB_REC_LEN) - return errno ? IMDB_ERR_SYSTEM : 0; + return errno ? IMDB_ERR_SYSTEM : IMDB_ERR_NXRECORD; if (rec->data[0] != 0xFF) return 0; @@ -183,6 +187,9 @@ int imdb_write_rec(imdb_db_t *db, imdb_rec_t *rec) assert(rec != NULL); assert(rec->num > 0); + if (!(db->flags & IMDB_FLAG_WRITE)) + return IMDB_ERR_READONLY; + DB_WRITE(db, rec->data, IMDB_REC_LEN, rec->num * IMDB_REC_LEN); if (bytes != IMDB_REC_LEN) @@ -259,10 +266,8 @@ imdb_search(imdb_db_t * const db, blk.start = 1; blk.records = blk_size; - if ((ret = imdb_read_rec(db, sample)) < 1) { - strncpy(db->error, "Can't read source sample", sizeof(db->error)); + if ((ret = imdb_read_rec(db, sample)) < 1) return ret; - } if (search->limit == 0) search->limit = -1; /* unsigned -> max */ diff --git a/src/database.h b/src/database.h index 2257b75..c5eaa51 100644 --- a/src/database.h +++ b/src/database.h @@ -19,6 +19,8 @@ #define IMDB_ERR_OOM -2 /* can't allocate memory */ #define IMDB_ERR_CORRUPTDB -3 /* empty or currupted database */ #define IMDB_ERR_WRONGVERS -4 /* database version mismatch */ +#define IMDB_ERR_NXRECORD -5 /* no such record in database */ +#define IMDB_ERR_READONLY -6 /* database opened in read-only mode */ typedef struct { int fd; diff --git a/tests/database.c b/tests/database.c index b980a67..62d65a9 100644 --- a/tests/database.c +++ b/tests/database.c @@ -24,13 +24,13 @@ int main() rec[0].num = 1; err = imdb_read_rec(db, rec); - assert(err == 0); /* no such record */ + assert(err == IMDB_ERR_NXRECORD); memset(rec[0].data, 0xAA, IMDB_REC_LEN); memset(rec[0].data, 0xFF, 1); /* record is used */ num = imdb_write_rec(db, rec); - assert(num != 1); /* database open in read-only mode */ + assert(num == IMDB_ERR_READONLY); /* database open in read-only mode */ imdb_close(db);