Add mmap.slice and allow for 0-sized fd-only mappings

This commit is contained in:
Michal Moskal 2017-07-09 17:51:16 +01:00
parent 0de116c9cc
commit fd67bb8845
2 changed files with 26 additions and 5 deletions

View File

@ -33,11 +33,14 @@ MMap *mmap(String filename, int size, int offset) {
int fd = open(filename->data, O_RDWR, 0);
if (fd < 0)
return 0;
void *data = ::mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset);
if (data == MAP_FAILED) {
close(fd);
return 0;
void *data = NULL;
if (size > 0) {
data = ::mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset);
if (data == MAP_FAILED) {
close(fd);
return 0;
}
}
auto r = new MMap();
@ -70,6 +73,18 @@ TNumber getNumber(MMap *buf, NumberFormat format, int offset) {
return getNumberCore(buf->data + offset, buf->length - offset, format);
}
/**
* Read a range of bytes into a buffer.
*/
//%
Buffer slice(MMap *buf, int offset = 0, int length = -1) {
offset = min((int)buf->length, offset);
if (length < 0)
length = buf->length;
length = min(length, buf->length - offset);
return mkBuffer(buf->data + offset, length);
}
/** Returns the length of a Buffer object. */
//% property
int length(MMap *s) {

View File

@ -20,6 +20,12 @@ declare interface MMap {
//% shim=MMapMethods::getNumber
getNumber(format: NumberFormat, offset: int32): number;
/**
* Read a range of bytes into a buffer.
*/
//% offset.defl=0 length.defl=-1 shim=MMapMethods::slice
slice(offset?: int32, length?: int32): Buffer;
/** Returns the length of a Buffer object. */
//% property shim=MMapMethods::length
length: int32;