Merge remote-tracking branch 'origin/topic/jazoff/datastructures-defer-init'

* origin/topic/jazoff/datastructures-defer-init:
  Defer initialization of lists and dicts until an item is added.
This commit is contained in:
Jon Siwek 2019-03-13 17:28:26 -07:00
commit 389fe2bc2a
6 changed files with 59 additions and 44 deletions

View file

@ -6,33 +6,27 @@
#include "List.h"
#include "util.h"
static const int DEFAULT_CHUNK_SIZE = 10;
#define DEFAULT_LIST_SIZE 10
#define GROWTH_FACTOR 2
BaseList::BaseList(int size)
{
chunk_size = DEFAULT_CHUNK_SIZE;
num_entries = 0;
max_entries = 0;
entry = 0;
if ( size < 0 )
{
num_entries = max_entries = 0;
entry = 0;
}
else
{
if ( size > 0 )
chunk_size = size;
if ( size <= 0 )
return;
num_entries = 0;
entry = (ent *) safe_malloc(chunk_size * sizeof(ent));
max_entries = chunk_size;
}
max_entries = size;
entry = (ent *) safe_malloc(max_entries * sizeof(ent));
}
BaseList::BaseList(BaseList& b)
{
max_entries = b.max_entries;
chunk_size = b.chunk_size;
num_entries = b.num_entries;
if ( max_entries )
@ -58,7 +52,6 @@ void BaseList::operator=(BaseList& b)
free(entry);
max_entries = b.max_entries;
chunk_size = b.chunk_size;
num_entries = b.num_entries;
if ( max_entries )
@ -73,10 +66,7 @@ void BaseList::operator=(BaseList& b)
void BaseList::insert(ent a)
{
if ( num_entries == max_entries )
{
resize(max_entries + chunk_size); // make more room
chunk_size *= 2;
}
resize(max_entries ? max_entries * GROWTH_FACTOR : DEFAULT_LIST_SIZE);
for ( int i = num_entries; i > 0; --i )
entry[i] = entry[i-1]; // move all pointers up one
@ -94,10 +84,7 @@ void BaseList::sortedinsert(ent a, list_cmp_func cmp_func)
// First append element.
if ( num_entries == max_entries )
{
resize(max_entries + chunk_size);
chunk_size *= 2;
}
resize(max_entries ? max_entries * GROWTH_FACTOR : DEFAULT_LIST_SIZE);
entry[num_entries++] = a;
@ -141,10 +128,7 @@ ent BaseList::remove_nth(int n)
void BaseList::append(ent a)
{
if ( num_entries == max_entries )
{
resize(max_entries + chunk_size); // make more room
chunk_size *= 2;
}
resize(max_entries ? max_entries * GROWTH_FACTOR : DEFAULT_LIST_SIZE);
entry[num_entries++] = a;
}
@ -168,7 +152,6 @@ void BaseList::clear()
}
num_entries = max_entries = 0;
chunk_size = DEFAULT_CHUNK_SIZE;
}
ent BaseList::replace(int ent_index, ent new_ent)