GNOME Bugzilla – Bug 440732
Add split functions for the linked lists
Last modified: 2018-05-24 11:01:48 UTC
lately, I've been using a lot this code pattern to clamp a list: if (g_list_length (list) > limit) { GList *l, *clamp; clamp = g_list_nth (list, limit - 1); l = clamp->next; l->prev = NULL; clamp->next = NULL; g_list_foreach (l, (GFunc) my_free_func, NULL); g_list_free (l); } it would be interesting to have the clamping code directly inside GLib: GList *l = g_list_split (list, limit); g_list_foreach (l, (GFunc) my_free_func, NULL); g_list_free (l); the attached patch implements g_list_split() and g_slist_split().
Created attachment 88674 [details] [review] Add split function for lists This patch adds a g_list_split() and a g_slist_split() pair of functions. Thos are the inverse functions of g_list_concat() and g_slist_concat(), and split a G(S)List in two at the given position, returning the head of the second list. These functions are useful for clamping a list at a given number of elements, and freeing the rest using g_list_foreach()+g_list_free(). This patch also adds the needed documentation for the newly added functions. Signed-off-by: Emmanuele Bassi <ebassi@openedhand.com> --- docs/reference/glib/tmpl/linked_lists_double.sgml | 12 ++++++++++++ docs/reference/glib/tmpl/linked_lists_single.sgml | 12 ++++++++++++ glib/glib.symbols | 2 ++ glib/glist.c | 19 +++++++++++++++++++ glib/glist.h | 2 ++ glib/gslist.c | 19 +++++++++++++++++++ glib/gslist.h | 2 ++ 7 files changed, 68 insertions(+), 0 deletions(-)
What happens if n == 0? Don't you lose the head of the first list in that case?
mmh, if n == 0 it segfaults segfaults at the moment, as g_list_nth(n - 1) would return an unchecked NULL. either a g_return_val_if_fail (n > 0, NULL) should be added or if (n == 0) set the passed head pointer to NULL and return the same list. I must admit that the 0 case is a bit pathological, so I'd add a n > 0 guard.
Wouldn't it be nicer to have g_list_split take the new list head? void g_list_split (GList *list, GList *head_of_split_list); You could get the same behaviour as the current patch by using g_list_split (list, g_list_nth (list, limit)) that way, it'd be a lot easier to implement and be a lot more functional if you iterate through the list without keeping track of the index. It would be O(n) for GSList though.
-- GitLab Migration Automatic Message -- This bug has been migrated to GNOME's GitLab instance and has been closed from further activity. You can subscribe and participate further through the new bug through this link to our GitLab instance: https://gitlab.gnome.org/GNOME/glib/issues/93.