Import from old repository commit 61ef2b42a9c4ba8e1600f15bb0236765edc2ad45.
[cascardo/ovs.git] / lib / shash.c
1 /*
2  * Copyright (c) 2009 Nicira Networks.
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
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     HMAP_FOR_EACH_SAFE (node, next, struct shash_node, node, &sh->map) {
48         hmap_remove(&sh->map, &node->node);
49         free(node->name);
50         free(node);
51     }
52 }
53
54 /* It is the caller's responsible to avoid duplicate names, if that is
55  * desirable. */
56 void
57 shash_add(struct shash *sh, const char *name, void *data)
58 {
59     struct shash_node *node = xmalloc(sizeof *node);
60     node->name = xstrdup(name);
61     node->data = data;
62     hmap_insert(&sh->map, &node->node, hash_name(name));
63 }
64
65 void
66 shash_delete(struct shash *sh, struct shash_node *node)
67 {
68     hmap_remove(&sh->map, &node->node);
69     free(node->name);
70     free(node);
71 }
72
73 /* If there are duplicates, returns a random element. */
74 struct shash_node *
75 shash_find(const struct shash *sh, const char *name)
76 {
77     struct shash_node *node;
78
79     HMAP_FOR_EACH_WITH_HASH (node, struct shash_node, node,
80                              hash_name(name), &sh->map) {
81         if (!strcmp(node->name, name)) {
82             return node;
83         }
84     }
85     return NULL;
86 }
87
88 void *
89 shash_find_data(const struct shash *sh, const char *name)
90 {
91     struct shash_node *node = shash_find(sh, name);
92     return node ? node->data : NULL;
93 }