Browse Source

* add simdb_{read,write}()

master
Alex 'AdUser' Z 8 years ago
parent
commit
c4359f673f
  1. 61
      src/database.c
  2. 35
      src/io.h

61
src/database.c

@ -22,6 +22,7 @@
#include "common.h"
#include "bitmap.h"
#include "record.h"
#include "io.h"
#include "simdb.h"
struct _simdb_t {
@ -176,6 +177,66 @@ simdb_error(int error) {
return "unknown error";
}
int
simdb_read(simdb_t *db, int start, int records, simdb_urec_t **data) {
simdb_urec_t *tmp;
off_t offset = 0;
ssize_t bytes = 0;
assert(db != NULL);
assert(data != NULL);
if (start < 1 || records < 1)
return SIMDB_ERR_USAGE;
offset = SIMDB_REC_LEN * start;
bytes = SIMDB_REC_LEN * records;
if ((tmp = calloc(1, bytes)) == NULL)
return SIMDB_ERR_OOM;
if ((bytes = pread(db->fd, tmp, bytes, offset)) < 0) {
free(tmp);
return SIMDB_ERR_SYSTEM;
}
records = bytes / SIMDB_REC_LEN;
if (records <= 0) {
free(tmp);
return 0;
}
*data = tmp;
return records;
}
int
simdb_write(simdb_t *db, int start, int records, simdb_urec_t *data) {
off_t offset = 0;
ssize_t bytes = 0;
assert(db != NULL);
assert(data != NULL);
if (start < 1 || records < 1)
return SIMDB_ERR_USAGE;
if (!(db->flags & SIMDB_FLAG_WRITE))
return SIMDB_ERR_READONLY;
offset = SIMDB_REC_LEN * start;
bytes = SIMDB_REC_LEN * records;
if ((bytes = pwrite(db->fd, data, bytes, offset)) < 0)
return SIMDB_ERR_SYSTEM;
records = bytes / SIMDB_REC_LEN;
if (records <= 0)
return 0;
return records;
}
int simdb_record_read(simdb_t *db, simdb_rec_t *rec) {
ssize_t bytes = 0;

35
src/io.h

@ -0,0 +1,35 @@
#ifndef HAS_IO_H
#define HAS_IO_H 1
/**
* @file
* @brief This file contains definitions of internal i/o functions, used by database
*/
/**
* @brief Read records from database
* @param db Database handle
* @param start First record number
* @param records Records count to read
* @param data Storage for records data (allocated)
* @retval <0 on error
* @retval 0 on no records read
* @retval >0 as records count actually read
* @note If at least one record read, contents of @a data pointer
* must be freed by user
*/
int simdb_read(simdb_t *db, int start, int records, simdb_urec_t **data);
/**
* @brief Write records to database
* @param db Database handle
* @param start First record number
* @param records Records count to read
* @param data Pointer to records data
* @retval <0 on error
* @retval 0 on no records written
* @retval >0 as records count actually written
*/
int simdb_write(simdb_t *db, int start, int records, simdb_urec_t *data);
#endif
Loading…
Cancel
Save