2 // Copyright (c) 1999-2008 by Digital Mars
4 // written by Walter Bright
5 // http://www.digitalmars.com
6 // License for redistribution is by either the Artistic License
7 // in artistic.txt, or the GNU General Public License in gnu.txt.
8 // See the included readme.txt for details.
19 #include "stringtable.h"
21 StringTable::StringTable(unsigned size
)
23 table
= (void **)mem
.calloc(size
, sizeof(void *));
28 StringTable::~StringTable()
32 // Zero out dangling pointers to help garbage collector.
33 // Should zero out StringEntry's too.
34 for (i
= 0; i
< count
; i
++)
49 static StringEntry
*alloc(const dchar
*s
, unsigned len
);
52 StringEntry
*StringEntry::alloc(const dchar
*s
, unsigned len
)
56 se
= (StringEntry
*) mem
.calloc(1,sizeof(StringEntry
) - sizeof(Lstring
) + Lstring::size(len
));
57 se
->value
.lstring
.length
= len
;
58 se
->hash
= Dchar::calcHash(s
,len
);
59 memcpy(se
->value
.lstring
.string
, s
, len
* sizeof(dchar
));
63 void **StringTable::search(const dchar
*s
, unsigned len
)
70 //printf("StringTable::search(%p,%d)\n",s,len);
71 hash
= Dchar::calcHash(s
,len
);
73 se
= (StringEntry
**)&table
[u
];
74 //printf("\thash = %d, u = %d\n",hash,u);
77 cmp
= (*se
)->hash
- hash
;
80 cmp
= (*se
)->value
.lstring
.len() - len
;
83 cmp
= Dchar::memcmp(s
,(*se
)->value
.lstring
.toDchars(),len
);
93 //printf("\treturn %p, %p\n",se, (*se));
97 StringValue
*StringTable::lookup(const dchar
*s
, unsigned len
)
100 se
= *(StringEntry
**)search(s
,len
);
107 StringValue
*StringTable::update(const dchar
*s
, unsigned len
)
111 pse
= (StringEntry
**)search(s
,len
);
113 if (!se
) // not in table: so create new entry
115 se
= StringEntry::alloc(s
, len
);
121 StringValue
*StringTable::insert(const dchar
*s
, unsigned len
)
125 pse
= (StringEntry
**)search(s
,len
);
128 return NULL
; // error: already in table
131 se
= StringEntry::alloc(s
, len
);