~q3cpma/misc-tools

ref: 0695c6188d0f70c89d8e1757f2463b2e3869a60a misc-tools/genhtab.c -rw-r--r-- 8.9 KiB
0695c618q3cpma htmldecode: move to root, use genhtab instead of lex 1 year, 4 days ago
                                                                                
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#include <getopt.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>

#include "array.h"
#include "misc.h"


struct htab
{
	uint32_t len;
	struct item
	{
		uint32_t keylen;
		char *key, *tag;
	} **buckets;
};


static uint32_t fnv1a(const uint8_t *k, size_t len)
{
	uint_fast32_t h = 2166136261u;
	for (size_t i = 0; i < len; ++i)
	{
		h = (h ^ k[i]) * 16777619u;
	}
	return h & 0xffffffff;
}

static const struct item * bucket_search(struct item it, struct item *bucket)
{
	for (size_t i = 0; i < GARRAY_SIZE(bucket); ++i)
	{
		if (it.keylen == bucket[i].keylen && memcmp(it.key, bucket[i].key, it.keylen) == 0)
		{
			return bucket + i;
		}
	}
	return NULL;
}

NORETURN void usage(int exit_status)
{
	printf(
		"NAME\n"
		"    %s - Generate static hash tables\n"
		"\n"
		"SYNOPSIS\n"
		"    %s [OPTIONS]\n"
		"\n"
		"DESCRIPTION\n"
		"    Generate a static hash table as a C99 header and source file pair from a\n"
		"    key/tag list specification.\n"
		"    NOTE: if non ASCII keys are used, they're considered UTF-8 encoded and the\n"
		"    produced table uses C11 u8\"...\" string literals.\n"
		"\n"
		"    That spec is read on stdin as a newline separated list of entries made of\n"
		"    the key (string), one or more delimiter characters (defaults to TAB) and the\n"
		"    tag (type defaults to int).\n"
		"    If the option -l is used, the first line is an exception and contains only\n"
		"    the tag that'll be returned for keys not in the table.\n"
		"\n"
		"    By default, the output files are named htab.c and htab.h. The header\n"
		"    includes a function named htab_search taking a key together with its\n"
		"    length and returning the associated tag.\n"
		"\n"
		"OPTIONS\n"
		"    -h\n"
		"        Print this help message and exit.\n"
		"\n"
		"    -d CHAR\n"
		"        Set the key/tag spec delimiter to CHAR.\n"
		"\n"
		"    -f FUNC_NAME\n"
		"        Change the search function name from htab_search to FUNC_NAME.\n"
		"\n"
		"    -i HEADER\n"
		"        Add HEADER as an additional local #include to the header file. Mainly\n"
		"        to allow the use of a user defined type for tag values.\n"
		"\n"
		"    -l\n"
		"        Literal mode, instead of returning a pointer to the value (mainly for\n"
		"        NULL to be used as special value), returns literals of the chosen type\n"
		"        with the first line of the spec as \"not found\" value.\n"
		"\n"
		"    -m MULT\n"
		"        Use MULT as a floating point multiplier instead of 0.75 when setting the\n"
		"        table bucket number to `mult * key_number`.\n"
		"\n"
		"    -o OUTPUT\n"
		"        Set output to OUTPUT.c and OUTPUT.h instead of htab.c and htab.h.\n"
		"\n"
		"    -t TAG_TYPE\n"
		"        Set the tag type to TAG_TYPE instead of int.\n"
		"\n"
		"    -v\n"
		"        Print the version and exit.\n"
		"\n"
		"    -w\n"
		"        Overwrite any output file without complaining.\n"
		"\n",
		PROG_NAME, PROG_NAME);
	exit(exit_status);
}


