//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com
//-- includes -----------------------------------------------
//-- data types ---------------------------------------------
typedef struct _MemoryBlock {
void *data;
size_t capacity, used, dataSize;
}* MemoryBlock;
//-- functions ----------------------------------------------
MemoryBlock getMemoryBlock( register const size_t dataSize, register const size_t initialSize ){
MemoryBlock mb = (MemoryBlock)malloc( sizeof( struct _MemoryBlock ) );
if( mb ) {
mb->used = 0;
mb->data = NULL;
mb->dataSize = dataSize;
mb->capacity = initialSize && ( mb->data = (void *)malloc( initialSize * dataSize ) ) ? initialSize : 0;
}
return mb;
}
void freeMemoryBlock( register const MemoryBlock mb ){
free( mb->data );
free( mb );
}
int resizeMemoryBlock( register const size_t newSize, register const MemoryBlock mb ){
void *newData = (void *)realloc( mb->data, newSize * mb->dataSize );
if( newData ){
mb->data = newData;
return mb->capacity = newSize;
}
return 0;
}
int growMemoryBlock( register const MemoryBlock mb ){
size_t delta = mb->capacity > 64 ? mb->capacity / 4 : mb->capacity > 8 ? 16 : 4;
void *newData = (void *)realloc( mb->data, ( mb->capacity + delta ) * mb->dataSize );
if( newData ){
mb->data = newData;
return mb->capacity += delta;
}
return 0;
}
int growExMemoryBlock( register const size_t neededBlocks, register const MemoryBlock mb ){
while( mb->used+neededBlocks > mb->capacity )
if( !growMemoryBlock( mb ) )
return 0;
return 1;
}
int incMemoryBlock( register const MemoryBlock mb ){
return mb->used+1 <= mb->capacity || growMemoryBlock( mb );
}