Re: behavior of g_list_insert_sorted()




Marc Ewing <marc@redhat.com> writes:

> The way g_list_insert_sorted() interprets the results of the compare
> function seem non-intuitive to me.  From looking at glist.c it
> appears that if the compare function returns 0, the data is not
> inserted into the list at all.  "Standard" compare function
> behavior (ie, those used for qsort and bsearch) is to return 0
> if the elements are equal.
> 
> This is either a bug in g_list_insert_sorted(), or there is an
> unstated "if the element is already in the list it won't be added"
> behavior.

Besides the non-standard part, there is another problem with this
behavior - you can't tell if the item got inserted or not. (And
thus, unless you are inserting ints casted to gpointer, you
risk leaking memory).

I'd say we should change g_list_insert_sorted to act "normally".
If someone really needs the unique behavior, we could add another
function

  gboolean g_list_insert_sorted_uniq (GList     **list, 
                                     gpointer     data,
                                     GCompareFunc func);

or

  GList *g_list_insert_sorted_uniq (GList       *list, 
                                    gpointer     data,
                                    GCompareFunc func,
                                    gboolean    *inserted);

But this probably can be left out until someone asks for it.

> Any thoughts on this?  (I notice that g_list_insert_sorted() isn't
> used anywhere in gtk, gimp, or gnome, so I guess nobody has run
> across this before).

Looking at the ChangeLog:

Wed Jan  7 02:14:30 PST 1998 Manish Singh <yosh@gimp.org>

        * glib/glib.h
        * glib/glist.c
        * glib/gslist.c
        * glib/testglib.c: Added g_[s]list_insert_sorted function
        and appropriate tests in testglib

So I assume Yosh had some use for it in mind. Perhaps he'll 
enlighten us on the original intent.

Regards,
                                        Owen



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]