From 8d1278d03fd57ed970f38d760807563604225fbd Mon Sep 17 00:00:00 2001 From: Lucas De Marchi Date: Tue, 27 Dec 2011 13:27:01 -0200 Subject: [PATCH] hash: add iterator --- libkmod/libkmod-hash.c | 40 ++++++++++++++++++++++++++++++++++++++++ libkmod/libkmod-hash.h | 12 ++++++++++++ 2 files changed, 52 insertions(+) diff --git a/libkmod/libkmod-hash.c b/libkmod/libkmod-hash.c index 15140ec..8ca9cf4 100644 --- a/libkmod/libkmod-hash.c +++ b/libkmod/libkmod-hash.c @@ -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; +} diff --git a/libkmod/libkmod-hash.h b/libkmod/libkmod-hash.h index 53e6c81..8f20b8f 100644 --- a/libkmod/libkmod-hash.h +++ b/libkmod/libkmod-hash.h @@ -1,7 +1,16 @@ #ifndef _LIBKMOD_HASH_H_ #define _LIBKMOD_HASH_H_ +#include + 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 -- 2.7.4