71 lines
1.5 KiB
C
71 lines
1.5 KiB
C
|
|
||
|
/**
|
||
|
* @file vector.c
|
||
|
* @brief Functions for creating and manipulating vectors.
|
||
|
*
|
||
|
* @author Jon Schutz
|
||
|
* @date 05-Feb-2001
|
||
|
**/
|
||
|
|
||
|
#include "vector.h"
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
|
||
|
/** Resize a vector.
|
||
|
@param v The vector to resize.
|
||
|
@param size The new size of the vector. Must be >= 0.
|
||
|
@param element_size The size of elements in the vector.
|
||
|
@return 0 on success, -1 if a memory allocation error occurred.
|
||
|
*/
|
||
|
int
|
||
|
vector_resize(vector *v, size_t size, size_t element_size)
|
||
|
{
|
||
|
void *b;
|
||
|
|
||
|
b = (v->array)?realloc(v->array, size * element_size)
|
||
|
:malloc(size * element_size);
|
||
|
|
||
|
if ((0 < (size * element_size)) && (NULL == b))
|
||
|
return -1;
|
||
|
|
||
|
if (size > v->array_size) {
|
||
|
memset(b + v->array_size * element_size, 0,
|
||
|
(size - v->array_size) * element_size);
|
||
|
}
|
||
|
v->array = b;
|
||
|
v->array_size = size;
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
/** Create a new vector.
|
||
|
|
||
|
@param v The vector to be initialised.
|
||
|
@param size The size of the set.
|
||
|
@param element_size The size of elements in the vector.
|
||
|
@return 0 on success, -1 on error.
|
||
|
*/
|
||
|
int
|
||
|
vector_create(vector *v, size_t size, size_t element_size)
|
||
|
{
|
||
|
v->array = NULL;
|
||
|
v->array_size = 0;
|
||
|
v->index = 0;
|
||
|
|
||
|
return vector_resize(v, size, element_size);
|
||
|
}
|
||
|
|
||
|
/** Destroy a vector, freeing storage associated with it. */
|
||
|
void
|
||
|
vector_destroy(vector *v)
|
||
|
{
|
||
|
free(v->array);
|
||
|
v->array = NULL;
|
||
|
v->array_size = 0;
|
||
|
}
|
||
|
|
||
|
int
|
||
|
word_vector_strcmp(const char **a, const char **b)
|
||
|
{
|
||
|
return strcmp(*a, *b);
|
||
|
}
|