X-Git-Url: http://git.onelab.eu/?a=blobdiff_plain;f=lib%2Fhmap.c;h=9f2774465c3c357b81b4a0086594966e1a72cd11;hb=ae490a5642978cd52b698583c62c3e7a52f6a92f;hp=1b4816d9ddbeeb60cedb10723cf8c0da4c6d96ee;hpb=f2f7be8696e030dbe6f7c859c4e2bd76fd363036;p=sliver-openvswitch.git diff --git a/lib/hmap.c b/lib/hmap.c index 1b4816d9d..9f2774465 100644 --- a/lib/hmap.c +++ b/lib/hmap.c @@ -18,10 +18,16 @@ #include "hmap.h" #include #include +#include #include "coverage.h" #include "random.h" #include "util.h" +COVERAGE_DEFINE(hmap_pathological); +COVERAGE_DEFINE(hmap_expand); +COVERAGE_DEFINE(hmap_shrink); +COVERAGE_DEFINE(hmap_reserve); + /* Initializes 'hmap' as an empty hash table. */ void hmap_init(struct hmap *hmap) @@ -42,6 +48,22 @@ hmap_destroy(struct hmap *hmap) } } +/* Removes all node from 'hmap', leaving it ready to accept more nodes. Does + * not free memory allocated for 'hmap'. + * + * This function is appropriate when 'hmap' will soon have about as many + * elements as it before. If 'hmap' will likely have fewer elements than + * before, use hmap_destroy() followed by hmap_clear() to save memory and + * iteration time. */ +void +hmap_clear(struct hmap *hmap) +{ + if (hmap->n > 0) { + hmap->n = 0; + memset(hmap->buckets, 0, (hmap->mask + 1) * sizeof *hmap->buckets); + } +} + /* Exchanges hash maps 'a' and 'b'. */ void hmap_swap(struct hmap *a, struct hmap *b) @@ -196,3 +218,46 @@ hmap_random_node(const struct hmap *hmap) } return node; } + +/* Returns the next node in 'hmap' in hash order, or NULL if no nodes remain in + * 'hmap'. Uses '*bucketp' and '*offsetp' to determine where to begin + * iteration, and stores new values to pass on the next iteration into them + * before returning. + * + * It's better to use plain HMAP_FOR_EACH and related functions, since they are + * faster and better at dealing with hmaps that change during iteration. + * + * Before beginning iteration, store 0 into '*bucketp' and '*offsetp'. + */ +struct hmap_node * +hmap_at_position(const struct hmap *hmap, + uint32_t *bucketp, uint32_t *offsetp) +{ + size_t offset; + size_t b_idx; + + offset = *offsetp; + for (b_idx = *bucketp; b_idx <= hmap->mask; b_idx++) { + struct hmap_node *node; + size_t n_idx; + + for (n_idx = 0, node = hmap->buckets[b_idx]; node != NULL; + n_idx++, node = node->next) { + if (n_idx == offset) { + if (node->next) { + *bucketp = node->hash & hmap->mask; + *offsetp = offset + 1; + } else { + *bucketp = (node->hash & hmap->mask) + 1; + *offsetp = 0; + } + return node; + } + } + offset = 0; + } + + *bucketp = 0; + *offsetp = 0; + return NULL; +}