summaryrefslogtreecommitdiffstats
path: root/squarkdb.c
diff options
context:
space:
mode:
Diffstat (limited to 'squarkdb.c')
-rw-r--r--squarkdb.c31
1 files changed, 25 insertions, 6 deletions
diff --git a/squarkdb.c b/squarkdb.c
index 543cbb1..e05f514 100644
--- a/squarkdb.c
+++ b/squarkdb.c
@@ -17,10 +17,11 @@ const char *sqdb_section_names[SQDB_SECTION_MAX] = {
[SQDB_SECTION_KEYWORD_MPH] = "keyword_mph",
};
-static int sqdb_allocate(struct sqdb *db, size_t s)
+static int sqdb_allocate(struct sqdb *db, size_t s, int wr)
{
size_t old_size, new_size;
void *base;
+ int prot = PROT_READ;
old_size = db->file_length;
new_size = ALIGN(db->file_length + s, PAGE_SIZE);
@@ -30,12 +31,13 @@ static int sqdb_allocate(struct sqdb *db, size_t s)
return old_size;
}
- if (ftruncate(db->fd, new_size) < 0)
+ if (wr && ftruncate(db->fd, new_size) < 0)
return -1;
if (db->mmap_base == NULL) {
- base = mmap(NULL, new_size, PROT_READ|PROT_WRITE,
- MAP_SHARED, db->fd, 0);
+ if (wr)
+ prot |= PROT_WRITE;
+ base = mmap(NULL, new_size, prot, MAP_SHARED, db->fd, 0);
} else {
base = mremap(db->mmap_base, ALIGN(old_size, PAGE_SIZE),
new_size, MREMAP_MAYMOVE);
@@ -49,6 +51,23 @@ static int sqdb_allocate(struct sqdb *db, size_t s)
return old_size;
}
+int sqdb_open(struct sqdb *db, const char *fn)
+{
+ struct stat st;
+
+ db->fd = open(fn, O_RDONLY);
+ if (db->fd < 0)
+ return -1;
+
+ fstat(db->fd, &st);
+
+ db->file_length = 0;
+ db->mmap_base = NULL;
+ sqdb_allocate(db, st.st_size, 0);
+
+ return 0;
+}
+
int sqdb_create(struct sqdb *db, const char *fn)
{
struct sqdb_header *hdr;
@@ -61,7 +80,7 @@ int sqdb_create(struct sqdb *db, const char *fn)
db->file_length = 0;
db->mmap_base = NULL;
- rc = sqdb_allocate(db, sizeof(struct sqdb_header));
+ rc = sqdb_allocate(db, sizeof(struct sqdb_header), 1);
if (rc < 0) {
close(db->fd);
return rc;
@@ -94,7 +113,7 @@ void *sqdb_section_create(struct sqdb *db, int id, uint32_t size)
if (hdr->section[id].offset || hdr->section[id].length)
return NULL;
- pos = sqdb_allocate(db, size);
+ pos = sqdb_allocate(db, size, 1);
if (pos < 0)
return NULL;