]> pd.if.org Git - nbds/blob - map/map.c
generic map iterator interface
[nbds] / map / map.c
1 /* 
2  * Written by Josh Dybnis and released to the public domain, as explained at
3  * http://creativecommons.org/licenses/publicdomain
4  *
5  * generic interface for map-like data structures
6  */
7
8 #include "common.h"
9 #include "map.h"
10 #include "mem.h"
11
12 struct map {
13     const map_impl_t *impl;
14     void *data;
15 };
16
17 struct map_iter {
18     const map_impl_t *impl;
19     void *state;
20 };
21
22 map_t *map_alloc (const map_impl_t *map_impl, const datatype_t *key_type) { 
23     map_t *map = nbd_malloc(sizeof(map_t)); 
24     map->impl  = map_impl;
25     map->data  = map->impl->alloc(key_type);
26     return map;
27 }
28
29 void map_free (map_t *map) {
30     map->impl->free_(map->data);
31 }
32
33 void map_print (map_t *map) {
34     map->impl->print(map->data);
35 }
36
37 uint64_t map_count (map_t *map) {
38     return map->impl->count(map->data);
39 }
40
41 uint64_t map_get (map_t *map, void *key) {
42     return map->impl->get(map->data, key);
43 }
44
45 uint64_t map_set (map_t *map, void *key, uint64_t new_val) {
46     return map->impl->cas(map->data, key, CAS_EXPECT_WHATEVER, new_val);
47 }
48
49 uint64_t map_add (map_t *map, void *key, uint64_t new_val) {
50     return map->impl->cas(map->data, key, CAS_EXPECT_DOES_NOT_EXIST, new_val);
51 }
52
53 uint64_t map_cas (map_t *map, void *key, uint64_t expected_val, uint64_t new_val) {
54     return map->impl->cas(map->data, key, expected_val, new_val);
55 }
56
57 uint64_t map_replace(map_t *map, void *key, uint64_t new_val) {
58     return map->impl->cas(map->data, key, CAS_EXPECT_EXISTS, new_val);
59 }
60
61 uint64_t map_remove (map_t *map, void *key) {
62     return map->impl->remove(map->data, key);
63 }
64
65 map_iter_t * map_iter_begin (map_t *map, void *key) {
66     map_iter_t *iter = nbd_malloc(sizeof(map_iter_t));
67     iter->impl  = map->impl;
68     iter->state = map->impl->iter_begin(map->data, key);
69     return iter;
70 }
71
72 uint64_t map_iter_next (map_iter_t *iter, void **key_ptr) {
73     return iter->impl->iter_next(iter->state, key_ptr);
74 }
75
76 void map_iter_free (map_iter_t *iter) {
77     iter->impl->iter_free(iter->state);
78     nbd_free(iter);
79 }