list: added list_copy.
This commit is contained in:
parent
35008fa605
commit
658bc8b9ad
3 changed files with 33 additions and 0 deletions
11
src/list.c
11
src/list.c
|
|
@ -30,6 +30,17 @@ struct list* list_create(void) {
|
||||||
return list;
|
return list;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct list* list_copy(struct list *list) {
|
||||||
|
|
||||||
|
if (list && list->nr) {
|
||||||
|
struct list *copy = xmalloc(sizeof(struct list));
|
||||||
|
copy->items = xmemdup(list->items, sizeof(list->items) * list->nr);
|
||||||
|
copy->nr = list->nr;
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
int list_destroy(struct list *list) {
|
int list_destroy(struct list *list) {
|
||||||
|
|
||||||
list_clear_fn(list, NULL);
|
list_clear_fn(list, NULL);
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,8 @@ typedef int (cmp_fn_t)(const void *, const void *b);
|
||||||
|
|
||||||
struct list* list_create(void);
|
struct list* list_create(void);
|
||||||
|
|
||||||
|
struct list* list_copy(struct list *list);
|
||||||
|
|
||||||
int list_destroy(struct list *list);
|
int list_destroy(struct list *list);
|
||||||
|
|
||||||
void list_clear(struct list *list);
|
void list_clear(struct list *list);
|
||||||
|
|
|
||||||
|
|
@ -46,6 +46,25 @@ void test_remove() {
|
||||||
list_destroy(l);
|
list_destroy(l);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void test_copy() {
|
||||||
|
|
||||||
|
int i;
|
||||||
|
char ref[4] = { 'a', 'b', 'c', 'd' };
|
||||||
|
struct list *c, *l = list_create();
|
||||||
|
|
||||||
|
for(i=0; i < 4; i++)
|
||||||
|
list_insert(l, &ref[i]);
|
||||||
|
|
||||||
|
c = list_copy(l);
|
||||||
|
assert(list_size(c) == 4);
|
||||||
|
assert(c->items[0] == &ref[0]);
|
||||||
|
assert(c->items[1] == &ref[1]);
|
||||||
|
assert(c->items[2] == &ref[2]);
|
||||||
|
assert(c->items[3] == &ref[3]);
|
||||||
|
|
||||||
|
list_destroy(l);
|
||||||
|
list_destroy(c);
|
||||||
|
}
|
||||||
|
|
||||||
void test_isempty() {
|
void test_isempty() {
|
||||||
|
|
||||||
|
|
@ -125,6 +144,7 @@ int main() {
|
||||||
|
|
||||||
test_insert();
|
test_insert();
|
||||||
test_remove();
|
test_remove();
|
||||||
|
test_copy();
|
||||||
test_isempty();
|
test_isempty();
|
||||||
test_size();
|
test_size();
|
||||||
test_indexof();
|
test_indexof();
|
||||||
|
|
|
||||||
Reference in a new issue