xref: /titanic_51/usr/src/cmd/mandoc/man_hash.c (revision 4e6f6c8344ddd39ded306346bd0107934d29b982)
1 /*	$Id: man_hash.c,v 1.29 2014/12/01 08:05:52 schwarze Exp $ */
2 /*
3  * Copyright (c) 2008, 2009, 2010 Kristaps Dzonsons <kristaps@bsd.lv>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 #include "config.h"
18 
19 #include <sys/types.h>
20 
21 #include <assert.h>
22 #include <ctype.h>
23 #include <limits.h>
24 #include <string.h>
25 
26 #include "man.h"
27 #include "libman.h"
28 
29 #define	HASH_DEPTH	 6
30 
31 #define	HASH_ROW(x) do { \
32 		if (isupper((unsigned char)(x))) \
33 			(x) -= 65; \
34 		else \
35 			(x) -= 97; \
36 		(x) *= HASH_DEPTH; \
37 	} while (/* CONSTCOND */ 0)
38 
39 /*
40  * Lookup table is indexed first by lower-case first letter (plus one
41  * for the period, which is stored in the last row), then by lower or
42  * uppercase second letter.  Buckets correspond to the index of the
43  * macro (the integer value of the enum stored as a char to save a bit
44  * of space).
45  */
46 static	unsigned char	 table[26 * HASH_DEPTH];
47 
48 
49 /*
50  * XXX - this hash has global scope, so if intended for use as a library
51  * with multiple callers, it will need re-invocation protection.
52  */
53 void
54 man_hash_init(void)
55 {
56 	int		 i, j, x;
57 
58 	memset(table, UCHAR_MAX, sizeof(table));
59 
60 	assert(MAN_MAX < UCHAR_MAX);
61 
62 	for (i = 0; i < (int)MAN_MAX; i++) {
63 		x = man_macronames[i][0];
64 
65 		assert(isalpha((unsigned char)x));
66 
67 		HASH_ROW(x);
68 
69 		for (j = 0; j < HASH_DEPTH; j++)
70 			if (UCHAR_MAX == table[x + j]) {
71 				table[x + j] = (unsigned char)i;
72 				break;
73 			}
74 
75 		assert(j < HASH_DEPTH);
76 	}
77 }
78 
79 enum mant
80 man_hash_find(const char *tmp)
81 {
82 	int		 x, y, i;
83 	enum mant	 tok;
84 
85 	if ('\0' == (x = tmp[0]))
86 		return(MAN_MAX);
87 	if ( ! (isalpha((unsigned char)x)))
88 		return(MAN_MAX);
89 
90 	HASH_ROW(x);
91 
92 	for (i = 0; i < HASH_DEPTH; i++) {
93 		if (UCHAR_MAX == (y = table[x + i]))
94 			return(MAN_MAX);
95 
96 		tok = (enum mant)y;
97 		if (0 == strcmp(tmp, man_macronames[tok]))
98 			return(tok);
99 	}
100 
101 	return(MAN_MAX);
102 }
103