From fd67bb884548f0a1b3d3837e48146424c6002305 Mon Sep 17 00:00:00 2001 From: Michal Moskal Date: Sun, 9 Jul 2017 17:51:16 +0100 Subject: [PATCH] Add mmap.slice and allow for 0-sized fd-only mappings --- libs/core/mmap.cpp | 25 ++++++++++++++++++++----- libs/core/shims.d.ts | 6 ++++++ 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/libs/core/mmap.cpp b/libs/core/mmap.cpp index 7f93e556..6b0f24be 100644 --- a/libs/core/mmap.cpp +++ b/libs/core/mmap.cpp @@ -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) { diff --git a/libs/core/shims.d.ts b/libs/core/shims.d.ts index 144db1a4..128e5879 100644 --- a/libs/core/shims.d.ts +++ b/libs/core/shims.d.ts @@ -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;