#include #include #include "inmemoryfile.h" InMemoryFile::InMemoryFile() { mem = malloc (INMEMORYFILE_ALLOCATEBLOCK); memallocsize = INMEMORYFILE_ALLOCATEBLOCK; memsize = 0; }; InMemoryFile::~InMemoryFile() { if (mem != NULL) free (mem); mem = NULL; memallocsize = 0; memsize = 0; }; int InMemoryFile::Allocate(size_t newsize) { // shrink size only if new memory block is smaller then 25% if ((newsize < memallocsize / 4) || (newsize > memallocsize)) { memallocsize = (1+(newsize/INMEMORYFILE_ALLOCATEBLOCK))*INMEMORYFILE_ALLOCATEBLOCK; memsize = newsize; mem = realloc(mem, memallocsize); if (mem == NULL || memsize > memallocsize) { debug ("could not reallocate memory memsize:%d memallocsize:%d\n.", memsize, memallocsize); exit (1); } } return 1; }; InMemoryFile InMemoryFile::operator=(InMemoryFile rightside) { memsize = rightside.memsize; memallocsize = 1+(memsize/INMEMORYFILE_ALLOCATEBLOCK)*INMEMORYFILE_ALLOCATEBLOCK; mem = realloc(mem, memallocsize+1); if (mem == NULL || memsize > memallocsize) { debug ("could not reallocate memory: %s\n.", strerror(errno)); exit (1); } memcpy (mem, rightside.mem, memsize); return *this; }; /// @brief copy the memory. /// @param srcptr pointer to the source memory /// @param srcsize size of the memory /// @return 1 on success, 0 on error int InMemoryFile::CopyFrom(void *srcptr, size_t srcsize) { if (Allocate (srcsize) == 0) return 0; memcpy (mem, srcptr, memsize); return 1; }