Mercurial > code
diff array.c @ 34:653bb22d3c0c
For array.c:
o No index needed in ARRAY_FOREACH or ARRAY_FOREACH_R, it is stored in
the structure.
o Added a function to remove by data : array_unref()
author | David Demelier <markand@malikania.fr> |
---|---|
date | Fri, 30 Sep 2011 16:38:40 +0200 |
parents | e532a973f43d |
children | b972758ddcd5 |
line wrap: on
line diff
--- a/array.c Sun Sep 25 19:16:21 2011 +0200 +++ b/array.c Fri Sep 30 16:38:40 2011 +0200 @@ -27,16 +27,16 @@ static int array_grow(struct array *); struct array * -array_new(const void *data, size_t unit, size_t bsize, int flags) +array_new(const void *data, size_t unit, int bsize, int type) { struct array *arr; if (unit == 0 || (arr = malloc(sizeof (struct array))) == NULL) return NULL; - arr->tmp = NULL; - arr->length = 0; - arr->flags = flags; + memset(arr, 0, sizeof (struct array)); + + arr->type = type; arr->bsize = (bsize == 0) ? ARRAY_DEFAULT_BSIZE : bsize; arr->unit = unit; arr->size = OFFSET(arr->bsize); @@ -144,6 +144,30 @@ } /* + * Remove the object referenced by the `data' argument. Useful when you + * don't know the index. + */ + +struct personne { + char *name; + int age; +}; + +void +array_unref(struct array *arr, const void *data) +{ + void *elm; + int i; + + for (i = 0; i < arr->length; ++i) { + elm = ARRAY_INDEX(arr, i); + + if (memcmp(elm, data, arr->unit) == 0) + array_remove(arr, i); + } +} + +/* * Swap the two elements referenced by index `i1' and `i2'. This function needs * to allocate data to swap elements thus if the functions fails it returns -1 * otherwise 0 is returned. @@ -161,13 +185,19 @@ * function. */ - if (arr->tmp == NULL && (arr->tmp = malloc(arr->unit)) == NULL) + if (arr->_tmp == NULL && (arr->_tmp = malloc(arr->unit)) == NULL) return -1; - memcpy((char *) arr->tmp, (char *) arr->data + OFFSET(i1), arr->unit); + memcpy((char *) arr->_tmp, (char *) arr->data + OFFSET(i1), arr->unit); memcpy((char *) arr->data + OFFSET(i1), (char *) arr->data + OFFSET(i2), arr->unit); - memcpy((char *) arr->data + OFFSET(i2), (char *) arr->tmp, arr->unit); + memcpy((char *) arr->data + OFFSET(i2), (char *) arr->_tmp, arr->unit); + + /* + * Clear bytes for safety. + */ + + memset(arr->_tmp, 0, arr->unit); return 0; } @@ -235,8 +265,8 @@ if (arr->data) free(arr->data); - if (arr->tmp) - free(arr->tmp); + if (arr->_tmp) + free(arr->_tmp); free(arr); } @@ -253,7 +283,7 @@ if ((arr->size / arr->unit) > (size_t) arr->length) return 0; - if (arr->flags & ARRAY_AUTO) { + if (arr->type == ARRAY_AUTO) { if ((arr->data = realloc(arr->data, arr->size + OFFSET(arr->bsize))) == NULL) return -1;