ghash: Add g_hash_table_new_similar()

This function creates a new hash table, but inherits the functions used
for the hash, comparison, and key/value memory management functions from
another hash table.

The primary use case is to implement a behaviour where you maintain a
hash table by regenerating it, letting the values not migrated be freed.
See the following pseudo code:

```
GHashTable *ht;

init(GList *resources) {
  ht = g_hash_table_new (g_str_hash, g_str_equal, g_free, g_free);
  for (r in resources)
    g_hash_table_insert (ht, strdup (resource_get_key (r)), create_value (r));
}

update(GList *resources) {
  GHashTable *new_ht = g_hash_table_new_similar (ht);

  for (r in resources) {
    if (g_hash_table_steal_extended (ht, resource_get_key (r), &key, &value))
      g_hash_table_insert (new_ht, key, value);
    else
      g_hash_table_insert (new_ht, strdup (resource_get_key (r)), create_value (r));
  }
  g_hash_table_unref (ht);
  ht = new_ht;
}
```
This commit is contained in:
Jonas Ådahl
2021-12-23 00:58:54 +01:00
parent 41d80f5029
commit 283d9e0c15
4 changed files with 74 additions and 0 deletions

View File

@@ -2851,6 +2851,7 @@ g_trash_stack_height
GHashTable
g_hash_table_new
g_hash_table_new_full
g_hash_table_new_similar
GHashFunc
GEqualFunc
g_hash_table_insert