Skip to content

Commit

Permalink
Merge branch 'shift'
Browse files Browse the repository at this point in the history
  • Loading branch information
tj committed Aug 23, 2010
2 parents 2f15a25 + 66048fa commit be46abc
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/list.c
Expand Up @@ -80,6 +80,23 @@ List_pop(List *self) {
return node; return node;
} }


/*
* Return / detach the first node in the list, or NULL.
*/

ListNode *
List_shift(List *self) {
if (!self->len) return NULL;
ListNode *node = self->head;
if (--self->len) {
(self->head = node->next)->prev = NULL;
} else {
self->head = self->tail = NULL;
}
node->next = node->prev = NULL;
return node;
}

/* /*
* Prepend the given node to the list * Prepend the given node to the list
* and return the node, NULL on failure. * and return the node, NULL on failure.
Expand Down
1 change: 1 addition & 0 deletions src/list.h
Expand Up @@ -76,6 +76,7 @@ ListNode *List_unshift(List *self, ListNode *node);
ListNode *List_find(List *self, void *val); ListNode *List_find(List *self, void *val);
ListNode *List_at(List *self, int index); ListNode *List_at(List *self, int index);
ListNode *List_pop(List *self); ListNode *List_pop(List *self);
ListNode *List_shift(List *self);
void List_remove(List *self, ListNode *node); void List_remove(List *self, ListNode *node);
void List_destroy(List *self); void List_destroy(List *self);


Expand Down
31 changes: 31 additions & 0 deletions test.c
Expand Up @@ -233,6 +233,36 @@ test_List_pop() {
assert(0 == list->len); assert(0 == list->len);
} }


static void
test_List_shift() {
// Setup
List *list = List_new();
ListNode *a = List_push(list, ListNode_new("a"));
ListNode *b = List_push(list, ListNode_new("b"));
ListNode *c = List_push(list, ListNode_new("c"));

// Assertions
assert(3 == list->len);

assert(a == List_shift(list));
assert(2 == list->len);
assert(b == list->head);
assert(NULL == list->head->prev && "new head node prev is not NULL");
assert(NULL == a->prev && "detached node prev is not NULL");
assert(NULL == a->next && "detached node next is not NULL");

assert(b == List_shift(list));
assert(1 == list->len);

assert(c == List_shift(list));
assert(0 == list->len);
assert(NULL == list->head);
assert(NULL == list->tail);

assert(NULL == List_shift(list));
assert(0 == list->len);
}

static void static void
test_ListIterator() { test_ListIterator() {
// Setup // Setup
Expand Down Expand Up @@ -286,6 +316,7 @@ main(int argc, const char **argv){
test(List_at); test(List_at);
test(List_remove); test(List_remove);
test(List_pop); test(List_pop);
test(List_shift);
test(List_destroy); test(List_destroy);
test(ListIterator); test(ListIterator);
puts("... \x1b[32m100%\x1b[0m\n"); puts("... \x1b[32m100%\x1b[0m\n");
Expand Down

0 comments on commit be46abc

Please sign in to comment.