Skip to content

Commit 054977a

Browse files
committed
list: add list_move().
1 parent c1f922c commit 054977a

File tree

3 files changed

+36
-6
lines changed

3 files changed

+36
-6
lines changed

src/list.c

+15
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,18 @@ void list_remove(struct list_node *item)
4040
item->prev = NULL;
4141
item->next = NULL;
4242
}
43+
44+
void list_move(struct list_node *dst, struct list_node *src)
45+
{
46+
if (list_is_empty(src)) {
47+
dst->next = dst->prev = dst;
48+
} else {
49+
dst->next = src->next;
50+
dst->prev = src->prev;
51+
52+
dst->next->prev = dst;
53+
dst->prev->next = dst;
54+
55+
src->next = src->prev = src;
56+
}
57+
}

src/list.h

+3
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,7 @@ void list_insert(struct list_node *item, struct list_node *after);
5454
/* Remove a node from its containing list. */
5555
void list_remove(struct list_node *item);
5656

57+
/* Move the contents of one list to another in constant time. */
58+
void list_move(struct list_node *dst, struct list_node *src);
59+
5760
#endif

tests/test_list.c

+18-6
Original file line numberDiff line numberDiff line change
@@ -63,13 +63,13 @@ static void test_remove(int mask)
6363
list_remove(&recs[i].node);
6464
}
6565

66-
static void test_verify(int mask)
66+
static void test_verify(struct list_node *l, int mask)
6767
{
6868
int even_count = (mask & 2) ? (N / 2) : 0;
6969
int odd_count = (mask & 1) ? (N / 2) : 0;
7070
struct list_node *n;
7171

72-
for (n = lst.next; n != &lst; n = n->next) {
72+
for (n = l->next; n != l; n = n->next) {
7373
struct record *r = (struct record *)n;
7474

7575
if (r->v & 1)
@@ -84,16 +84,28 @@ static void test_verify(int mask)
8484

8585
int main(void)
8686
{
87+
struct list_node copy;
88+
8789
test_init();
8890

8991
test_start_odd();
90-
test_verify(1);
92+
test_verify(&lst, 1);
9193
test_add_evens();
92-
test_verify(3);
94+
test_verify(&lst, 3);
95+
96+
list_move(&copy, &lst);
97+
test_verify(&copy, 3);
98+
assert(list_is_empty(&lst));
99+
100+
list_move(&lst, &copy);
101+
test_verify(&lst, 3);
102+
assert(list_is_empty(&copy));
103+
93104
test_remove(1);
94-
test_verify(2);
105+
test_verify(&lst, 2);
106+
95107
test_remove(2);
96-
test_verify(0);
108+
test_verify(&lst, 0);
97109

98110
return 0;
99111
}

0 commit comments

Comments
 (0)