This commit is contained in:
twinaphex 2017-11-25 02:12:15 +01:00
parent 0f6c453428
commit ac651b7581

View File

@ -3,7 +3,11 @@
#include <file/nbio.h>
#ifdef _WIN32
#include <direct.h>
#else
#include <unistd.h>
#endif
#include <fcntl.h>
#include <sys/mman.h>
@ -20,34 +24,28 @@ struct nbio_t* nbio_open(const char * filename, unsigned mode)
static const int o_flags[] = { O_RDONLY, O_RDWR|O_CREAT|O_TRUNC, O_RDWR, O_RDONLY, O_RDWR|O_CREAT|O_TRUNC };
static const int map_flags[] = { PROT_READ, PROT_WRITE|PROT_READ, PROT_WRITE|PROT_READ, PROT_READ, PROT_WRITE|PROT_READ };
int fd;
size_t len;
void* ptr;
struct nbio_t* handle;
fd = open(filename, o_flags[mode]|O_CLOEXEC, 0644);
if (fd < 0) return NULL;
void* ptr = NULL;
struct nbio_t* handle = NULL;
int fd = open(filename, o_flags[mode]|O_CLOEXEC, 0644);
if (fd < 0)
return NULL;
len = lseek(fd, 0, SEEK_END);
if (len != 0)
{
ptr = mmap(NULL, len, map_flags[mode], MAP_SHARED, fd, 0);
}
else
{
ptr = NULL;
}
if (ptr == MAP_FAILED)
{
close(fd);
return NULL;
}
handle = malloc(sizeof(struct nbio_t));
handle->fd = fd;
handle = malloc(sizeof(struct nbio_t));
handle->fd = fd;
handle->map_flags = map_flags[mode];
handle->len = len;
handle->ptr = ptr;
handle->len = len;
handle->ptr = ptr;
return handle;
}
@ -70,19 +68,25 @@ void nbio_resize(struct nbio_t* handle, size_t len)
{
if (len < handle->len)
{
/* this works perfectly fine if this check is removed, but it won't work on other nbio implementations */
/* this works perfectly fine if this check is removed, but it
* won't work on other nbio implementations */
/* therefore, it's blocked so nobody accidentally relies on it */
puts("ERROR - attempted file shrink operation, not implemented");
abort();
}
if (ftruncate(handle->fd, len) != 0)
{
puts("ERROR - couldn't resize file (ftruncate)");
abort(); /* this one returns void and I can't find any other way for it to report failure */
abort(); /* this one returns void and I can't find any other
way for it to report failure */
}
munmap(handle->ptr, handle->len);
handle->ptr = mmap(NULL, len, handle->map_flags, MAP_SHARED, handle->fd, 0);
handle->len = len;
if (handle->ptr == MAP_FAILED)
{
puts("ERROR - couldn't resize file (mmap)");