3 * $Id: sym.c,v 1.6 1999/05/26 21:08:31 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.6 1999/05/26 21:08:31 mdw
34 * Rename symbols in line with newer conventions.
36 * Revision 1.5 1999/05/13 22:48:37 mdw
37 * Twiddle the extension threshold. Change `-ise' to `-ize' throughout.
39 * Revision 1.4 1999/05/06 19:51:35 mdw
40 * Reformatted the LGPL notice a little bit.
42 * Revision 1.3 1999/05/05 18:50:31 mdw
43 * Change licensing conditions to LGPL.
45 * Revision 1.2 1998/11/26 19:27:33 mdw
46 * Move SYM_NAME into the header file. Fix bugs.
48 * Revision 1.1.1.1 1998/06/17 23:44:42 mdw
49 * Initial version of mLib
53 /*----- Header files ------------------------------------------------------*/
55 /* --- ANSI headers --- */
61 /* --- Local headers --- */
70 /*----- Tuning parameters -------------------------------------------------*/
72 /* --- Initial hash table size --- *
74 * This is the initial @mask@ value. It must be of the form %$2^n - 1$%,
75 * so that it can be used to mask of the bottom bits of a hash value.
78 #define SYM_INITSZ 255 /* Size of a new hash table */
80 /* --- Maximum load factor --- *
82 * This parameter controls how much the table has to be loaded before the
83 * table is extended. The number of elements %$n$%, the number of bins %$b$%
84 * and the limit %$l$% satisfy the relation %$n < bl$%; if a new item is
85 * added to the table and this relation is found to be false, the table is
89 #define SYM_LIMIT(n) ((n) * 4) /* Load factor for growing table */
91 /*----- Main code ---------------------------------------------------------*/
93 /* --- @sym_create@ --- *
95 * Arguments: @sym_table *t@ = symbol table to initialize
99 * Use: Initializes the given symbol table. Raises @EXC_NOMEM@ if
100 * there isn't enough memory.
103 void sym_create(sym_table
*t
)
107 TRACK_CTX("symbol table creation");
110 t
->mask
= SYM_INITSZ
;
111 t
->c
= SYM_LIMIT(SYM_INITSZ
);
112 t
->a
= xmalloc((t
->mask
+ 1) * sizeof(sym_base
*));
114 for (i
= 0; i
< SYM_INITSZ
+ 1; i
++)
120 /* --- @sym_destroy@ --- *
122 * Arguments: @sym_table *t@ = pointer to symbol table in question
126 * Use: Destroys a symbol table, freeing all the memory it used to
130 void sym_destroy(sym_table
*t
)
135 TRACK_CTX("symbol table deletion");
138 for (i
= 0; i
<= t
->mask
; i
++) {
142 if (p
->len
> SYM_BUFSZ
)
143 sub_free(p
->name
.p
, p
->len
);
153 /* --- @sym_find@ --- *
155 * Arguments: @sym_table *t@ = pointer to symbol table in question
156 * @const char *n@ = pointer to symbol table to look up
157 * @long l@ = length of the name string or negative to measure
158 * @size_t sz@ = size of desired symbol object, or zero
159 * @unsigned *f@ = pointer to a flag, or null.
161 * Returns: The address of a @sym_base@ structure, or null if not found
164 * Use: Looks up a symbol in a given symbol table. The name is
165 * passed by the address of its first character. The length
166 * may be given, in which case the name may contain arbitrary
167 * binary data, or it may be given as a negative number, in
168 * which case the length of the name is calculated as
171 * The return value is the address of a pointer to a @sym_base@
172 * block (which may have other things on the end, as above). If
173 * the symbol could be found, the return value points to the
174 * symbol block. If the symbol wasn't there, then if @sz@ is
175 * nonzero, a new symbol is created and its address is returned;
176 * otherwise a null pointer is returned. The exception
177 * @EXC_NOMEM@ is raised if the block can't be allocated.
179 * The value of @*f@ indicates whether a new symbol entry was
180 * created: a nonzero value indicates that an old value was
184 void *sym_find(sym_table
*t
, const char *n
, long l
, size_t sz
, unsigned *f
)
186 unsigned long hash
; /* Hash value for user's name */
187 size_t len
= l
< 0 ?
strlen(n
) + 1 : l
; /* Find length of user's name */
188 sym_base
*bin
; /* Bin containing our item */
189 sym_base
*p
, *q
; /* Pointer wandering through list */
191 /* --- Find the correct bin --- */
193 CRC32(hash
, 0, n
, len
); /* Find hash value for this name */
194 bin
= p
= (sym_base
*)(t
->a
+ (hash
& t
->mask
));
196 /* --- Search the bin list --- */
199 if (hash
== p
->next
->hash
&& /* Check full hash values first */
200 len
== p
->next
->len
&& /* Then compare string lengths */
201 !memcmp(n
, SYM_NAME(p
->next
), len
)) /* And finally compare names */
203 /* --- Found a match --- *
205 * As a minor, and probably pointless, tweak, move the item to the
206 * front of its bin list.
209 q
= p
->next
; /* Find the actual symbol block */
210 p
->next
= q
->next
; /* Extract block from bin list */
211 q
->next
= bin
->next
; /* Set up symbol's next pointer */
212 bin
->next
= q
; /* And reinsert the block */
214 /* --- Return the block --- */
216 if (f
) *f
= 1; /* Didn't fail to find the item */
217 return (q
); /* And return the block */
220 p
= p
->next
; /* Move onto the next item */
223 /* --- Couldn't find the item there --- */
225 if (f
) *f
= 0; /* Failed to find the block */
226 if (!sz
) return (0); /* Return zero if not creating */
228 /* --- Create a new symbol block and initialize it --- */
231 TRACK_CTX("new symbol creation");
234 p
= xmalloc(sz
); /* Create a new symbol block */
235 p
->next
= bin
->next
; /* Set up the next pointer */
236 p
->hash
= hash
; /* Set up the hash value too */
237 p
->len
= len
; /* And set up the string length */
238 if (len
<= SYM_BUFSZ
)
239 memcpy(p
->name
.b
, n
, len
); /* And copy the string over */
242 p
->name
.p
= sub_alloc(len
); /* Allocate a block for the name */
243 memcpy(p
->name
.p
, n
, len
); /* And copy the string over */
254 bin
->next
= p
; /* Put the pointer into the bin */
256 /* --- Consider growing the array --- */
261 unsigned long m
= t
->mask
+ 1; /* Next set bit in has word */
262 sym_base
*p
, *q
, *r
; /* More useful pointers */
263 size_t i
, lim
; /* Loop counter and limit */
265 TRACK_CTX("symbol table extension");
268 /* --- Update values in the anchor block --- */
271 t
->a
= xrealloc(t
->a
, (t
->mask
+ 1) * 2 * sizeof(sym_base
*));
272 } CATCH
switch (exc_type
) {
281 t
->c
= SYM_LIMIT(t
->mask
+ 1); /* Set load value */
282 t
->mask
= (t
->mask
+ 1) * 2 - 1; /* Set the new mask value */
284 /* --- Now wander through the table rehashing things --- *
286 * This loop is very careful to avoid problems with aliasing. The items
287 * are dealt with from the end backwards to avoid overwriting bins before
288 * they've been processed.
291 lim
= (t
->mask
+ 1) >> 1;
292 for (i
= 0; i
< lim
; i
++) {
294 /* --- Some initialisation --- */
296 r
= t
->a
[i
]; /* Find the list we're dissecting */
297 p
= (sym_base
*)(t
->a
+ i
); /* Find bit-clear list */
298 q
= (sym_base
*)(t
->a
+ i
+ lim
); /* And the bit-set lsit */
300 /* --- Now go through the @r@ list --- */
303 if (r
->hash
& m
) /* Is the next bit set? */
304 q
= q
->next
= r
; /* Yes, so fit up previous link */
306 p
= p
->next
= r
; /* No, so fit up previous link */
307 r
= r
->next
; /* Move onto the next item */
309 p
->next
= q
->next
= 0; /* Null terminate the new lists */
315 /* --- Finished that, so return the new symbol block --- */
320 /* --- @sym_remove@ --- *
322 * Arguments: @sym_table *i@ = pointer to a symbol table object
323 * @void *b@ = pointer to symbol table entry
327 * Use: Removes the object from the symbol table. The space occupied
328 * by the object and its name is freed; anything else attached
329 * to the entry should already be gone by this point.
332 void sym_remove(sym_table
*t
, void *b
)
334 /* --- A quick comment --- *
336 * Since the @sym_base@ block contains the hash, finding the element in the
337 * bin list is really quick -- it's not worth bothering with things like
338 * doubly linked lists.
342 sym_base
*bin
= (sym_base
*)(t
->a
+ (p
->hash
& t
->mask
));
344 /* --- Find the item in the bin list --- */
354 /* --- Now just remove the item from the list and free it --- *
356 * Oh, and bump the load counter.
360 if (p
->len
> SYM_BUFSZ
)
361 sub_free(p
->name
.p
, p
->len
);
366 /* --- @sym_mkiter@ --- *
368 * Arguments: @sym_iter *i@ = pointer to an iterator object
369 * @sym_table *t@ = pointer to a symbol table object
373 * Use: Creates a new symbol table iterator which may be used to
374 * iterate through a symbol table.
377 void sym_mkiter(sym_iter
*i
, sym_table
*t
)
384 /* --- @sym_next@ --- *
386 * Arguments: @sym_iter *i@ = pointer to iterator object
388 * Returns: Pointer to the next symbol found, or null when finished.
390 * Use: Returns the next symbol from the table. Symbols are not
391 * returned in any particular order.
394 void *sym_next(sym_iter
*i
)
398 /* --- Find the next item --- */
401 if (i
->i
> i
->t
->mask
)
403 i
->n
= i
->t
->a
[i
->i
++];
406 /* --- Update the iterator block --- */
416 /*----- Symbol table test code --------------------------------------------*/
423 typedef struct sym_word
{
429 /* --- What it does --- *
431 * Reads the file /usr/dict/words (change to some other file full of
432 * interesting and appropriate bits of text to taste) into a big buffer and
433 * picks apart into lines. Then picks lines at random and enters them into
439 char *buff
, *p
, *lim
;
448 /* --- Initialize for reading the file --- */
451 buff
= xmalloc(sz
+ 1);
455 if ((fp
= fopen("/usr/dict/words", "r")) == 0)
456 fprintf(stderr
, "buggered ;-( (%s)\n", strerror(errno
));
458 /* --- Read buffers of text --- *
460 * Read a buffer. If more to come, double the buffer size and try again.
461 * This is the method I recommended to comp.lang.c, so I may as well try
466 i
= fread(buff
+ done
, 1, sz
- done
, fp
);
471 buff
= xrealloc(buff
, sz
+ 1);
474 /* --- Count the lines --- */
479 for (p
= buff
; p
< lim
; p
++)
480 if (*p
== '\n') sz
++;
482 /* --- Build a table of line starts --- */
484 line
= xmalloc(sz
* sizeof(char *));
487 for (p
= buff
; p
< lim
; p
++)
488 if (*p
== '\n') *p
= 0, line
[i
++] = p
+ 1;
491 /* --- Build a table of lines --- *
493 * This reverses the mapping which the symbol table performs, so that its
494 * accuracy can be tested.
497 flag
= xmalloc(sz
* sizeof(sym_word
*));
498 for (i
= 0; i
< sz
; i
++)
505 i
= (unsigned)rand() % sz
;
512 printf("find `%s'\n", line
[i
]);
513 if ((rand() & 1023) == 0) {
514 putchar('.'); fflush(stdout
);
517 w
= sym_find(&tbl
, line
[i
], -1, 0, 0);
519 printf("*** error: find `%s' gave %p not %p\n",
520 line
[i
], (void *)w
, (void *)flag
[i
]);
521 else if (w
&& w
->i
!= i
)
522 printf("*** error: find sym for `%s' gives index %i not %i\n",
530 printf("create `%s'\n", line
[i
]);
531 if ((rand() & 1023) == 0) {
532 putchar('+'); fflush(stdout
);
535 w
= sym_find(&tbl
, line
[i
], -1, sizeof(sym_word
), &f
);
539 printf("*** error: create `%s' gave %p not %p\n",
540 line
[i
], (void *)w
, (void *)flag
[i
]);
541 else if (w
&& w
->i
!= i
)
542 printf("*** error: create sym for `%s' gives index %i not %i\n",
548 printf("*** error: create `%s' gave new block, should be %p\n",
549 line
[i
], (void *)flag
[i
]);
565 v
= (rand() % entries
) == 0;
568 printf("\niterated %i entries\n", entries
);
573 ntbl
= xmalloc(sz
* sizeof(sym_word
*));
574 memcpy(ntbl
, flag
, sz
* sizeof(sym_word
*));
575 sym_mkiter(&it
, &tbl
);
577 while ((w
= sym_next(&it
)) != 0) {
579 printf("*** error: iterate returned duff item %i\n", w
->i
);
584 for (i
= 0; i
< sz
; i
++)
585 if (ntbl
[i
]) printf("*** error: iterate didn't return item %i\n",
592 int v
= rand() & 255 ?
0 : 1;
597 for (i
= 0; i
<= tbl
.mask
; i
++) {
598 if (!tbl
.a
[i
]) continue;
599 if (v
) printf(" %i: ", i
);
602 if ((b
->hash
& tbl
.mask
) != i
)
603 printf("*** error: bad hash value found");
604 if (v
) printf("`%s'(%08lx:%lu) ",
605 line
[((sym_word
*)b
)->i
],
610 if (v
) putchar('\n');
616 printf("remove `%s'\n", SYM_NAME(&flag
[i
]->base
));
617 if ((rand() & 1023) == 0) {
618 putchar('-'); fflush(stdout
);
620 sym_remove(&tbl
, flag
[i
]);
634 /*----- That's all, folks -------------------------------------------------*/