]> git.ipfire.org Git - thirdparty/kmod.git/commitdiff
hash: add iterator
authorLucas De Marchi <lucas.demarchi@profusion.mobi>
Tue, 27 Dec 2011 15:27:01 +0000 (13:27 -0200)
committerLucas De Marchi <lucas.demarchi@profusion.mobi>
Tue, 27 Dec 2011 20:11:58 +0000 (18:11 -0200)
libkmod/libkmod-hash.c
libkmod/libkmod-hash.h

index 15140ece3f94d03994c7005056ef3ed0cb55f3f5..8ca9cf41e2cb6729d97c7f19925b7ab8e88aad44 100644 (file)
@@ -285,3 +285,43 @@ unsigned int hash_get_count(const struct hash *hash)
 {
        return hash->count;
 }
+
+void hash_iter_init(const struct hash *hash, struct hash_iter *iter)
+{
+       iter->hash = hash;
+       iter->bucket = 0;
+       iter->entry = -1;
+}
+
+bool hash_iter_next(struct hash_iter *iter, const char **key,
+                                                       const void **value)
+{
+       const struct hash_bucket *b = iter->hash->buckets + iter->bucket;
+       const struct hash_entry *e;
+
+       iter->entry++;
+
+       if (iter->entry >= b->used) {
+               iter->entry = 0;
+
+               for (iter->bucket++; iter->bucket < iter->hash->n_buckets;
+                                                       iter->bucket++) {
+                       b = iter->hash->buckets + iter->bucket;
+
+                       if (b->used > 0)
+                               break;
+               }
+
+               if (iter->bucket >= iter->hash->n_buckets)
+                       return false;
+       }
+
+       e = b->entries + iter->entry;
+
+       if (value != NULL)
+               *value = e->value;
+       if (key != NULL)
+               *key = e->key;
+
+       return true;
+}
index 53e6c81d3fe90e44689e907161d314d9945fa23d..8f20b8f4e2d964f6bcdfb6a53a2a686253d4c3fe 100644 (file)
@@ -1,7 +1,16 @@
 #ifndef _LIBKMOD_HASH_H_
 #define _LIBKMOD_HASH_H_
 
+#include <stdbool.h>
+
 struct hash;
+
+struct hash_iter {
+       const struct hash *hash;
+       unsigned int bucket;
+       unsigned int entry;
+};
+
 struct hash *hash_new(unsigned int n_buckets, void (*free_value)(void *value));
 void hash_free(struct hash *hash);
 int hash_add(struct hash *hash, const char *key, const void *value);
@@ -9,5 +18,8 @@ int hash_add_unique(struct hash *hash, const char *key, const void *value);
 int hash_del(struct hash *hash, const char *key);
 void *hash_find(const struct hash *hash, const char *key);
 unsigned int hash_get_count(const struct hash *hash);
+void hash_iter_init(const struct hash *hash, struct hash_iter *iter);
+bool hash_iter_next(struct hash_iter *iter, const char **key,
+                                                       const void **value);
 
 #endif