2015-06-18 16:13:37 -07:00
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
#include <sys/mman.h>
|
2016-04-27 14:00:14 -07:00
|
|
|
#include "memfile.hpp"
|
2015-06-18 16:13:37 -07:00
|
|
|
|
|
|
|
#define INCREMENT 131072
|
2016-10-26 15:57:24 -07:00
|
|
|
#define INITIAL 256
|
2015-06-18 16:13:37 -07:00
|
|
|
|
|
|
|
struct memfile *memfile_open(int fd) {
|
2016-10-26 15:57:24 -07:00
|
|
|
if (ftruncate(fd, INITIAL) != 0) {
|
2015-06-18 16:13:37 -07:00
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
2016-10-26 15:57:24 -07:00
|
|
|
char *map = (char *) mmap(NULL, INITIAL, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
2015-06-18 16:13:37 -07:00
|
|
|
if (map == MAP_FAILED) {
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
2016-08-30 14:02:51 -07:00
|
|
|
struct memfile *mf = new memfile;
|
2015-06-18 16:13:37 -07:00
|
|
|
if (mf == NULL) {
|
2016-10-26 15:57:24 -07:00
|
|
|
munmap(map, INITIAL);
|
2015-06-18 16:13:37 -07:00
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
mf->fd = fd;
|
|
|
|
mf->map = map;
|
2016-10-26 15:57:24 -07:00
|
|
|
mf->len = INITIAL;
|
2015-06-18 16:13:37 -07:00
|
|
|
mf->off = 0;
|
2015-12-21 17:00:07 -08:00
|
|
|
mf->tree = 0;
|
2015-06-18 16:13:37 -07:00
|
|
|
|
|
|
|
return mf;
|
|
|
|
}
|
|
|
|
|
|
|
|
int memfile_close(struct memfile *file) {
|
|
|
|
if (munmap(file->map, file->len) != 0) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (file->fd >= 0) {
|
|
|
|
if (close(file->fd) != 0) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-08-30 14:02:51 -07:00
|
|
|
delete file;
|
2015-06-18 16:13:37 -07:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
int memfile_write(struct memfile *file, void *s, long long len) {
|
|
|
|
if (file->off + len > file->len) {
|
|
|
|
if (munmap(file->map, file->len) != 0) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
2017-05-18 14:33:38 -07:00
|
|
|
file->len += (len + INCREMENT + 1) / INCREMENT * INCREMENT;
|
2015-06-18 16:13:37 -07:00
|
|
|
|
|
|
|
if (ftruncate(file->fd, file->len) != 0) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
2016-04-27 12:41:49 -07:00
|
|
|
file->map = (char *) mmap(NULL, file->len, PROT_READ | PROT_WRITE, MAP_SHARED, file->fd, 0);
|
2015-06-18 16:13:37 -07:00
|
|
|
if (file->map == MAP_FAILED) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
memcpy(file->map + file->off, s, len);
|
|
|
|
file->off += len;
|
|
|
|
return len;
|
|
|
|
}
|