int main(int argc, char **argv)
{
	signals_nointerrupt();

	const char *outpath = "htab";
	const char *tagtype = "int";
	const char *searchfun = "htab_search";
	const char **addinclude = NULL;
	GARRAY_INIT(addinclude);
	char delim = '\t';
	float bucketnum_mult = 0.75;
	bool literal_mode = false;
	bool overwrite = false;

	for (int opt; (opt = getopt(argc, argv, "hd:f:i:lm:o:t:vw")) != -1; )
    {
        switch (opt)
		{
			case 'h':
				usage(EXIT_SUCCESS);
				break;

			case 'd':
				delim = optarg[0];
				break;

			case 'f':
				searchfun = optarg;
				break;

			case 'i':
				GARRAY_APPEND(addinclude, optarg);
				break;

			case 'l':
				literal_mode = true;
				break;

			case 'm':
				bucketnum_mult = xstrtof(optarg);
				break;

			case 'o':
				outpath = optarg;
				break;

			case 't':
				tagtype = optarg;
				break;

			case 'v':
                puts(PROG_VERSION);
                exit(EXIT_SUCCESS);

			case 'w':
				overwrite = true;
				break;

			default:
				exit(EXIT_FAILURE);
		}
	}

	size_t dummy = 0;
	char **key, **tag, *line = NULL, *notfoundtag = NULL;
	uint32_t *keylen;
	size_t maxkeylen = 0;
	GARRAY_INIT(key);
	GARRAY_INIT(tag);
	GARRAY_INIT(keylen);

	for (ssize_t read; (read = xgetline(&line, &dummy, stdin)) != -1;
		line = NULL, dummy = 0)
	{
		if (literal_mode && notfoundtag == NULL)
		{
			notfoundtag = line;
			continue;
		}
		char *p = strchr(line, delim);
		if (p == NULL)
		{
			die("%s: malformed entry; no delimiter found", line);
		}
		size_t len = p - line;
		for (; *p == delim; ++p)
		{
			*p = '\0';
		}

		if (len > UINT32_MAX)
		{
			die("Key is too long, length field is an uint32_t");
		}
		if (len > maxkeylen)
		{
			maxkeylen = len;
		}
		GARRAY_APPEND(key, line);
		GARRAY_APPEND(keylen, len);

		if (literal_mode && !strcmp(p, notfoundtag))
		{
			die("%s: invalid tag, already reserved for unknown keys", p);
		}
		GARRAY_APPEND(tag, p);
	}
	free(line);

	if (GARRAY_SIZE(key) == 0)
	{
		die("No keys given");
	}

	struct htab ht;
	ht.len = (uint32_t)1 << (log2_u32(GARRAY_SIZE(key) * bucketnum_mult) + 1);
	ht.buckets = xcalloc(ht.len, sizeof(struct item *));

	for (size_t i = 0; i < GARRAY_SIZE(key); ++i)
	{
		struct item it = {keylen[i], key[i], tag[i]};
		uint32_t h = fnv1a((uint8_t *)key[i], keylen[i]) & (ht.len - 1);
		if (ht.buckets[h])
		{
			if (bucket_search(it, ht.buckets[h]))
			{
				die("%s: duplicate key", key[i]);
			}
		}
		else
		{
			GARRAY_INIT(ht.buckets[h]);
		}
		GARRAY_APPEND(ht.buckets[h], it);
	}


	size_t outpathlen = strlen(outpath);
	char *pathbuf = xmalloc(outpathlen + 2 + 1);
	memcpy(pathbuf, outpath, outpathlen);
	memcpy(pathbuf + outpathlen, ".c", 3);
	if (!overwrite && !access(pathbuf, F_OK))
	{
		die("%s: file already exists", pathbuf);
	}
	FILE *source = xfopen(pathbuf, "w");
	memcpy(pathbuf + outpathlen, ".h", 3);
	if (!overwrite && !access(pathbuf, F_OK))
	{
		die("%s: file already exists", pathbuf);
	}

	fprintf(source,
		"#include <string.h>\n"
		"\n"
		"#include \"%s\"\n"
		"\n"
		"static const struct\n"
		"{\n"
		"    uint32_t len;\n"
		"    uint32_t maxkeylen;\n"
		"    struct bucket\n"
		"    {\n"
		"        uint32_t len;\n"
		"        struct item\n"
		"        {\n"
		"            char *key;\n"
		"            uint32_t keylen;\n"
		"            %s tag;\n"
		"        } *items;\n"
		"    } *buckets;\n"
		"} htab =\n"
		"{\n"
		"    %" PRIu32 ",\n"
		"    %" PRIu32 ",\n"
		"    (struct bucket [])\n"
		"    {\n",
		pathbuf, tagtype, ht.len, (uint32_t)maxkeylen);

	for (size_t i = 0; i < ht.len; ++i)
	{
		if (ht.buckets[i] == NULL)
		{
			fprintf(source,
				"        {\n"
				"            0,\n"
				"            NULL\n"
				"        },\n");
		}
		else
		{
			fprintf(source,
				"        {\n"
				"            %" PRIu32 ",\n"
				"            (struct item [])\n"
				"            {\n",
				(uint32_t)GARRAY_SIZE(ht.buckets[i]));
			for (size_t j = 0; j < GARRAY_SIZE(ht.buckets[i]); ++j)
			{
				fprintf(source,
					"                {");
				fprintf_cstrlit(source,
					ht.buckets[i][j].key, ht.buckets[i][j].keylen);
				fprintf(source,
					", %" PRIu32 ", %s},\n",
					ht.buckets[i][j].keylen, ht.buckets[i][j].tag);
			}
			fprintf(source,
				"            }\n"
				"        },\n");
		}
	}

	fprintf(source,
		"    }\n"
		"};\n"
		"\n");

	char *rettype;
	char *notfoundret;
	if (literal_mode)
	{
		rettype = (char *)tagtype;
		pasprintf(&notfoundret, "(%s)%s", tagtype, notfoundtag);
	}
	else
	{
		pasprintf(&rettype, "const %s *", tagtype);
		notfoundret = "NULL";
	}

	fprintf(source,
		"static uint32_t fnv1a(const uint8_t *key, size_t len)\n"
		"{\n"
		"    uint_fast32_t h = 2166136261u;\n"
		"    for (size_t i = 0; i < len; ++i)\n"
		"    {\n"
		"        h = (h ^ key[i]) * 16777619u;\n"
		"    }\n"
		"    return h & 0xffffffff;\n"
		"}\n"
		"\n"
		"%s %s(const char *key, size_t len)\n"
		"{\n"
		"    if (len > htab.maxkeylen)\n"
		"    {\n"
		"        return %s;\n"
		"    }\n"
		"    uint32_t h = fnv1a((uint8_t *)key, len) & (htab.len - 1);\n"
		"    for (size_t i = 0; i < htab.buckets[h].len; ++i)\n"
		"    {\n"
		"        if (len == htab.buckets[h].items[i].keylen &&\n"
		"            memcmp(key, htab.buckets[h].items[i].key, len) == 0)\n"
		"        {\n"
		"            return %shtab.buckets[h].items[i].tag;\n"
		"        }\n"
		"    }\n"
		"    return %s;\n"
		"}\n",
		rettype, searchfun, notfoundret, (literal_mode ? "" : "&"), notfoundret);
	xfclose(source);

	FILE *header = xfopen(pathbuf, "w");
	fprintf(header,
		"#ifndef GEN_HTAB_GUARD\n"
		"#define GEN_HTAB_GUARD\n"
		"\n"
		"#include <stddef.h>\n"
		"#include <stdint.h>\n"
		"\n");
	for (size_t i = 0; i < GARRAY_SIZE(addinclude); ++i)
	{
		fprintf(header, "#include \"%s\"\n", addinclude[i]);
	}
	fprintf(header,
		"\n"
		"%s %s(const char *key, size_t len);\n"
		"\n"
		"#endif\n",
		rettype, searchfun);
	xfclose(header);

	free(literal_mode ? notfoundret : rettype);
	GARRAY_FREE(addinclude);
	PTR_GARRAY_FREE(key, free);
	GARRAY_FREE(tag);
	GARRAY_FREE(keylen);

	for (size_t i = 0; i < ht.len; ++i)
	{
		GARRAY_FREE(ht.buckets[i]);
	}
	free(ht.buckets);
	free(pathbuf);
}