Re: API for iterating the g_hash_table

Sven Neumann wrote:

Tony Yat-Tung Cheung <dragonman asiayeah com> writes:

Currently, there is g_hash_table_size(), we could easily add iteration
by providing the following two new APIs,

gconstpointer g_hash_table_get_key(GHashTable *hash_table, int pos);
gconspointer g_hash_table_get_value(GHashTable *hash_table, int pos);

The two APIs allows one to iterate the hash table, for example,

for (i = 0; i < g_hash_table_size(hash_table); i++) {
  gconstpointer value = g_hash_table_get_value(hash_table, i);

  /* Do some processing here */
  if (is_match(value))
    return TRUE;

This looks rather akward since it exposes internals like the position
of an element in the hash table. If this functionality is actually
needed (do you have a use case?), then it should be an extended
version of g_hash_table_foreach() that stops traversal when the
callback function returns TRUE (just like g_tree_foreach).

Yes, the proposed API may expose too much implementation details in some views. For perfect API, one may want to use an iterator, instead of an integer index. Then APIs will become,
gconstpointer g_hash_table_get_key(GHashTable *hash_table, GHashTableIterator iterator);
gconspointer g_hash_table_get_value(GHashTable *hash_table, GHashTableIterator iterator);
It's certainly an improvement for g_hash_table_foreach() to stop traversal when the callback function returns TRUE. We should have this, except that it breaks the current API. Even with it, sometimes the user may also want to do more than just stopping the trasversal. He/she may also want to get the current node, return a special value from the current function...etc. I think the most convenient API is an iterator, either in a simple integer index or an iterator structure.


Tony Cheung

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