test_lsquic_hash.c revision fb3e20e0
1/* Copyright (c) 2017 - 2020 LiteSpeed Technologies Inc.  See LICENSE. */
2#include <assert.h>
3#include <stdint.h>
4#include <stdio.h>
5#include <stdlib.h>
6#include <string.h>
7#include <sys/queue.h>
8#ifndef WIN32
9#include <unistd.h>
10#endif
11
12#include "lsquic_hash.h"
13
14
15struct widget
16{
17    unsigned long   key;
18    struct lsquic_hash_elem hash_el;
19    char            data[30];
20};
21
22
23int
24main (int argc, char **argv)
25{
26    struct lsquic_hash *hash;
27    struct lsquic_hash_elem *el;
28    unsigned n, nelems;
29    struct widget *widgets, *widget;
30
31    hash = lsquic_hash_create();
32
33    if (argc > 1)
34        nelems = atoi(argv[1]);
35    else
36        nelems = 1000000;
37
38    widgets = calloc(nelems, sizeof(widgets[0]));
39
40    for (n = 0; n < nelems; ++n)
41    {
42        widget = &widgets[n];
43        widget->key = n;    /* This will be used for verification later the test */
44        sprintf(widget->data, "%lu", widget->key);
45        el = lsquic_hash_find(hash, &widget->key, sizeof(widget->key));
46        assert(!el);
47        el = lsquic_hash_insert(hash, &widget->key, sizeof(widget->key), widget, &widget->hash_el);
48        assert(el);
49    }
50
51    assert(nelems == lsquic_hash_count(hash));
52
53    for (n = 0, el = lsquic_hash_first(hash); el; ++n, el = lsquic_hash_next(hash))
54    {
55        widget = lsquic_hashelem_getdata(el);
56        assert(widget >= widgets);
57        assert(widget < widgets + nelems);
58    }
59    assert(n == nelems);
60
61    for (n = 0; n < nelems; ++n)
62    {
63        unsigned long key = n;
64        el = lsquic_hash_find(hash, &key, sizeof(key));
65        assert(el);
66        widget = lsquic_hashelem_getdata(el);
67        assert(widget->key == key);
68        lsquic_hash_erase(hash, el);
69        el = lsquic_hash_find(hash, &key, sizeof(key));
70        assert(!el);
71    }
72
73    assert(0 == lsquic_hash_count(hash));
74
75    lsquic_hash_destroy(hash);
76    free(widgets);
77
78    exit(0);
79}
80