[common] added objectlist_pop and objectlist_remove methods

This commit is contained in:
Geoffrey McRae 2019-11-04 22:05:21 +11:00
parent 1dfa0ed218
commit df9798c819
3 changed files with 38 additions and 8 deletions

View File

@ -1 +1 @@
B1-26-g01f5238a9d+1 B1-27-g1dfa0ed218+1

View File

@ -24,10 +24,12 @@ typedef struct ObjectList * ObjectList;
typedef void (*ObjectFreeFn)(void * object); typedef void (*ObjectFreeFn)(void * object);
ObjectList objectlist_new (ObjectFreeFn free_fn); ObjectList objectlist_new (ObjectFreeFn free_fn);
void objectlist_free (ObjectList * sl); void objectlist_free (ObjectList * ol);
int objectlist_push (ObjectList sl, void * object); int objectlist_push (ObjectList ol, void * object);
unsigned int objectlist_count(ObjectList sl); void * objectlist_pop (ObjectList ol);
char * objectlist_at (ObjectList sl, unsigned int index); bool objectlist_remove(ObjectList ol, unsigned int index);
unsigned int objectlist_count (ObjectList ol);
void * objectlist_at (ObjectList ol, unsigned int index);
// generic free method // generic free method
void objectlist_free_item(void *object); void objectlist_free_item(void *object);

View File

@ -20,6 +20,7 @@ Place, Suite 330, Boston, MA 02111-1307 USA
#include "common/objectlist.h" #include "common/objectlist.h"
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
struct ObjectList struct ObjectList
{ {
@ -57,7 +58,7 @@ int objectlist_push(ObjectList ol, void * object)
if (ol->count == ol->size) if (ol->count == ol->size)
{ {
ol->size += 32; ol->size += 32;
ol->list = realloc(ol->list, sizeof(char *) * ol->size); ol->list = realloc(ol->list, sizeof(void *) * ol->size);
} }
unsigned int index = ol->count; unsigned int index = ol->count;
@ -65,12 +66,39 @@ int objectlist_push(ObjectList ol, void * object)
return index; return index;
} }
void * objectlist_pop(ObjectList ol)
{
if (ol->count == 0)
return NULL;
return ol->list[--ol->count];
}
bool objectlist_remove(ObjectList ol, unsigned int index)
{
if (index >= ol->count)
return false;
if (ol->free_fn)
ol->free_fn(ol->list[index]);
void ** newlist = malloc(sizeof(void *) * ol->size);
--ol->count;
memcpy(&newlist[0], &ol->list[0], index * sizeof(void *));
memcpy(&newlist[index], &ol->list[index + 1], (ol->count - index) * sizeof(void *));
free(ol->list);
ol->list = newlist;
return true;
}
unsigned int objectlist_count(ObjectList ol) unsigned int objectlist_count(ObjectList ol)
{ {
return ol->count; return ol->count;
} }
char * objectlist_at(ObjectList ol, unsigned int index) void * objectlist_at(ObjectList ol, unsigned int index)
{ {
if (index >= ol->count) if (index >= ol->count)
return NULL; return NULL;