shash: Introduce new macros SHASH_FOR_EACH, SHASH_FOR_EACH_SAFE.
[sliver-openvswitch.git] / lib / shash.c
1 /*
2  * Copyright (c) 2009 Nicira Networks.
3  *
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:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <config.h>
18 #include "shash.h"
19 #include <assert.h>
20 #include "hash.h"
21
22 static size_t
23 hash_name(const char *name)
24 {
25     return hash_string(name, 0);
26 }
27
28 void
29 shash_init(struct shash *sh)
30 {
31     hmap_init(&sh->map);
32 }
33
34 void
35 shash_destroy(struct shash *sh)
36 {
37     if (sh) {
38         shash_clear(sh);
39     }
40 }
41
42 void
43 shash_clear(struct shash *sh)
44 {
45     struct shash_node *node, *next;
46
47     SHASH_FOR_EACH_SAFE (node, next, sh) {
48         hmap_remove(&sh->map, &node->node);
49         free(node->name);
50         free(node);
51     }
52 }
53
54 bool
55 shash_is_empty(const struct shash *shash)
56 {
57     return hmap_is_empty(&shash->map);
58 }
59
60 /* It is the caller's responsibility to avoid duplicate names, if that is
61  * desirable. */
62 struct shash_node *
63 shash_add(struct shash *sh, const char *name, void *data)
64 {
65     struct shash_node *node = xmalloc(sizeof *node);
66     node->name = xstrdup(name);
67     node->data = data;
68     hmap_insert(&sh->map, &node->node, hash_name(name));
69     return node;
70 }
71
72 void
73 shash_delete(struct shash *sh, struct shash_node *node)
74 {
75     hmap_remove(&sh->map, &node->node);
76     free(node->name);
77     free(node);
78 }
79
80 /* If there are duplicates, returns a random element. */
81 struct shash_node *
82 shash_find(const struct shash *sh, const char *name)
83 {
84     struct shash_node *node;
85
86     HMAP_FOR_EACH_WITH_HASH (node, struct shash_node, node,
87                              hash_name(name), &sh->map) {
88         if (!strcmp(node->name, name)) {
89             return node;
90         }
91     }
92     return NULL;
93 }
94
95 void *
96 shash_find_data(const struct shash *sh, const char *name)
97 {
98     struct shash_node *node = shash_find(sh, name);
99     return node ? node->data : NULL;
100 }
101
102 struct shash_node *
103 shash_first(const struct shash *shash)
104 {
105     struct hmap_node *node = hmap_first(&shash->map);
106     return node ? CONTAINER_OF(node, struct shash_node, node) : NULL;
107 }
108