import hashtab
[hashtab.git] / example.c
blob4a34ce118ca56cc12d0df981b2c7df2457cd50ec
1 /*
2 * Copyright (c) 2015 Mohamed Aslan <maslan@sce.carleton.ca>
4 * Permission to use, copy, modify, and 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.
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.
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <err.h>
22 #include <hashtab.h>
24 int
25 main(int argc, char **argv)
27 int i;
28 struct hashtab ht;
29 char *key, *val;
30 size_t key_size, val_size;
31 size_t iter;
32 char *keys[] = {"hi", "hello", "world", "hello world", "open", "source", "kernel", "hack"};
33 char *values[] = {"1", "2", "3", "4", "5", "6", "7", "8"};
35 if (!hashtab_init(&ht, 4, NULL))
36 errx(1, "hashtab_init");
37 for (i = 0; i < 8; i++) {
38 hashtab_put(&ht, keys[i], strlen(keys[i]), values[i], strlen(values[i]) + 1);
39 printf("%s -> %s\n", keys[i], values[i]);
41 printf("\n");
42 for (i = 0; i < 8; i++) {
43 hashtab_get(&ht, keys[i], strlen(keys[i]), (void **) &val, &val_size);
44 printf("%s -> %s\n", keys[i], val);
47 printf("\nloop 1\n");
48 if (hashtab_first(&ht, &iter)) {
49 do {
50 hashtab_at(&ht, iter, (void *) &key, &key_size, (void **) &val, &val_size);
51 printf("%s -> %s\n", key, val);
52 } while (hashtab_next(&ht, &iter));
54 printf("done\n");
56 printf("loop 2\n");
57 HASHTAB_FOREACH(ht, iter, key, key_size, val, val_size) {
58 hashtab_at(&ht, iter, (void *) &key, &key_size, (void **) &val, &val_size);
59 printf("%s -> %s\n", key, val);
61 printf("done\n");
64 printf("\n");
65 hashtab_put(&ht, "world", strlen("world"), "10", strlen("10") + 1);
66 hashtab_get(&ht, "world", strlen("world"), (void **) &val, &val_size);
67 printf("world -> %s\n", val);
68 printf("\n");
69 hashtab_del(&ht, "world", strlen("world"));
70 if (hashtab_get(&ht, "world", strlen("world"), (void **) &val, &val_size))
71 printf("world -> %s\n", val);
72 else
73 printf("world not found\n");
74 return 0;