xref: /openbsd/lib/libcurses/tinfo/comp_hash.c (revision 7b36286a)
1 /*	$OpenBSD: comp_hash.c,v 1.7 2007/03/20 03:40:06 tedu Exp $	*/
2 
3 /****************************************************************************
4  * Copyright (c) 1998 Free Software Foundation, Inc.                        *
5  *                                                                          *
6  * Permission is hereby granted, free of charge, to any person obtaining a  *
7  * copy of this software and associated documentation files (the            *
8  * "Software"), to deal in the Software without restriction, including      *
9  * without limitation the rights to use, copy, modify, merge, publish,      *
10  * distribute, distribute with modifications, sublicense, and/or sell       *
11  * copies of the Software, and to permit persons to whom the Software is    *
12  * furnished to do so, subject to the following conditions:                 *
13  *                                                                          *
14  * The above copyright notice and this permission notice shall be included  *
15  * in all copies or substantial portions of the Software.                   *
16  *                                                                          *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
18  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
20  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
21  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
22  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
23  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
24  *                                                                          *
25  * Except as contained in this notice, the name(s) of the above copyright   *
26  * holders shall not be used in advertising or otherwise to promote the     *
27  * sale, use or other dealings in this Software without prior written       *
28  * authorization.                                                           *
29  ****************************************************************************/
30 
31 /****************************************************************************
32  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
33  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
34  ****************************************************************************/
35 
36 
37 /*
38  *	comp_hash.c --- Routines to deal with the hashtable of capability
39  *			names.
40  *
41  */
42 
43 #include <curses.priv.h>
44 
45 #include <tic.h>
46 #include <hashsize.h>
47 
48 #ifdef MAIN_PROGRAM
49 #include <ctype.h>
50 #undef  DEBUG
51 #define DEBUG(level, params) /*nothing*/
52 #endif
53 
54 MODULE_ID("$From: comp_hash.c,v 1.21 1999/06/26 21:25:11 tom Exp $")
55 
56 static  int hash_function(const char *);
57 
58 /*
59  *	_nc_make_hash_table()
60  *
61  *	Takes the entries in table[] and hashes them into hash_table[]
62  *	by name.  There are CAPTABSIZE entries in table[] and HASHTABSIZE
63  *	slots in hash_table[].
64  *
65  */
66 
67 #ifdef MAIN_PROGRAM
68 
69 #undef MODULE_ID
70 #define MODULE_ID(id) /*nothing*/
71 #include <tinfo/doalloc.c>
72 
73 static void _nc_make_hash_table(struct name_table_entry *table,
74 		     struct name_table_entry **hash_table)
75 {
76 int	i;
77 int	hashvalue;
78 int	collisions = 0;
79 
80 	for (i = 0; i < CAPTABSIZE; i++) {
81 	    hashvalue = hash_function(table[i].nte_name);
82 
83 	    if (hash_table[hashvalue] != (struct name_table_entry *) 0)
84 		collisions++;
85 
86 	    if (hash_table[hashvalue] != 0)
87 		table[i].nte_link = (short)(hash_table[hashvalue] - table);
88 	    hash_table[hashvalue] = &table[i];
89 	}
90 
91 	DEBUG(4, ("Hash table complete: %d collisions out of %d entries", collisions, CAPTABSIZE));
92 }
93 #endif
94 
95 
96 /*
97  *	int hash_function(string)
98  *
99  *	Computes the hashing function on the given string.
100  *
101  *	The current hash function is the sum of each consectutive pair
102  *	of characters, taken as two-byte integers, mod Hashtabsize.
103  *
104  */
105 
106 static
107 int
108 hash_function(const char *string)
109 {
110 long	sum = 0;
111 
112 	DEBUG(9, ("hashing %s", string));
113 	while (*string) {
114 	    sum += (long)(*string + (*(string + 1) << 8));
115 	    string++;
116 	}
117 
118 	DEBUG(9, ("sum is %ld", sum));
119 	return (int)(sum % HASHTABSIZE);
120 }
121 
122 
123 /*
124  *	struct name_table_entry *
125  *	find_entry(string)
126  *
127  *	Finds the entry for the given string in the hash table if present.
128  *	Returns a pointer to the entry in the table or 0 if not found.
129  *
130  */
131 
132 #ifndef MAIN_PROGRAM
133 struct name_table_entry const *
134 _nc_find_entry(const char *string, const struct name_table_entry *const *hash_table)
135 {
136 int	hashvalue;
137 struct name_table_entry	const *ptr;
138 
139 	hashvalue = hash_function(string);
140 
141 	if ((ptr = hash_table[hashvalue]) != 0) {
142 		while (strcmp(ptr->nte_name, string) != 0) {
143 			if (ptr->nte_link < 0)
144 				return 0;
145 			ptr = ptr->nte_link + hash_table[HASHTABSIZE];
146 		}
147 	}
148 
149 	return (ptr);
150 }
151 
152 /*
153  *	struct name_table_entry *
154  *	find_type_entry(string, type, table)
155  *
156  *	Finds the first entry for the given name with the given type in the
157  *	given table if present (as distinct from find_entry, which finds the
158  *	the last entry regardless of type).  You can use this if you detect
159  *	a name clash.  It's slower, though.  Returns a pointer to the entry
160  *	in the table or 0 if not found.
161  */
162 
163 struct name_table_entry const *
164 _nc_find_type_entry(const char *string,
165 		    int type,
166 		    const struct name_table_entry *table)
167 {
168 struct name_table_entry	const *ptr;
169 
170 	for (ptr = table; ptr < table + CAPTABSIZE; ptr++) {
171 	    if (ptr->nte_type == type && strcmp(string, ptr->nte_name) == 0)
172 		return(ptr);
173 	}
174 
175 	return ((struct name_table_entry *)NULL);
176 }
177 #endif
178 
179 #ifdef MAIN_PROGRAM
180 /*
181  * This filter reads from standard input a list of tab-delimited columns,
182  * (e.g., from Caps.filtered) computes the hash-value of a specified column and
183  * writes the hashed tables to standard output.
184  *
185  * By compiling the hash table at build time, we're able to make the entire
186  * set of terminfo and termcap tables readonly (and also provide some runtime
187  * performance enhancement).
188  */
189 
190 #define MAX_COLUMNS BUFSIZ	/* this _has_ to be worst-case */
191 
192 static char **parse_columns(char *buffer)
193 {
194 	static char **list;
195 
196 	int col = 0;
197 
198 	if (list == 0 && (list = typeCalloc(char *, MAX_COLUMNS)) == 0)
199 		return(0);
200 
201 	if (*buffer != '#') {
202 		while (*buffer != '\0') {
203 			char *s;
204 			for (s = buffer; (*s != '\0') && !isspace(*s); s++)
205 				/*EMPTY*/;
206 			if (s != buffer) {
207 				char mark = *s;
208 				*s = '\0';
209 				if ((s - buffer) > 1
210 				 && (*buffer == '"')
211 				 && (s[-1] == '"')) {	/* strip the quotes */
212 					buffer++;
213 					s[-1] = '\0';
214 				}
215 				list[col] = buffer;
216 				col++;
217 				if (mark == '\0')
218 					break;
219 				while (isspace(*++s))
220 					/*EMPTY*/;
221 				buffer = s;
222 			} else
223 				break;
224 		}
225 	}
226 	return col ? list : 0;
227 }
228 
229 int main(int argc, char **argv)
230 {
231 	struct name_table_entry *name_table = typeCalloc(struct name_table_entry, CAPTABSIZE);
232 	struct name_table_entry **hash_table = typeCalloc(struct name_table_entry *, HASHTABSIZE);
233 	const char *root_name = "";
234 	int  column = 0;
235 	int  n;
236 	char buffer[BUFSIZ];
237 
238 	static const char * typenames[] = { "BOOLEAN", "NUMBER", "STRING" };
239 
240 	short BoolCount = 0;
241 	short NumCount  = 0;
242 	short StrCount  = 0;
243 
244 	/* The first argument is the column-number (starting with 0).
245 	 * The second is the root name of the tables to generate.
246 	 */
247 	if (argc <= 2
248 	 || (column = atoi(argv[1])) <= 0
249 	 || (column >= MAX_COLUMNS)
250 	 || *(root_name = argv[2]) == 0) {
251 		fprintf(stderr, "usage: make_hash column root_name\n");
252 		exit(EXIT_FAILURE);
253 	}
254 
255 	/*
256 	 * Read the table into our arrays.
257 	 */
258 	for (n = 0; (n < CAPTABSIZE) && fgets(buffer, BUFSIZ, stdin); ) {
259 		char **list, *nlp = strchr(buffer, '\n');
260 		if (nlp)
261 		    *nlp = '\0';
262 		list = parse_columns(buffer);
263 		if (list == 0)	/* blank or comment */
264 		    continue;
265 		name_table[n].nte_link = -1;	/* end-of-hash */
266 		name_table[n].nte_name = strdup(list[column]);
267 		if (!strcmp(list[2], "bool")) {
268 			name_table[n].nte_type  = BOOLEAN;
269 			name_table[n].nte_index = BoolCount++;
270 		} else if (!strcmp(list[2], "num")) {
271 			name_table[n].nte_type  = NUMBER;
272 			name_table[n].nte_index = NumCount++;
273 		} else if (!strcmp(list[2], "str")) {
274 			name_table[n].nte_type  = STRING;
275 			name_table[n].nte_index = StrCount++;
276 		} else {
277 			fprintf(stderr, "Unknown type: %s\n", list[2]);
278 			exit(EXIT_FAILURE);
279 		}
280 		n++;
281 	}
282 	_nc_make_hash_table(name_table, hash_table);
283 
284 	/*
285 	 * Write the compiled tables to standard output
286 	 */
287 	printf("static struct name_table_entry const _nc_%s_table[] =\n",
288 		root_name);
289 	printf("{\n");
290 	for (n = 0; n < CAPTABSIZE; n++) {
291 		snprintf(buffer, sizeof(buffer), "\"%s\"",
292 			 name_table[n].nte_name);
293 		printf("\t{ %15s,\t%10s,\t%3d, %3d }%c\n",
294 			buffer,
295 			typenames[name_table[n].nte_type],
296 			name_table[n].nte_index,
297 			name_table[n].nte_link,
298 			n < CAPTABSIZE - 1 ? ',' : ' ');
299 	}
300 	printf("};\n\n");
301 
302 	printf("const struct name_table_entry * const _nc_%s_hash_table[%d] =\n",
303 		root_name,
304 		HASHTABSIZE+1);
305 	printf("{\n");
306 	for (n = 0; n < HASHTABSIZE; n++) {
307 		if (hash_table[n] != 0) {
308 			snprintf(buffer, sizeof(buffer), "_nc_%s_table + %3ld",
309 				 root_name,
310 				(long) (hash_table[n] - name_table));
311 		} else {
312 			buffer[0] = '0';
313 			buffer[1] = '\0';
314 		}
315 		printf("\t%s,\n", buffer);
316 	}
317 	printf("\t_nc_%s_table\t/* base-of-table */\n", root_name);
318 	printf("};\n\n");
319 
320 	printf("#if (BOOLCOUNT!=%d)||(NUMCOUNT!=%d)||(STRCOUNT!=%d)\n",
321 		BoolCount, NumCount, StrCount);
322 	printf("#error\t--> term.h and comp_captab.c disagree about the <--\n");
323 	printf("#error\t--> numbers of booleans, numbers and/or strings <--\n");
324 	printf("#endif\n\n");
325 
326 	return EXIT_SUCCESS;
327 }
328 #endif
329