luaH_set does the set and protect its value; luaH_move can then be a

macro.
New algorithm for double hashing (does not use "%").
This commit is contained in:
Roberto Ierusalimschy 1999-01-25 15:41:19 -02:00
parent 57ffc3f009
commit fd7d0774e5
1 changed files with 16 additions and 31 deletions

View File

@ -1,5 +1,5 @@
/* /*
** $Id: ltable.c,v 1.18 1999/01/22 18:47:23 roberto Exp roberto $ ** $Id: ltable.c,v 1.19 1999/01/25 12:30:11 roberto Exp roberto $
** Lua tables (hash) ** Lua tables (hash)
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@ -53,21 +53,17 @@ static long int hashindex (TObject *ref) {
} }
Node *luaH_present (Hash *t, TObject *ref) { Node *luaH_present (Hash *t, TObject *key) {
int tsize = nhash(t); int tsize = nhash(t);
long int h = hashindex(ref); long int h = hashindex(key);
int h1 = h%tsize; int h1 = h%tsize;
Node *n = node(t, h1); Node *n = node(t, h1);
/* keep looking until an entry with "ref" equal to ref or nil */ /* keep looking until an entry with "ref" equal to key or nil */
if ((ttype(ref(n)) == ttype(ref) ? !luaO_equalval(ref, ref(n)) while ((ttype(ref(n)) == ttype(key)) ? !luaO_equalval(key, ref(n))
: ttype(ref(n)) != LUA_T_NIL)) { : ttype(ref(n)) != LUA_T_NIL) {
int h2 = h%(tsize-2) + 1; h1 += (h&(tsize-2)) + 1; /* double hashing */
do {
h1 += h2;
if (h1 >= tsize) h1 -= tsize; if (h1 >= tsize) h1 -= tsize;
n = node(t, h1); n = node(t, h1);
} while ((ttype(ref(n)) == ttype(ref) ? !luaO_equalval(ref, ref(n))
: ttype(ref(n)) != LUA_T_NIL));
} }
return n; return n;
} }
@ -139,21 +135,20 @@ static void rehash (Hash *t) {
} }
/* void luaH_set (Hash *t, TObject *ref, TObject *val) {
** If the hash node is present, return its pointer, otherwise create a new
** node for the given reference and also return its pointer.
*/
TObject *luaH_set (Hash *t, TObject *ref) {
Node *n = luaH_present(t, ref); Node *n = luaH_present(t, ref);
if (ttype(ref(n)) == LUA_T_NIL) { if (ttype(ref(n)) != LUA_T_NIL)
*val(n) = *val;
else {
TObject buff = *val; /* rehash may invalidate this address */
if ((long)nuse(t)*3L > (long)nhash(t)*2L) { if ((long)nuse(t)*3L > (long)nhash(t)*2L) {
rehash(t); rehash(t);
n = luaH_present(t, ref); n = luaH_present(t, ref);
} }
nuse(t)++; nuse(t)++;
*ref(n) = *ref; *ref(n) = *ref;
*val(n) = buff;
} }
return (val(n));
} }
@ -186,7 +181,7 @@ void luaH_setint (Hash *t, int ref, TObject *val) {
TObject index; TObject index;
ttype(&index) = LUA_T_NUMBER; ttype(&index) = LUA_T_NUMBER;
nvalue(&index) = ref; nvalue(&index) = ref;
*(luaH_set(t, &index)) = *val; luaH_set(t, &index, val);
} }
@ -197,13 +192,3 @@ TObject *luaH_getint (Hash *t, int ref) {
return luaH_get(t, &index); return luaH_get(t, &index);
} }
void luaH_move (Hash *t, int from, int to) {
TObject index;
TObject *toadd;
ttype(&index) = LUA_T_NUMBER;
nvalue(&index) = to;
toadd = luaH_set(t, &index);
nvalue(&index) = from;
*toadd = *luaH_get(t, &index);
}