1 /* Copyright (c) 2008, Sandia National Laboratories */
3 #include <lwk/kernel.h>
5 #include <lwk/htable.h>
10 struct hlist_head * tbl;
11 size_t obj_key_offset;
12 size_t obj_link_offset;
17 obj2key(const struct htable *ht, const void *obj)
19 return *((id_t *)((uintptr_t)obj + ht->obj_key_offset));
22 static struct hlist_node *
23 obj2node(const struct htable *ht, const void *obj)
25 return (struct hlist_node *)((uintptr_t)obj + ht->obj_link_offset);
29 node2obj(const struct htable *ht, const struct hlist_node *node)
31 return (void *)((uintptr_t)node - ht->obj_link_offset);
35 node2key(const struct htable *ht, const struct hlist_node *node)
37 return obj2key(ht, node2obj(ht, node));
40 static struct hlist_head *
41 key2head(const struct htable *ht, id_t key)
43 return &ht->tbl[hash_long(key, ht->tbl_order)];
46 static struct hlist_head *
47 obj2head(const struct htable *ht, const void *obj)
49 return &ht->tbl[hash_long(obj2key(ht, obj), ht->tbl_order)];
53 htable_create(size_t tbl_order,
54 size_t obj_key_offset, size_t obj_link_offset, htable_t *tbl)
59 if (!(ht = kmem_alloc(sizeof(*ht))))
62 ht->tbl_order = tbl_order;
63 tbl_size = (1 << tbl_order);
65 if (!(ht->tbl = kmem_alloc(tbl_size * sizeof(struct hlist_head))))
68 ht->obj_key_offset = obj_key_offset;
69 ht->obj_link_offset = obj_link_offset;
77 htable_destroy(htable_t tbl)
79 struct htable *ht = tbl;
88 htable_add(htable_t tbl, void *obj)
90 struct htable *ht = tbl;
91 hlist_add_head(obj2node(ht, obj), obj2head(ht, obj));
97 htable_del(htable_t tbl, void *obj)
99 struct htable *ht = tbl;
100 struct hlist_node *node;
101 hlist_for_each(node, obj2head(ht, obj)) {
102 if (obj == node2obj(ht, node)) {
112 htable_lookup(htable_t tbl, id_t key)
114 struct htable *ht = tbl;
115 struct hlist_node *node;
116 hlist_for_each(node, key2head(ht, key)) {
117 if (key == node2key(ht, node))
118 return node2obj(ht, node);