c-libp2p/utils/vector.c

82 lines
1.9 KiB
C
Raw Normal View History

2017-03-19 19:39:48 +00:00
#include <stdio.h>
#include <stdlib.h>
#include "libp2p/utils/vector.h"
2017-03-19 19:39:48 +00:00
struct Libp2pVector* libp2p_utils_vector_new(int initial_size)
{
struct Libp2pVector* v = (struct Libp2pVector*)malloc(sizeof(struct Libp2pVector));
v->capacity = initial_size;
v->total = 0;
v->items = malloc(sizeof(void *) * v->capacity);
return v;
}
2017-03-19 19:39:48 +00:00
int libp2p_utils_vector_total(struct Libp2pVector *v)
{
return v->total;
}
2017-03-19 19:39:48 +00:00
static void libp2p_utils_vector_resize(struct Libp2pVector *v, int capacity)
{
#ifdef DEBUG_ON
printf("vector_resize: %d to %d\n", v->capacity, capacity);
#endif
void const** items = realloc(v->items, sizeof(void *) * capacity);
2017-03-19 19:39:48 +00:00
if (items) {
v->items = items;
v->capacity = capacity;
}
}
/****
* Add an item to the vector. NOTE: This does not copy the item
* @param v the vector to add to
* @param item the item to add
*/
int libp2p_utils_vector_add(struct Libp2pVector *v, const void *item)
2017-03-19 19:39:48 +00:00
{
if (v->capacity == v->total)
libp2p_utils_vector_resize(v, v->capacity * 2);
v->items[v->total++] = item;
return v->total;
}
2017-02-17 04:13:16 +00:00
2017-03-19 19:39:48 +00:00
void libp2p_utils_vector_set(struct Libp2pVector *v, int index, void *item)
{
if (index >= 0 && index < v->total)
v->items[index] = item;
}
const void *libp2p_utils_vector_get(struct Libp2pVector *v, int index)
2017-03-19 19:39:48 +00:00
{
if (index >= 0 && index < v->total)
return v->items[index];
return NULL;
}
void libp2p_utils_vector_delete(struct Libp2pVector *v, int index)
{
if (index < 0 || index >= v->total)
return;
v->items[index] = NULL;
for (int i = 0; i < v->total - 1; i++) {
v->items[i] = v->items[i + 1];
v->items[i + 1] = NULL;
}
v->total--;
if (v->total > 0 && v->total == v->capacity / 4)
libp2p_utils_vector_resize(v, v->capacity / 2);
2017-02-17 04:13:16 +00:00
}
2017-03-19 19:39:48 +00:00
void libp2p_utils_vector_free(struct Libp2pVector *v)
{
free(v->items);
2017-04-17 16:57:37 +00:00
free(v);
2017-02-17 04:13:16 +00:00
}