diff mbox series

[1/5] ptrlist: add ptr_list_nth_entry()

Message ID 20181101181117.3877-2-ben.dooks@codethink.co.uk (mailing list archive)
State Superseded, archived
Headers show
Series [1/5] ptrlist: add ptr_list_nth_entry() | expand

Commit Message

Ben Dooks Nov. 1, 2018, 6:11 p.m. UTC
From: Luc Van Oostenryck <luc.vanoostenryck@gmail.com>

Usually ptr lists are accessed iteratively via the FOR/END macros
but in few case we may need to access a given element in a list,
like for example when accessing a given argument of a function.

Create an helper doing that instead of open coding it.

[ben.dooks@codethink.co.uk: applied to current working tree]
Signed-off-by: Luc Van Oostenryck <luc.vanoostenryck@gmail.com>
---
 ptrlist.c | 22 ++++++++++++++++++++++
 ptrlist.h |  2 ++
 2 files changed, 24 insertions(+)
diff mbox series

Patch

diff --git a/ptrlist.c b/ptrlist.c
index 8402f8d..fce185d 100644
--- a/ptrlist.c
+++ b/ptrlist.c
@@ -29,6 +29,28 @@  int ptr_list_size(struct ptr_list *head)
 	return nr;
 }
 
+///
+// get the nth element of a ptrlist
+// @head: the head of the list
+// @return: the nth element of the list or ``NULL`` if the list is too short.
+void *ptr_list_nth_entry(struct ptr_list *list, unsigned int idx)
+{
+	struct ptr_list *head = list;
+
+	if (!head)
+		return NULL;
+
+	do {
+		unsigned int nr = list->nr;
+
+		if (idx < nr)
+			return list->list[idx];
+		else
+			idx -= nr;
+	} while ((list = list->next) != head);
+	return NULL;
+}
+
 /*
  * Linearize the entries of a list up to a total of 'max',
  * and return the nr of entries linearized.
diff --git a/ptrlist.h b/ptrlist.h
index 78625c8..41d3281 100644
--- a/ptrlist.h
+++ b/ptrlist.h
@@ -46,6 +46,8 @@  extern void __free_ptr_list(struct ptr_list **);
 extern int ptr_list_size(struct ptr_list *);
 extern int linearize_ptr_list(struct ptr_list *, void **, int);
 
+extern void *ptr_list_nth_entry(struct ptr_list *, unsigned int idx);
+
 /*
  * Hey, who said that you can't do overloading in C?
  *