[pacman-dev] [PATCH] add alpm_list_append

Andrew Gregory andrew.gregory.8 at gmail.com
Mon Jan 11 14:29:22 UTC 2016


alpm_list_add always returns the provided list making it impossible for
callers to check whether or not the operation actually succeeded without
manually comparing the list length before and after.  alpm_list_append
instead returns a pointer to the newly created list item so that success
can be checked.

Signed-off-by: Andrew Gregory <andrew.gregory.8 at gmail.com>
---
 lib/libalpm/alpm_list.c | 34 ++++++++++++++++++++++++----------
 lib/libalpm/alpm_list.h |  1 +
 2 files changed, 25 insertions(+), 10 deletions(-)

diff --git a/lib/libalpm/alpm_list.c b/lib/libalpm/alpm_list.c
index 62b2843..f3effc7 100644
--- a/lib/libalpm/alpm_list.c
+++ b/lib/libalpm/alpm_list.c
@@ -93,28 +93,42 @@ void SYMEXPORT alpm_list_free_inner(alpm_list_t *list, alpm_list_fn_free fn)
  */
 alpm_list_t SYMEXPORT *alpm_list_add(alpm_list_t *list, void *data)
 {
-	alpm_list_t *ptr, *lp;
+	alpm_list_append(&list, data);
+	return list;
+}
+
+/**
+ * @brief Add a new item to the end of the list.
+ *
+ * @param list the list to add to
+ * @param data the new item to be added to the list
+ *
+ * @return the newly added item
+ */
+alpm_list_t SYMEXPORT *alpm_list_append(alpm_list_t **list, void *data)
+{
+	alpm_list_t *ptr;
 
 	ptr = malloc(sizeof(alpm_list_t));
 	if(ptr == NULL) {
-		return list;
+		return NULL;
 	}
 
 	ptr->data = data;
 	ptr->next = NULL;
 
 	/* Special case: the input list is empty */
-	if(list == NULL) {
+	if(*list == NULL) {
+		*list = ptr;
 		ptr->prev = ptr;
-		return ptr;
+	} else {
+		alpm_list_t *lp = alpm_list_last(*list);
+		lp->next = ptr;
+		ptr->prev = lp;
+		(*list)->prev = ptr;
 	}
 
-	lp = alpm_list_last(list);
-	lp->next = ptr;
-	ptr->prev = lp;
-	list->prev = ptr;
-
-	return list;
+	return ptr;
 }
 
 /**
diff --git a/lib/libalpm/alpm_list.h b/lib/libalpm/alpm_list.h
index 801f4a0..5af84e1 100644
--- a/lib/libalpm/alpm_list.h
+++ b/lib/libalpm/alpm_list.h
@@ -57,6 +57,7 @@ void alpm_list_free_inner(alpm_list_t *list, alpm_list_fn_free fn);
 
 /* item mutators */
 alpm_list_t *alpm_list_add(alpm_list_t *list, void *data);
+alpm_list_t *alpm_list_append(alpm_list_t **list, void *data);
 alpm_list_t *alpm_list_add_sorted(alpm_list_t *list, void *data, alpm_list_fn_cmp fn);
 alpm_list_t *alpm_list_join(alpm_list_t *first, alpm_list_t *second);
 alpm_list_t *alpm_list_mmerge(alpm_list_t *left, alpm_list_t *right, alpm_list_fn_cmp fn);
-- 
2.7.0


More information about the pacman-dev mailing list