Re: GHashTable suggestions



on 1/4/01 11:52 AM, Sven Neumann at sven gimp org wrote:

> this might come a little late, but it's something I just stumpled
> across when looking at the GHashTable API. IMHO it would be very
> convenient if the function
> 
>         gboolean 
>         g_hash_table_remove (GHashTable    *hash_table,
>                              gconstpointer  key);
> 
> would instead return the removed value. Thus one could avoid to do
> two lookups when removing a value from a GHashTable. With the
> current API you have to
> 
>         value = g_hash_table_lookup (hash, key);
>         g_free (value)  /*  or unref or whatever  */
>         g_hash_table_remove (hash, key);
> 
> which could become
> 
>         g_free (g_hash_table_remove (hash, key));

For many of my hash tables, the key has to be removed as well. These changes
would help a bit, but I think the proposal below would help even more and be
more compatible.

> The same applies to g_hash_table_insert(). I must admit that it
> looks strange, but it would actually be useful if it would return
> the previous value in the case the key already existed in the
> GHashTable and it's value was replaced by the new one. The obvious
> advantage is that one could write
> 
>         g_free (g_hash_table_insert (hash, key, value));
> 
> instead of
> 
>         g_free (g_hash_table_lookup (hash, key);
>         g_hash_table_insert (hash, key, value);
> 
> Alternatively there could be new functions called for example
> 
>         gboolean g_hash_table_remove_and_destroy (hash, key);
>         gboolean g_hash_table_replace (hash, key, value);
> 
> but this could only work if there was a destroy function that could
> be registered with the GHashTable.

I'd do something like the second proposal. I'd make a new extended
g_hash_table_new (_full? _extended? _with_destroy_notify?) that takes key
and value destroy notify functions. Then I'd add:

        g_hash_table_remove_no_notify (hash, key);

Which resonates with gtk_object_remove_no_notify.

This change should be 100% backward compatible. The size of GHashTable would
have to change, but little else would.

    -- Darin





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