2
* vector.c - resizable array (should be replaced with STL vector).
4
* Licensed under LGPLv2: the complete text of the GNU Lesser General
5
* Public License can be found in COPYING file of the nilfs-utils
8
* Copyright (C) 2008-2011 Nippon Telegraph and Telephone Corporation.
13
#endif /* HAVE_CONFIG_H */
17
#endif /* HAVE_STDLIB_H */
21
#endif /* HAVE_STRING_H */
28
* nilfs_vector_create - create a vector
29
* @elemsize: element size
31
* Description: nilfs_vector_create() creates a new vector, which is a
32
* resizable array of data. The size of each element is specified by
35
* Return Value: On success, the pointer to the newly-created vector is
36
* returned. On error, NULL is returned.
38
struct nilfs_vector *nilfs_vector_create(size_t elemsize)
40
struct nilfs_vector *vector;
42
if ((vector = malloc(sizeof(struct nilfs_vector))) == NULL)
45
if ((vector->v_data = malloc(elemsize * NILFS_VECTOR_INIT_MAXELEMS)) == NULL) {
50
vector->v_elemsize = elemsize;
51
vector->v_maxelems = NILFS_VECTOR_INIT_MAXELEMS;
58
* nilfs_vector_destroy - destroy a vector
61
* Description: nilfs_vector_destroy() destroys the vector specified by
62
* @vector, which must have been returned by a previous call to
63
* nilfs_vector_create().
65
void nilfs_vector_destroy(struct nilfs_vector *vector)
74
* nilfs_vector_get_new_element - add a new element
77
* Description: nilfs_vector_get_new_element() adds a new element at the end
78
* of the vector @vector.
80
* Return Value: on success, the pointer to the new element is returned. On
81
* error, NULL is returned.
83
void *nilfs_vector_get_new_element(struct nilfs_vector *vector)
88
/* resize array if necessary */
89
if (vector->v_nelems >= vector->v_maxelems) {
90
maxelems = vector->v_maxelems * NILFS_VECTOR_FACTOR;
91
if ((data = realloc(vector->v_data,
92
vector->v_elemsize * maxelems)) == NULL)
94
vector->v_data = data;
95
vector->v_maxelems = maxelems;
97
return vector->v_data + vector->v_elemsize * vector->v_nelems++;
101
* nilfs_vector_delete_elements - delete elements
104
* @nelems: number of elements to be deleted
106
* Description: nilfs_vector_delete_elements() deletes @nelems elements from
109
* Return Value: On success, 0 is returned. On error, -1 is returned.
111
int nilfs_vector_delete_elements(struct nilfs_vector *vector,
115
if ((index >= vector->v_nelems) ||
116
(index + nelems - 1 >= vector->v_nelems)) {
121
if (index + nelems - 1 < vector->v_nelems - 1)
122
memmove(vector->v_data + vector->v_elemsize * index,
123
vector->v_data + vector->v_elemsize * (index + nelems),
124
(vector->v_nelems - (index + nelems)) *
126
vector->v_nelems -= nelems;