File: example.c

package info (click to toggle)
sparsehash 2.0.3-2
  • links: PTS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 1,756 kB
  • sloc: cpp: 6,600; sh: 3,960; ansic: 1,317; makefile: 240
file content (55 lines) | stat: -rw-r--r-- 1,378 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <sparsehash/internal/sparseconfig.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "libchash.h"

static void TestInsert() {
  struct HashTable* ht;
  HTItem* bck;

  ht = AllocateHashTable(1, 0);    /* value is 1 byte, 0: don't copy keys */

  HashInsert(ht, PTR_KEY(ht, "January"), 31);  /* 0: don't overwrite old val */
  bck = HashInsert(ht, PTR_KEY(ht, "February"), 28);
  bck = HashInsert(ht, PTR_KEY(ht, "March"), 31);

  bck = HashFind(ht, PTR_KEY(ht, "February"));
  assert(bck);
  assert(bck->data == 28);

  FreeHashTable(ht);
}

static void TestFindOrInsert() {
  struct HashTable* ht;
  int i;
  int iterations = 1000000;
  int range = 30;         /* random number between 1 and 30 */

  ht = AllocateHashTable(4, 0);    /* value is 4 bytes, 0: don't copy keys */

  /* We'll test how good rand() is as a random number generator */
  for (i = 0; i < iterations; ++i) {
    int key = rand() % range;
    HTItem* bck = HashFindOrInsert(ht, key, 0);     /* initialize to 0 */
    bck->data++;                   /* found one more of them */
  }

  for (i = 0; i < range; ++i) {
    HTItem* bck = HashFind(ht, i);
    if (bck) {
      printf("%3d: %d\n", bck->key, bck->data);
    } else {
      printf("%3d: 0\n", i);
    }
  }

  FreeHashTable(ht);
}

int main(int argc, char** argv) {
  TestInsert();
  TestFindOrInsert();
  return 0;
}