Moved data structures to new collections subfolder
[strongswan.git] / src / libcharon / plugins / unit_tester / tests / test_hashtable.c
1 /*
2 * Copyright (C) 2010 Tobias Brunner
3 * Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include <library.h>
17 #include <collections/hashtable.h>
18
19 static u_int hash(char *key)
20 {
21 return chunk_hash(chunk_create(key, strlen(key)));
22 }
23
24 static u_int equals(char *key1, char *key2)
25 {
26 return streq(key1, key2);
27 }
28
29 /**
30 * Test the remove_at method
31 */
32 bool test_hashtable_remove_at()
33 {
34 char *k1 = "key1", *k2 = "key2", *k3 = "key3", *key;
35 char *v1 = "val1", *v2 = "val2", *v3 = "val3", *value;
36 enumerator_t *enumerator;
37 hashtable_t *ht = hashtable_create((hashtable_hash_t)hash,
38 (hashtable_equals_t)equals, 0);
39
40 ht->put(ht, k1, v1);
41 ht->put(ht, k2, v2);
42 ht->put(ht, k3, v3);
43
44 if (ht->get_count(ht) != 3)
45 {
46 return FALSE;
47 }
48
49 enumerator = ht->create_enumerator(ht);
50 while (enumerator->enumerate(enumerator, &key, &value))
51 {
52 if (streq(key, k2))
53 {
54 ht->remove_at(ht, enumerator);
55 }
56 }
57 enumerator->destroy(enumerator);
58
59 if (ht->get_count(ht) != 2)
60 {
61 return FALSE;
62 }
63
64 if (ht->get(ht, k1) == NULL ||
65 ht->get(ht, k3) == NULL)
66 {
67 return FALSE;
68 }
69
70 if (ht->get(ht, k2) != NULL)
71 {
72 return FALSE;
73 }
74
75 ht->put(ht, k2, v2);
76
77 if (ht->get_count(ht) != 3)
78 {
79 return FALSE;
80 }
81
82 if (ht->get(ht, k1) == NULL ||
83 ht->get(ht, k2) == NULL ||
84 ht->get(ht, k3) == NULL)
85 {
86 return FALSE;
87 }
88
89 enumerator = ht->create_enumerator(ht);
90 while (enumerator->enumerate(enumerator, &key, &value))
91 {
92 ht->remove_at(ht, enumerator);
93 }
94 enumerator->destroy(enumerator);
95
96 if (ht->get_count(ht) != 0)
97 {
98 return FALSE;
99 }
100
101 if (ht->get(ht, k1) != NULL ||
102 ht->get(ht, k2) != NULL ||
103 ht->get(ht, k3) != NULL)
104 {
105 return FALSE;
106 }
107
108 ht->destroy(ht);
109
110 return TRUE;
111 }