Browse Source

list: add convenience function to get item by index

K. Lange 10 months ago
parent
commit
2cddc37a67
2 changed files with 10 additions and 0 deletions
  1. 1 0
      base/usr/include/toaru/list.h
  2. 9 0
      lib/list.c

+ 1 - 0
base/usr/include/toaru/list.h

@@ -42,6 +42,7 @@ extern node_t * list_pop(list_t * list);
 extern node_t * list_dequeue(list_t * list);
 extern list_t * list_copy(list_t * original);
 extern void list_merge(list_t * target, list_t * source);
+extern void * list_index(list_t * list, int index);
 
 extern void list_append_after(list_t * list, node_t * before, node_t * node);
 extern node_t * list_insert_after(list_t * list, node_t * before, void * item);

+ 9 - 0
lib/list.c

@@ -166,6 +166,15 @@ int list_index_of(list_t * list, void * value) {
 	return -1; /* not find */
 }
 
+void * list_index(list_t * list, int index) {
+	int i = 0;
+	foreach(item, list) {
+		if (i == index) return item->value;
+		i++;
+	}
+	return NULL;
+}
+
 void list_remove(list_t * list, size_t index) {
 	/* remove index from the list */
 	if (index > list->length) return;