169554a0aa5d98e734a3d9fd8c05012105f7200c
[people/ms/libloc.git] / src / test-stringpool.c
1 /*
2 libloc - A library to determine the location of someone on the Internet
3
4 Copyright (C) 2017 IPFire Development Team <info@ipfire.org>
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15 */
16
17 #include <stdio.h>
18 #include <stddef.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <fcntl.h>
22 #include <ctype.h>
23 #include <errno.h>
24 #include <unistd.h>
25 #include <time.h>
26
27 #include <loc/libloc.h>
28 #include "stringpool.h"
29
30 static const char* characters = "012345789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
31
32 static char* random_string(size_t size) {
33 char* string = malloc(size + 1);
34
35 char* p = string;
36 for (unsigned int i = 0; i < size; i++) {
37 *p++ = characters[rand() % strlen(characters)];
38 }
39 *p = '\0';
40
41 return string;
42 }
43
44 int main(int argc, char** argv) {
45 // Initialize the RNG
46 time_t now = time(NULL);
47 srand(now);
48
49 int err;
50
51 struct loc_ctx* ctx;
52 err = loc_new(&ctx);
53 if (err < 0)
54 exit(EXIT_FAILURE);
55
56 // Create the stringpool
57 struct loc_stringpool* pool;
58 err = loc_stringpool_new(ctx, &pool, 10002 * 4);
59 if (err < 0)
60 exit(EXIT_FAILURE);
61
62 // Append a string
63 off_t pos = loc_stringpool_add(pool, "ABC");
64 if (pos < 0) {
65 fprintf(stderr, "Could not add string: %s\n", strerror(-pos));
66 exit(EXIT_FAILURE);
67 }
68
69 printf("Added string at %jd\n", pos);
70
71 // Must start at first byte
72 if (pos != 0) {
73 fprintf(stderr, "First string didn't start at the first byte\n");
74 exit(EXIT_FAILURE);
75 }
76
77 // Append the same string again
78 pos = loc_stringpool_add(pool, "ABC");
79 if (pos != 0) {
80 fprintf(stderr, "Same string was added at a different position again\n");
81 exit(EXIT_FAILURE);
82 }
83
84 // Append another string
85 pos = loc_stringpool_add(pool, "DEF");
86 if (pos == 0) {
87 fprintf(stderr, "Second string was added at the first address\n");
88 exit(EXIT_FAILURE);
89 }
90
91 // Add 10000 random strings
92 for (unsigned int i = 0; i < 10000; i++) {
93 char* string = random_string(3);
94
95 pos = loc_stringpool_add(pool, string);
96 free(string);
97
98 if (pos < 0) {
99 fprintf(stderr, "Could not add string %d: %s\n", i, strerror(-pos));
100 exit(EXIT_FAILURE);
101 }
102 }
103
104 // Dump pool
105 loc_stringpool_dump(pool);
106
107 loc_stringpool_unref(pool);
108 loc_unref(ctx);
109
110 return EXIT_SUCCESS;
111 }