2 * Copyright (c) 2008, 2009 Nicira Networks.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
24 /* Initializes 'hmap' as an empty hash table. */
26 hmap_init(struct hmap *hmap)
28 hmap->buckets = &hmap->one;
34 /* Frees memory reserved by 'hmap'. It is the client's responsibility to free
35 * the nodes themselves, if necessary. */
37 hmap_destroy(struct hmap *hmap)
39 if (hmap && hmap->buckets != &hmap->one) {
44 /* Exchanges hash maps 'a' and 'b'. */
46 hmap_swap(struct hmap *a, struct hmap *b)
51 if (a->buckets == &b->one) {
54 if (b->buckets == &a->one) {
60 resize(struct hmap *hmap, size_t new_mask)
65 assert(!(new_mask & (new_mask + 1)));
66 assert(new_mask != SIZE_MAX);
70 tmp.buckets = xmalloc(sizeof *tmp.buckets * (new_mask + 1));
72 for (i = 0; i <= tmp.mask; i++) {
73 tmp.buckets[i] = NULL;
76 for (i = 0; i <= hmap->mask; i++) {
77 struct hmap_node *node, *next;
79 for (node = hmap->buckets[i]; node; node = next) {
81 hmap_insert_fast(&tmp, node, node->hash);
85 COVERAGE_INC(hmap_pathological);
88 hmap_swap(hmap, &tmp);
93 calc_mask(size_t capacity)
95 size_t mask = capacity / 2;
101 #if SIZE_MAX > UINT32_MAX
105 /* If we need to dynamically allocate buckets we might as well allocate at
106 * least 4 of them. */
107 mask |= (mask & 1) << 1;
112 /* Expands 'hmap', if necessary, to optimize the performance of searches. */
114 hmap_expand(struct hmap *hmap)
116 size_t new_mask = calc_mask(hmap->n);
117 if (new_mask > hmap->mask) {
118 COVERAGE_INC(hmap_expand);
119 resize(hmap, new_mask);
123 /* Shrinks 'hmap', if necessary, to optimize the performance of iteration. */
125 hmap_shrink(struct hmap *hmap)
127 size_t new_mask = calc_mask(hmap->n);
128 if (new_mask < hmap->mask) {
129 COVERAGE_INC(hmap_shrink);
130 resize(hmap, new_mask);
134 /* Expands 'hmap', if necessary, to optimize the performance of searches when
135 * it has up to 'n' elements. (But iteration will be slow in a hash map whose
136 * allocated capacity is much higher than its current number of nodes.) */
138 hmap_reserve(struct hmap *hmap, size_t n)
140 size_t new_mask = calc_mask(n);
141 if (new_mask > hmap->mask) {
142 COVERAGE_INC(hmap_reserve);
143 resize(hmap, new_mask);