list_iterator.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // iterator.c
  3. //
  4. // Copyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca>
  5. //
  6. #include "list.h"
  7. /*
  8. * Allocate a new list_iterator_t. NULL on failure.
  9. * Accepts a direction, which may be LIST_HEAD or LIST_TAIL.
  10. */
  11. list_iterator_t *
  12. list_iterator_new(list_t *list, list_direction_t direction) {
  13. list_node_t *node = direction == LIST_HEAD
  14. ? list->head
  15. : list->tail;
  16. return list_iterator_new_from_node(node, direction);
  17. }
  18. /*
  19. * Allocate a new list_iterator_t with the given start
  20. * node. NULL on failure.
  21. */
  22. list_iterator_t *
  23. list_iterator_new_from_node(list_node_t *node, list_direction_t direction) {
  24. list_iterator_t *self;
  25. if (!(self = LIST_MALLOC(sizeof(list_iterator_t))))
  26. return NULL;
  27. self->next = node;
  28. self->direction = direction;
  29. return self;
  30. }
  31. /*
  32. * Return the next list_node_t or NULL when no more
  33. * nodes remain in the list.
  34. */
  35. list_node_t *
  36. list_iterator_next(list_iterator_t *self) {
  37. list_node_t *curr = self->next;
  38. if (curr) {
  39. self->next = self->direction == LIST_HEAD
  40. ? curr->next
  41. : curr->prev;
  42. }
  43. return curr;
  44. }
  45. /*
  46. * Free the list iterator.
  47. */
  48. void
  49. list_iterator_destroy(list_iterator_t *self) {
  50. LIST_FREE(self);
  51. self = NULL;
  52. }