diff options
Diffstat (limited to 'example_hashmap/new/main.c')
-rw-r--r-- | example_hashmap/new/main.c | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/example_hashmap/new/main.c b/example_hashmap/new/main.c new file mode 100644 index 0000000..4846ab5 --- /dev/null +++ b/example_hashmap/new/main.c @@ -0,0 +1,62 @@ +#include <assert.h> +#include <stdio.h> + +#include "map.h" + +#define foreach(name, i, s) \ + for (name##_iter i = name##_begin(s); !name##_end(s, i); i = name##_next(i)) + +/* int wrapper, provides cmp/hash for a generic integer type + * (here a trait like is_integer would be ideal but oh well) */ +typedef intw[any I]() { + typedef I <>; + + size_t <>_hash(<> *a) + { + /* identity hash */ + return *a; + } + + int <>_cmp(<> *a, <> *b) + { + return *a - *b; + } +}; + +/* create wrapper for ints. */ +typedef intw = intw[int](); + +/* create hashmap of ints, using the intw wrapper we just created. Kind of + * boilerplatey, admittedly. */ +typedef ints = map[intw, intw](); + +int main() +{ + /* heuristic, but if we know how many elements we'll need, we should + * give it to the create function. */ + ints ints = ints_create(0); + for (int i = 0; i < 1000000; ++i) { + ints_insert(&ints, i, i); + } + assert(ints_len(&ints) == 1000000); + + for (int i = 0; i < 1000000; ++i) { + int *v = ints_find(&ints, i); + assert(v && *v == i); + } + + size_t count = 0; + foreach(ints, iter, &ints) { + assert(iter->key == iter->data); + count++; + } + + assert(count == 1000000); + + for (int i = 0; i < 1000000; ++i) { + ints_remove(&ints, i); + } + + assert(ints_len(&ints) == 0); + ints_destroy(&ints); +} |