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

@ -34,10 +34,13 @@ MMap *mmap(String filename, int size, int offset) {
if (fd < 0) if (fd < 0)
return 0; return 0;
void *data = ::mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset); void *data = NULL;
if (data == MAP_FAILED) { if (size > 0) {
close(fd); data = ::mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset);
return 0; if (data == MAP_FAILED) {
close(fd);
return 0;
}
} }
auto r = new MMap(); 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); 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. */ /** Returns the length of a Buffer object. */
//% property //% property
int length(MMap *s) { int length(MMap *s) {

View File

@ -20,6 +20,12 @@ declare interface MMap {
//% shim=MMapMethods::getNumber //% shim=MMapMethods::getNumber
getNumber(format: NumberFormat, offset: int32): number; 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. */ /** Returns the length of a Buffer object. */
//% property shim=MMapMethods::length //% property shim=MMapMethods::length
length: int32; length: int32;