You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.7 KiB

#include <stdlib.h>
#include <UDPTCPNetwork.h>
#include "inmemoryfile.h"
InMemoryFile::InMemoryFile() {
filename = "";
mem = malloc (INMEMORYFILE_ALLOCATEBLOCK);
memallocsize = INMEMORYFILE_ALLOCATEBLOCK;
memsize = 0;
};
InMemoryFile::~InMemoryFile() {
if (mem != NULL) free (mem);
filename = "";
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);
filename = rightside.filename;
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;
}