3 * $Id: sym.c,v 1.5 1999/05/13 22:48:37 mdw Exp $
5 * Symbol table management
7 * (c) 1998 Straylight/Edgeware
10 /*----- Licensing notice --------------------------------------------------*
12 * This file is part of the mLib utilities library.
14 * mLib is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU Library General Public License as
16 * published by the Free Software Foundation; either version 2 of the
17 * License, or (at your option) any later version.
19 * mLib is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Library General Public License for more details.
24 * You should have received a copy of the GNU Library General Public
25 * License along with mLib; if not, write to the Free
26 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
30 /*----- Revision history --------------------------------------------------*
33 * Revision 1.5 1999/05/13 22:48:37 mdw
34 * Twiddle the extension threshold. Change `-ise' to `-ize' throughout.
36 * Revision 1.4 1999/05/06 19:51:35 mdw
37 * Reformatted the LGPL notice a little bit.
39 * Revision 1.3 1999/05/05 18:50:31 mdw
40 * Change licensing conditions to LGPL.
42 * Revision 1.2 1998/11/26 19:27:33 mdw
43 * Move SYM_NAME into the header file. Fix bugs.
45 * Revision 1.1.1.1 1998/06/17 23:44:42 mdw
46 * Initial version of mLib
50 /*----- Header files ------------------------------------------------------*/
52 /* --- ANSI headers --- */
58 /* --- Local headers --- */
67 /*----- Tuning parameters -------------------------------------------------*/
69 /* --- Initial hash table size --- *
71 * This is the initial @mask@ value. It must be of the form %$2^n - 1$%,
72 * so that it can be used to mask of the bottom bits of a hash value.
75 #define SYM_INITSZ 255 /* Size of a new hash table */
77 /* --- Maximum load factor --- *
79 * This parameter controls how much the table has to be loaded before the
80 * table is extended. The number of elements %$n$%, the number of bins %$b$%
81 * and the limit %$l$% satisfy the relation %$n < bl$%; if a new item is
82 * added to the table and this relation is found to be false, the table is
86 #define SYM_LIMIT(n) ((n) * 4) /* Load factor for growing table */
88 /*----- Main code ---------------------------------------------------------*/
90 /* --- @sym_createTable@ --- *
92 * Arguments: @sym_table *t@ = symbol table to initialize
96 * Use: Initializes the given symbol table. Raises @EXC_NOMEM@ if
97 * there isn't enough memory.
100 void sym_createTable(sym_table *t)
104 TRACK_CTX("symbol table creation");
107 t->mask = SYM_INITSZ;
108 t->c = SYM_LIMIT(SYM_INITSZ);
109 t->a = xmalloc((t->mask + 1) * sizeof(sym_base *));
111 for (i = 0; i < SYM_INITSZ + 1; i++)
117 /* --- @sym_destroyTable@ --- *
119 * Arguments: @sym_table *t@ = pointer to symbol table in question
123 * Use: Destroys a symbol table, freeing all the memory it used to
127 void sym_destroyTable(sym_table *t)
132 TRACK_CTX("symbol table deletion");
135 for (i = 0; i <= t->mask; i++) {
139 if (p->len > SYM_BUFSZ)
140 sub_free(p->name.p, p->len);
150 /* --- @sym_find@ --- *
152 * Arguments: @sym_table *t@ = pointer to symbol table in question
153 * @const char *n@ = pointer to symbol table to look up
154 * @long l@ = length of the name string or negative to measure
155 * @size_t sz@ = size of desired symbol object, or zero
156 * @unsigned *f@ = pointer to a flag, or null.
158 * Returns: The address of a @sym_base@ structure, or null if not found
161 * Use: Looks up a symbol in a given symbol table. The name is
162 * passed by the address of its first character. The length
163 * may be given, in which case the name may contain arbitrary
164 * binary data, or it may be given as a negative number, in
165 * which case the length of the name is calculated as
168 * The return value is the address of a pointer to a @sym_base@
169 * block (which may have other things on the end, as above). If
170 * the symbol could be found, the return value points to the
171 * symbol block. If the symbol wasn't there, then if @sz@ is
172 * nonzero, a new symbol is created and its address is returned;
173 * otherwise a null pointer is returned. The exception
174 * @EXC_NOMEM@ is raised if the block can't be allocated.
176 * The value of @*f@ indicates whether a new symbol entry was
177 * created: a nonzero value indicates that an old value was
181 void *sym_find(sym_table *t, const char *n, long l, size_t sz, unsigned *f)
183 unsigned long hash; /* Hash value for user's name */
184 size_t len = l < 0 ? strlen(n) + 1 : l; /* Find length of user's name */
185 sym_base *bin; /* Bin containing our item */
186 sym_base *p, *q; /* Pointer wandering through list */
188 /* --- Find the correct bin --- */
190 CRC32(hash, 0, n, len); /* Find hash value for this name */
191 bin = p = (sym_base *)(t->a + (hash & t->mask));
193 /* --- Search the bin list --- */
196 if (hash == p->next->hash && /* Check full hash values first */
197 len == p->next->len && /* Then compare string lengths */
198 !memcmp(n, SYM_NAME(p->next), len)) /* And finally compare names */
200 /* --- Found a match --- *
202 * As a minor, and probably pointless, tweak, move the item to the
203 * front of its bin list.
206 q = p->next; /* Find the actual symbol block */
207 p->next = q->next; /* Extract block from bin list */
208 q->next = bin->next; /* Set up symbol's next pointer */
209 bin->next = q; /* And reinsert the block */
211 /* --- Return the block --- */
213 if (f) *f = 1; /* Didn't fail to find the item */
214 return (q); /* And return the block */
217 p = p->next; /* Move onto the next item */
220 /* --- Couldn't find the item there --- */
222 if (f) *f = 0; /* Failed to find the block */
223 if (!sz) return (0); /* Return zero if not creating */
225 /* --- Create a new symbol block and initialize it --- */
228 TRACK_CTX("new symbol creation");
231 p = xmalloc(sz); /* Create a new symbol block */
232 p->next = bin->next; /* Set up the next pointer */
233 p->hash = hash; /* Set up the hash value too */
234 p->len = len; /* And set up the string length */
235 if (len <= SYM_BUFSZ)
236 memcpy(p->name.b, n, len); /* And copy the string over */
239 p->name.p = sub_alloc(len); /* Allocate a block for the name */
240 memcpy(p->name.p, n, len); /* And copy the string over */
251 bin->next = p; /* Put the pointer into the bin */
253 /* --- Consider growing the array --- */
258 unsigned long m = t->mask + 1; /* Next set bit in has word */
259 sym_base *p, *q, *r; /* More useful pointers */
260 size_t i, lim; /* Loop counter and limit */
262 TRACK_CTX("symbol table extension");
265 /* --- Update values in the anchor block --- */
268 t->a = xrealloc(t->a, (t->mask + 1) * 2 * sizeof(sym_base *));
269 } CATCH switch (exc_type) {
278 t->c = SYM_LIMIT(t->mask + 1); /* Set load value */
279 t->mask = (t->mask + 1) * 2 - 1; /* Set the new mask value */
281 /* --- Now wander through the table rehashing things --- *
283 * This loop is very careful to avoid problems with aliasing. The items
284 * are dealt with from the end backwards to avoid overwriting bins before
285 * they've been processed.
288 lim = (t->mask + 1) >> 1;
289 for (i = 0; i < lim; i++) {
291 /* --- Some initialisation --- */
293 r = t->a[i]; /* Find the list we're dissecting */
294 p = (sym_base *)(t->a + i); /* Find bit-clear list */
295 q = (sym_base *)(t->a + i + lim); /* And the bit-set lsit */
297 /* --- Now go through the @r@ list --- */
300 if (r->hash & m) /* Is the next bit set? */
301 q = q->next = r; /* Yes, so fit up previous link */
303 p = p->next = r; /* No, so fit up previous link */
304 r = r->next; /* Move onto the next item */
306 p->next = q->next = 0; /* Null terminate the new lists */
312 /* --- Finished that, so return the new symbol block --- */
317 /* --- @sym_remove@ --- *
319 * Arguments: @sym_table *i@ = pointer to a symbol table object
320 * @void *b@ = pointer to symbol table entry
324 * Use: Removes the object from the symbol table. The space occupied
325 * by the object and its name is freed; anything else attached
326 * to the entry should already be gone by this point.
329 void sym_remove(sym_table *t, void *b)
331 /* --- A quick comment --- *
333 * Since the @sym_base@ block contains the hash, finding the element in the
334 * bin list is really quick -- it's not worth bothering with things like
335 * doubly linked lists.
339 sym_base *bin = (sym_base *)(t->a + (p->hash & t->mask));
341 /* --- Find the item in the bin list --- */
351 /* --- Now just remove the item from the list and free it --- *
353 * Oh, and bump the load counter.
357 if (p->len > SYM_BUFSZ)
358 sub_free(p->name.p, p->len);
363 /* --- @sym_createIter@ --- *
365 * Arguments: @sym_iter *i@ = pointer to an iterator object
366 * @sym_table *t@ = pointer to a symbol table object
370 * Use: Creates a new symbol table iterator which may be used to
371 * iterate through a symbol table.
374 void sym_createIter(sym_iter *i, sym_table *t)
381 /* --- @sym_next@ --- *
383 * Arguments: @sym_iter *i@ = pointer to iterator object
385 * Returns: Pointer to the next symbol found, or null when finished.
387 * Use: Returns the next symbol from the table. Symbols are not
388 * returned in any particular order.
391 void *sym_next(sym_iter *i)
395 /* --- Find the next item --- */
398 if (i->i > i->t->mask)
400 i->n = i->t->a[i->i++];
403 /* --- Update the iterator block --- */
413 /*----- Symbol table test code --------------------------------------------*/
420 typedef struct sym_word {
426 /* --- What it does --- *
428 * Reads the file /usr/dict/words (change to some other file full of
429 * interesting and appropriate bits of text to taste) into a big buffer and
430 * picks apart into lines. Then picks lines at random and enters them into
436 char *buff, *p, *lim;
445 /* --- Initialize for reading the file --- */
448 buff = xmalloc(sz + 1);
452 if ((fp = fopen("/usr/dict/words", "r")) == 0)
453 fprintf(stderr, "buggered ;-( (%s)\n", strerror(errno));
455 /* --- Read buffers of text --- *
457 * Read a buffer. If more to come, double the buffer size and try again.
458 * This is the method I recommended to comp.lang.c, so I may as well try
463 i = fread(buff + done, 1, sz - done, fp);
468 buff = xrealloc(buff, sz + 1);
471 /* --- Count the lines --- */
476 for (p = buff; p < lim; p++)
477 if (*p == '\n') sz++;
479 /* --- Build a table of line starts --- */
481 line = xmalloc(sz * sizeof(char *));
484 for (p = buff; p < lim; p++)
485 if (*p == '\n') *p = 0, line[i++] = p + 1;
488 /* --- Build a table of lines --- *
490 * This reverses the mapping which the symbol table performs, so that its
491 * accuracy can be tested.
494 flag = xmalloc(sz * sizeof(sym_word *));
495 for (i = 0; i < sz; i++)
499 sym_createTable(&tbl);
502 i = (unsigned)rand() % sz;
509 printf("find `%s'\n", line[i]);
510 if ((rand() & 1023) == 0) {
511 putchar('.'); fflush(stdout);
514 w = sym_find(&tbl, line[i], -1, 0, 0);
516 printf("*** error: find `%s' gave %p not %p\n",
517 line[i], (void *)w, (void *)flag[i]);
518 else if (w && w->i != i)
519 printf("*** error: find sym for `%s' gives index %i not %i\n",
527 printf("create `%s'\n", line[i]);
528 if ((rand() & 1023) == 0) {
529 putchar('+'); fflush(stdout);
532 w = sym_find(&tbl, line[i], -1, sizeof(sym_word), &f);
536 printf("*** error: create `%s' gave %p not %p\n",
537 line[i], (void *)w, (void *)flag[i]);
538 else if (w && w->i != i)
539 printf("*** error: create sym for `%s' gives index %i not %i\n",
545 printf("*** error: create `%s' gave new block, should be %p\n",
546 line[i], (void *)flag[i]);
562 v = (rand() % entries) == 0;
565 printf("\niterated %i entries\n", entries);
570 ntbl = xmalloc(sz * sizeof(sym_word *));
571 memcpy(ntbl, flag, sz * sizeof(sym_word *));
572 sym_createIter(&it, &tbl);
574 while ((w = sym_next(&it)) != 0) {
576 printf("*** error: iterate returned duff item %i\n", w->i);
581 for (i = 0; i < sz; i++)
582 if (ntbl[i]) printf("*** error: iterate didn't return item %i\n",
589 int v = rand() & 255 ? 0 : 1;
594 for (i = 0; i <= tbl.mask; i++) {
595 if (!tbl.a[i]) continue;
596 if (v) printf(" %i: ", i);
599 if ((b->hash & tbl.mask) != i)
600 printf("*** error: bad hash value found");
601 if (v) printf("`%s'(%08lx:%lu) ",
602 line[((sym_word *)b)->i],
607 if (v) putchar('\n');
613 printf("remove `%s'\n", SYM_NAME(&flag[i]->base));
614 if ((rand() & 1023) == 0) {
615 putchar('-'); fflush(stdout);
617 sym_remove(&tbl, flag[i]);
631 /*----- That's all, folks -------------------------------------------------*/