00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00037 #include "ctrump/common/symbol.h"
00038 #include "ctrump/common/mempool.h"
00039 #include <stdlib.h>
00040 #include <string.h>
00041
00042 static unsigned int
00043 hash(const char *symstr,
00044 int symlen)
00045 {
00046 int h = 0;
00047 int i;
00048 for (i=0; i<symlen; i++) {
00049 int c = symstr[i];
00050
00051 h = h*997+c;
00052 }
00053
00054 return h + (h>>5);
00055 }
00056
00060 static struct table {
00061 unsigned int table_size;
00062 struct ctrump_symbol **table;
00063 struct ctrump_mempool pool;
00064 } table;
00065 static int symbol_id = 0;
00066
00067 void
00068 ctrump_init_symtab(int initial_size)
00069 {
00070 int i;
00071 symbol_id = 0;
00072 table.table_size = initial_size;
00073 ctrump_mempool_init(&table.pool, 1024);
00074 table.table = malloc(initial_size * sizeof(struct ctrump_symbol*));
00075 for (i=0; i<initial_size; i++) {
00076 table.table[i] = NULL;
00077 }
00078 }
00079
00080 void
00081 ctrump_destroy_symtab(void)
00082 {
00083 ctrump_mempool_destroy(&table.pool);
00084 free(table.table);
00085 }
00086
00087 const struct ctrump_symbol *
00088 ctrump_intern(const char *symstr,
00089 int symstrlen)
00090 {
00091 unsigned int h = hash(symstr, symstrlen);
00092 struct ctrump_symbol **chain_ptr = &table.table[h%table.table_size];
00093 struct ctrump_symbol *cur = *chain_ptr;
00094 char *strbuf;
00095
00096 while (cur) {
00097 if ((memcmp(cur->symstr, symstr, symstrlen)==0) &&
00098 cur->symlen == symstrlen) {
00099
00100 return cur;
00101 }
00102
00103 chain_ptr = &cur->chain;
00104 cur = cur->chain;
00105 }
00106
00107
00108 strbuf = ctrump_mempool_alloc_align(&table.pool, 0, symstrlen+1);
00109 memcpy(strbuf, symstr, symstrlen);
00110 strbuf[symstrlen] = '\0';
00111
00112 cur = ctrump_mempool_alloc(&table.pool, sizeof(struct ctrump_symbol));
00113 cur->symlen = symstrlen;
00114 cur->symstr = strbuf;
00115 cur->chain = NULL;
00116 cur->hashval = h;
00117 cur->id = symbol_id++;
00118
00119 *chain_ptr = cur;
00120
00121 return cur;
00122 }
00123
00124 int
00125 ctrump_get_current_symbol_num(void)
00126 {
00127 return symbol_id;
00128 }