shash: Fix memory leak in shash_destroy().
[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         hmap_destroy(&sh->map);
40     }
41 }
42
43 void
44 shash_clear(struct shash *sh)
45 {
46     struct shash_node *node, *next;
47
48     HMAP_FOR_EACH_SAFE (node, next, struct shash_node, node, &sh->map) {
49         hmap_remove(&sh->map, &node->node);
50         free(node->name);
51         free(node);
52     }
53 }
54
55 /* It is the caller's responsible to avoid duplicate names, if that is
56  * desirable. */
57 void
58 shash_add(struct shash *sh, const char *name, void *data)
59 {
60     struct shash_node *node = xmalloc(sizeof *node);
61     node->name = xstrdup(name);
62     node->data = data;
63     hmap_insert(&sh->map, &node->node, hash_name(name));
64 }
65
66 void
67 shash_delete(struct shash *sh, struct shash_node *node)
68 {
69     hmap_remove(&sh->map, &node->node);
70     free(node->name);
71     free(node);
72 }
73
74 /* If there are duplicates, returns a random element. */
75 struct shash_node *
76 shash_find(const struct shash *sh, const char *name)
77 {
78     struct shash_node *node;
79
80     HMAP_FOR_EACH_WITH_HASH (node, struct shash_node, node,
81                              hash_name(name), &sh->map) {
82         if (!strcmp(node->name, name)) {
83             return node;
84         }
85     }
86     return NULL;
87 }
88
89 void *
90 shash_find_data(const struct shash *sh, const char *name)
91 {
92     struct shash_node *node = shash_find(sh, name);
93     return node ? node->data : NULL;
94 }