g_hash_table_lookup_iter
Submitted by Allison (desrt)
Link to original bug (#686326)
Description
It's quite often that you want to perform 'complex' operations on a hashtable.
Things like "lookup and modify if exists, or create otherwise" or "lookup and modify, possibly removing".
GHashTableIter
is quite a good way to support this. We already support remove/replace operations on it.
gboolean g_hash_table_lookup_iter (GHashTable *table,
constgpointer key,
GHashTableIter *iter);
gpointer g_hash_table_iter_get_data (GHashTableIter *iter);
Then we could do stuff like:
if (g_hash_table_lookup_iter (table, key, &iter))
{
mydata = g_hash_table_iter_get_data (&iter);
...modify mydata...
if (mydata->should_be_removed)
g_hash_table_iter_remove (&iter);
}
and a similar example with outright replacement.
Now onto the real crack:
One other common pattern that's a bit annoying is "lookup and insert if missing". That one is a bit more complicated to implement because we'd have to support GHashTableIter
pointing to non-existent potential future items. I don't really care for that possibility, so we could have instead:
gboolean g_hash_table_insert_or_lookup_iter (GHashTable *table,
gconstpointer key,
GCopyFunc key_copy_func,
gpointer copy_user_data,
GHashTableIter *iter);
This would either lookup the iter (as above) or, if it didn't exist, copy the key and insert it with NULL
data (presumably to be modified later with g_hash_table_iter_replace()
).