2 * Copyright (c) 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.
23 hash_name(const char *name)
25 return hash_string(name, 0);
29 shash_init(struct shash *sh)
35 shash_destroy(struct shash *sh)
39 hmap_destroy(&sh->map);
44 shash_clear(struct shash *sh)
46 struct shash_node *node, *next;
48 SHASH_FOR_EACH_SAFE (node, next, sh) {
49 hmap_remove(&sh->map, &node->node);
56 shash_is_empty(const struct shash *shash)
58 return hmap_is_empty(&shash->map);
62 shash_count(const struct shash *shash)
64 return hmap_count(&shash->map);
67 /* It is the caller's responsibility to avoid duplicate names, if that is
70 shash_add(struct shash *sh, const char *name, const void *data)
72 struct shash_node *node = xmalloc(sizeof *node);
73 node->name = xstrdup(name);
74 node->data = (void *) data;
75 hmap_insert(&sh->map, &node->node, hash_name(name));
80 shash_add_once(struct shash *sh, const char *name, const void *data)
82 if (!shash_find(sh, name)) {
83 shash_add(sh, name, data);
91 shash_delete(struct shash *sh, struct shash_node *node)
93 hmap_remove(&sh->map, &node->node);
98 /* If there are duplicates, returns a random element. */
100 shash_find(const struct shash *sh, const char *name)
102 struct shash_node *node;
104 HMAP_FOR_EACH_WITH_HASH (node, struct shash_node, node,
105 hash_name(name), &sh->map) {
106 if (!strcmp(node->name, name)) {
114 shash_find_data(const struct shash *sh, const char *name)
116 struct shash_node *node = shash_find(sh, name);
117 return node ? node->data : NULL;
121 shash_find_and_delete(struct shash *sh, const char *name)
123 struct shash_node *node = shash_find(sh, name);
125 void *data = node->data;
126 shash_delete(sh, node);
134 shash_first(const struct shash *shash)
136 struct hmap_node *node = hmap_first(&shash->map);
137 return node ? CONTAINER_OF(node, struct shash_node, node) : NULL;
141 compare_nodes_by_name(const void *a_, const void *b_)
143 const struct shash_node *const *a = a_;
144 const struct shash_node *const *b = b_;
145 return strcmp((*a)->name, (*b)->name);
148 const struct shash_node **
149 shash_sort(const struct shash *sh)
151 if (shash_is_empty(sh)) {
154 const struct shash_node **nodes;
155 struct shash_node *node;
159 nodes = xmalloc(n * sizeof *nodes);
161 SHASH_FOR_EACH (node, sh) {
166 qsort(nodes, n, sizeof *nodes, compare_nodes_by_name);