1 | #include <stdlib.h>
|
---|
2 | #include <stdio.h>
|
---|
3 | #include <assert.h>
|
---|
4 | #include "libchash.h"
|
---|
5 |
|
---|
6 | static void TestInsert() {
|
---|
7 | struct HashTable* ht;
|
---|
8 | HTItem* bck;
|
---|
9 |
|
---|
10 | ht = AllocateHashTable(1, 0); /* value is 1 byte, 0: don't copy keys */
|
---|
11 |
|
---|
12 | HashInsert(ht, PTR_KEY(ht, "January"), 31); /* 0: don't overwrite old val */
|
---|
13 | bck = HashInsert(ht, PTR_KEY(ht, "February"), 28);
|
---|
14 | bck = HashInsert(ht, PTR_KEY(ht, "March"), 31);
|
---|
15 |
|
---|
16 | bck = HashFind(ht, PTR_KEY(ht, "February"));
|
---|
17 | assert(bck);
|
---|
18 | assert(bck->data == 28);
|
---|
19 |
|
---|
20 | FreeHashTable(ht);
|
---|
21 | }
|
---|
22 |
|
---|
23 | static void TestFindOrInsert() {
|
---|
24 | struct HashTable* ht;
|
---|
25 | int i;
|
---|
26 | int iterations = 1000000;
|
---|
27 | int range = 30; /* random number between 1 and 30 */
|
---|
28 |
|
---|
29 | ht = AllocateHashTable(4, 0); /* value is 4 bytes, 0: don't copy keys */
|
---|
30 |
|
---|
31 | /* We'll test how good rand() is as a random number generator */
|
---|
32 | for (i = 0; i < iterations; ++i) {
|
---|
33 | int key = rand() % range;
|
---|
34 | HTItem* bck = HashFindOrInsert(ht, key, 0); /* initialize to 0 */
|
---|
35 | bck->data++; /* found one more of them */
|
---|
36 | }
|
---|
37 |
|
---|
38 | for (i = 0; i < range; ++i) {
|
---|
39 | HTItem* bck = HashFind(ht, i);
|
---|
40 | if (bck) {
|
---|
41 | printf("%3d: %d\n", bck->key, bck->data);
|
---|
42 | } else {
|
---|
43 | printf("%3d: 0\n", i);
|
---|
44 | }
|
---|
45 | }
|
---|
46 |
|
---|
47 | FreeHashTable(ht);
|
---|
48 | }
|
---|
49 |
|
---|
50 | int main(int argc, char** argv) {
|
---|
51 | TestInsert();
|
---|
52 | TestFindOrInsert();
|
---|
53 | return 0;
|
---|
54 | }
|
---|