00001 /* 00002 Ancient, hideous custom memory management classes. 00003 FIXME: replace these with something well-tested, 00004 standard, and modern, like std::vector. 00005 00006 Orion Sky Lawlor, olawlor@acm.org, 2001/2/5 00007 */ 00008 #include <stdio.h> 00009 #include <stdlib.h> /* for malloc, free */ 00010 #include <string.h> /* for memcpy */ 00011 #include "collide_buffers.h" 00012 #include "charm++.h" 00013 00014 /************** MemoryBuffer **************** 00015 Manages an expandable buffer of bytes. Like std::vector, 00016 but typeless. 00017 */ 00018 00019 memoryBuffer::memoryBuffer()//Empty initial buffer 00020 { 00021 data=NULL;len=0; 00022 } 00023 00024 memoryBuffer::memoryBuffer(size_t initLen)//Initial capacity specified 00025 { 00026 data=NULL;len=0;reallocate(initLen); 00027 //printf("COLLIDE: Initializing memory buffer to size %d\n", initLen); 00028 } 00029 00030 memoryBuffer::~memoryBuffer()//Deletes array 00031 { 00032 //printf("COLLIDE: Freeing memory buffer of size %d\n", len); 00033 free(data); 00034 } 00035 00036 void memoryBuffer::setData(const void *toData,size_t toLen)//Reallocate and copy 00037 { 00038 //printf("COLLIDE: Setting memory buffer size from %d to %d\n", len, toLen); 00039 reallocate(toLen); 00040 memcpy(data,toData,toLen); 00041 } 00042 00043 void memoryBuffer::resize(size_t newlen)//Reallocate, preserving old data 00044 { 00045 if (len==0) {reallocate(newlen); return;} 00046 if (len==newlen) return; 00047 //printf("COLLIDE: Resizing memory buffer from size %d to %d\n", len, newlen); 00048 void *oldData=data; size_t oldlen=len; 00049 data=malloc(len=newlen); 00050 memcpy(data,oldData,oldlen<newlen?oldlen:newlen); 00051 free(oldData); 00052 } 00053 00054 void memoryBuffer::reallocate(size_t newlen)//Free old data, allocate new 00055 { 00056 free(data); 00057 data=malloc(len=newlen); 00058 } 00059