diff --git a/src/mem.cpp b/src/mem.cpp index 98f3fd45..78f2f3dd 100644 --- a/src/mem.cpp +++ b/src/mem.cpp @@ -73,6 +73,18 @@ MemBuffer::~MemBuffer() this->dealloc(); } +// similar to BoundedPtr, except checks only at creation +unsigned char *MemBuffer::subref(char const *errfmt, unsigned skip, unsigned take) +{ + if ((take + skip) < take // wrap-around + || (take + skip) > b_size // overrun + ) { + char buf[100]; snprintf(buf, sizeof(buf), errfmt, skip, take); + throwCantPack(buf); + } + return &b[skip]; +} + void MemBuffer::dealloc() { if (b != NULL) diff --git a/src/mem.h b/src/mem.h index 59944cf0..8839fd93 100644 --- a/src/mem.h +++ b/src/mem.h @@ -64,6 +64,11 @@ public: void clear(unsigned off, unsigned len) { fill(off, len, 0); } void clear() { fill(0, b_size, 0); } + // If the entire range [skip, take+skip) is inside the buffer, + // then return &b[skip]; else throwCantPack(sprintf(errfmt, skip, take)). + // This is similar to BoundedPtr, except only checks once. + unsigned char *subref(char const *errfmt, unsigned skip, unsigned take); + private: unsigned char *b; unsigned b_size;