Browse Source

+ block_t

master
Alex 'AdUser' Z 11 years ago
parent
commit
beb14b9911
  1. 33
      src/database.c
  2. 10
      src/database.h
  3. 9
      tests/database.c

33
src/database.c

@ -121,33 +121,22 @@ int db_wr_rec(db_t *db, rec_t *rec)
return bytes / REC_LEN; return bytes / REC_LEN;
} }
int db_rd_blk(db_t *db, uint64_t start, size_t len, rec_t *list) int db_rd_blk(db_t *db, block_t *blk)
{ {
rec_t *r = NULL;
ssize_t bytes = 0; ssize_t bytes = 0;
unsigned int i = 0;
unsigned char *buf;
unsigned char *p = NULL;
assert(db != NULL);
assert(list != NULL);
assert(len > 0);
CALLOC(buf, len, REC_LEN); assert(db != NULL);
DB_SEEK(db, start * REC_LEN); assert(blk != NULL);
DB_READ(db, buf, len * REC_LEN); assert(blk->start > 0);
assert(blk->records > 0);
p = buf;
r = list;
len = bytes / REC_LEN;
for (i = 0; i < len; i++, r++, p += REC_LEN) {
r->num = start + i;
memcpy(r->data, p, REC_LEN);
}
FREE(buf); FREE(blk->data);
CALLOC(blk->data, blk->records, REC_LEN);
DB_SEEK(db, blk->start * REC_LEN);
DB_READ(db, blk->data, blk->records * REC_LEN);
blk->records = bytes / REC_LEN;
return len; return blk->records;
} }
int db_rd_list(db_t *db, rec_t *list, size_t list_len) int db_rd_list(db_t *db, rec_t *list, size_t list_len)

10
src/database.h

@ -10,6 +10,12 @@ typedef struct {
const char *errstr; const char *errstr;
} db_t; } db_t;
typedef struct {
uint64_t start;
size_t records;
unsigned char *data;
} block_t;
typedef struct { typedef struct {
uint64_t num; uint64_t num;
unsigned char data[REC_LEN]; unsigned char data[REC_LEN];
@ -21,8 +27,8 @@ extern int db_close(db_t *db);
extern int db_rd_rec(db_t *db, rec_t *rec); extern int db_rd_rec(db_t *db, rec_t *rec);
extern int db_wr_rec(db_t *db, rec_t *rec); extern int db_wr_rec(db_t *db, rec_t *rec);
extern int db_rd_blk(db_t *db, uint64_t start, size_t len, rec_t *list); extern int db_rd_blk(db_t *db, block_t *blk);
extern int db_wr_blk(db_t *db, uint64_t start, size_t len, rec_t *list); extern int db_wr_blk(db_t *db, block_t *blk);
extern int db_rd_list(db_t *db, rec_t *list, size_t list_len); extern int db_rd_list(db_t *db, rec_t *list, size_t list_len);
extern int db_wr_list(db_t *db, rec_t *list, size_t list_len); extern int db_wr_list(db_t *db, rec_t *list, size_t list_len);

9
tests/database.c

@ -5,6 +5,7 @@ int main(int argc, char **argv)
{ {
db_t db; db_t db;
rec_t rec[2]; rec_t rec[2];
block_t blk;
char *path = "test.db"; char *path = "test.db";
unlink(path); unlink(path);
@ -18,8 +19,12 @@ int main(int argc, char **argv)
assert(db_rd_rec(&db, rec) == 1); assert(db_rd_rec(&db, rec) == 1);
assert(db_rd_blk(&db, 1, 1, rec) == 1); blk.start = 1;
assert(db_rd_blk(&db, 1, 2, rec) == 1); blk.records = 2;
blk.data = NULL;
assert(db_rd_blk(&db, &blk) == 1);
assert(blk.records == 1);
assert(blk.data != NULL);
rec[0].num = 1; rec[0].num = 1;
rec[1].num = 3; rec[1].num = 3;

Loading…
Cancel
Save