Skip to content

Commit 75a4a03

Browse files
JinZhou5042Jin Zhou
andauthored
vine: LIST_ITERATE_REVERSE (#4252)
Co-authored-by: Jin Zhou <[email protected]>
1 parent e376617 commit 75a4a03

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

dttools/src/list.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -629,6 +629,11 @@ void list_first_item(struct list *list)
629629
list_seek(list->iter, 0);
630630
}
631631

632+
void list_last_item(struct list *list)
633+
{
634+
list_seek(list->iter, -1);
635+
}
636+
632637
void *list_next_item(struct list *list)
633638
{
634639
void *item = NULL;
@@ -637,6 +642,14 @@ void *list_next_item(struct list *list)
637642
return item;
638643
}
639644

645+
void *list_prev_item(struct list *list)
646+
{
647+
void *item = NULL;
648+
list_get(list->iter, &item);
649+
list_prev(list->iter);
650+
return item;
651+
}
652+
640653
struct list *list_duplicate(struct list *src)
641654
{
642655
void *item;

dttools/src/list.h

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,14 @@ Call @ref list_next_item to begin returning the items.
374374

375375
void list_first_item(struct list *list);
376376

377+
/** Begin traversing a list in reverse.
378+
This function sets the internal list iterator to the last item.
379+
Call @ref list_prev_item to begin returning the items in reverse order.
380+
@param list The list to traverse.
381+
*/
382+
383+
void list_last_item(struct list *list);
384+
377385
/** Continue traversing a list.
378386
This function returns the current list item,
379387
and advances the internal iterator to the next item.
@@ -383,6 +391,15 @@ and advances the internal iterator to the next item.
383391

384392
void *list_next_item(struct list *list);
385393

394+
/** Continue traversing a list in reverse.
395+
This function returns the current list item,
396+
and advances the internal iterator to the previous item.
397+
@param list The list to traverse.
398+
@return The current item in the list, NULL if end of list.
399+
*/
400+
401+
void *list_prev_item(struct list *list);
402+
386403
/** Apply a function to a list.
387404
Invokes op on every member of the list.
388405
@param list The list to operate on.
@@ -421,4 +438,16 @@ LIST_ITERATE( list, s ) {
421438

422439
#define LIST_ITERATE( list, item ) list_first_item(list); while((item=list_next_item(list)))
423440

441+
/** Macro to iterate over a list in reverse order.
442+
Note that a statement or code block must follow the macro, like this:
443+
<pre>
444+
char *s;
445+
LIST_ITERATE_REVERSE( list, s ) {
446+
printf("%s\n",s);
447+
}
448+
</pre>
449+
*/
450+
451+
#define LIST_ITERATE_REVERSE( list, item ) list_last_item(list); while((item=list_prev_item(list)))
452+
424453
#endif

0 commit comments

Comments
 (0)