Hi Denis,
On ti, 2015-02-10 at 16:42 +0200, Jukka Rissanen wrote:
Add new function l_hashmap_find() which is similar to foreach.
The find will start to call a user supplied function for every
entry in hashmap. If user function returns true, then the find
will return and not call remaining hash elements.
---
Just wanted to ask are you ok with func? At the moment there is no
function to traverse the hash, other than the foreach variant and it is
very sub-optimal as it will traverse the whole hash even if such a thing
is not needed by the caller. Even better option would be to change the
return parameter of foreach callback to return bool so we could do with
only one traversing function.
ell/hashmap.c | 39 +++++++++++++++++++++++++++++++++++++++
ell/hashmap.h | 5 +++++
2 files changed, 44 insertions(+)
diff --git a/ell/hashmap.c b/ell/hashmap.c
index 6c7c10f..03fcd7c 100644
--- a/ell/hashmap.c
+++ b/ell/hashmap.c
@@ -687,3 +687,42 @@ LIB_EXPORT bool l_hashmap_isempty(struct l_hashmap *hashmap)
return hashmap->entries == 0;
}
+
+/**
+ * l_hashmap_find:
+ * @hashmap: hash table object
+ * @function: callback function
+ * @user_data: user data given to callback function
+ *
+ * Call @function for every entry in @hashmap. If @function returns true,
+ * then quit calling @function.
+ **/
+LIB_EXPORT void l_hashmap_find(struct l_hashmap *hashmap,
+ l_hashmap_find_func_t function, void *user_data)
+{
+ unsigned int i;
+
+ if (unlikely(!hashmap || !function))
+ return;
+
+ for (i = 0; i < NBUCKETS; i++) {
+ struct entry *entry, *head = &hashmap->buckets[i];
+
+ if (!head->next)
+ continue;
+
+ for (entry = head;; entry = entry->next) {
+ bool found;
+
+ if (!entry->removed) {
+ found = function(entry->key, entry->value,
+ user_data);
+ if (found)
+ return;
+ }
+
+ if (entry->next == head)
+ break;
+ }
+ }
+}
diff --git a/ell/hashmap.h b/ell/hashmap.h
index a904109..3085477 100644
--- a/ell/hashmap.h
+++ b/ell/hashmap.h
@@ -31,6 +31,8 @@ extern "C" {
typedef void (*l_hashmap_foreach_func_t) (const void *key, void *value,
void *user_data);
+typedef bool (*l_hashmap_find_func_t) (const void *key, void *value,
+ void *user_data);
typedef void (*l_hashmap_destroy_func_t) (void *value);
typedef unsigned int (*l_hashmap_hash_func_t) (const void *p);
typedef int (*l_hashmap_compare_func_t) (const void *a, const void *b);
@@ -70,6 +72,9 @@ void *l_hashmap_lookup(struct l_hashmap *hashmap, const void *key);
void l_hashmap_foreach(struct l_hashmap *hashmap,
l_hashmap_foreach_func_t function, void *user_data);
+void l_hashmap_find(struct l_hashmap *hashmap,
+ l_hashmap_find_func_t function, void *user_data);
+
unsigned int l_hashmap_size(struct l_hashmap *hashmap);
bool l_hashmap_isempty(struct l_hashmap *hashmap);
Jukka