From db1ad97c36a5b87f449859ddd4b5f3e98c46dd9d Mon Sep 17 00:00:00 2001 From: Thulinma Date: Sat, 1 Jul 2017 13:45:35 +0200 Subject: [PATCH] Added Util::ResizeablePointer class --- lib/util.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ lib/util.h | 18 ++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/lib/util.cpp b/lib/util.cpp index a69e6afd..f6ea07be 100644 --- a/lib/util.cpp +++ b/lib/util.cpp @@ -12,6 +12,7 @@ #if defined(_WIN32) #include // _mkdir #endif +#include #define RECORD_POINTER p + getOffset() + (getRecordPosition(recordNo) * getRSize()) + fd.offset #define RAXHDR_FIELDOFFSET p[1] @@ -148,6 +149,46 @@ namespace Util{ return fseeko(stream, offset, whence); } + ResizeablePointer::ResizeablePointer(){ + currSize = 0; + ptr = 0; + maxSize = 0; + } + + ResizeablePointer::~ResizeablePointer(){ + if (ptr){free(ptr);} + currSize = 0; + ptr = 0; + maxSize = 0; + } + + bool ResizeablePointer::assign(void * p, uint32_t l){ + if (!allocate(l)){return false;} + memcpy(ptr, p, l); + currSize = l; + return true; + } + + bool ResizeablePointer::append(void * p, uint32_t l){ + if (!allocate(l+currSize)){return false;} + memcpy(((char*)ptr)+currSize, p, l); + currSize += l; + return true; + } + + bool ResizeablePointer::allocate(uint32_t l){ + if (l > maxSize){ + void *tmp = realloc(ptr, l); + if (!tmp){ + FAIL_MSG("Could not allocate %lu bytes of memory", l); + return false; + } + ptr = tmp; + maxSize = l; + } + return true; + } + /// If waitReady is true (default), waits for isReady() to return true in 50ms sleep increments. RelAccX::RelAccX(char *data, bool waitReady){ if (!data){ diff --git a/lib/util.h b/lib/util.h index fb3019de..b62e7d18 100644 --- a/lib/util.h +++ b/lib/util.h @@ -12,6 +12,24 @@ namespace Util{ uint64_t ftell(FILE *stream); uint64_t fseek(FILE *stream, uint64_t offset, int whence); + /// Helper class that maintains a resizeable pointer and will free it upon deletion of the class. + class ResizeablePointer{ + public: + ResizeablePointer(); + ~ResizeablePointer(); + inline uint32_t& size(){return currSize;} + bool assign(void * p, uint32_t l); + bool append(void * p, uint32_t l); + bool allocate(uint32_t l); + inline operator char*(){return (char*)ptr;} + inline operator void*(){return ptr;} + private: + void * ptr; + uint32_t currSize; + uint32_t maxSize; + + }; + /// Holds type, size and offset for RelAccX class internal data fields. class RelAccXFieldData{ public: