xref: /freebsd/contrib/lua/src/ltable.c (revision a9490b81)
18e3e3a7aSWarner Losh /*
20495ed39SKyle Evans ** $Id: ltable.c $
38e3e3a7aSWarner Losh ** Lua tables (hash)
48e3e3a7aSWarner Losh ** See Copyright Notice in lua.h
58e3e3a7aSWarner Losh */
68e3e3a7aSWarner Losh 
78e3e3a7aSWarner Losh #define ltable_c
88e3e3a7aSWarner Losh #define LUA_CORE
98e3e3a7aSWarner Losh 
108e3e3a7aSWarner Losh #include "lprefix.h"
118e3e3a7aSWarner Losh 
128e3e3a7aSWarner Losh 
138e3e3a7aSWarner Losh /*
148e3e3a7aSWarner Losh ** Implementation of tables (aka arrays, objects, or hash tables).
158e3e3a7aSWarner Losh ** Tables keep its elements in two parts: an array part and a hash part.
168e3e3a7aSWarner Losh ** Non-negative integer keys are all candidates to be kept in the array
178e3e3a7aSWarner Losh ** part. The actual size of the array is the largest 'n' such that
188e3e3a7aSWarner Losh ** more than half the slots between 1 and n are in use.
198e3e3a7aSWarner Losh ** Hash uses a mix of chained scatter table with Brent's variation.
208e3e3a7aSWarner Losh ** A main invariant of these tables is that, if an element is not
218e3e3a7aSWarner Losh ** in its main position (i.e. the 'original' position that its hash gives
228e3e3a7aSWarner Losh ** to it), then the colliding element is in its own main position.
238e3e3a7aSWarner Losh ** Hence even when the load factor reaches 100%, performance remains good.
248e3e3a7aSWarner Losh */
258e3e3a7aSWarner Losh 
268e3e3a7aSWarner Losh #include <math.h>
278e3e3a7aSWarner Losh #include <limits.h>
288e3e3a7aSWarner Losh 
298e3e3a7aSWarner Losh #include "lua.h"
308e3e3a7aSWarner Losh 
318e3e3a7aSWarner Losh #include "ldebug.h"
328e3e3a7aSWarner Losh #include "ldo.h"
338e3e3a7aSWarner Losh #include "lgc.h"
348e3e3a7aSWarner Losh #include "lmem.h"
358e3e3a7aSWarner Losh #include "lobject.h"
368e3e3a7aSWarner Losh #include "lstate.h"
378e3e3a7aSWarner Losh #include "lstring.h"
388e3e3a7aSWarner Losh #include "ltable.h"
398e3e3a7aSWarner Losh #include "lvm.h"
408e3e3a7aSWarner Losh 
418e3e3a7aSWarner Losh 
428e3e3a7aSWarner Losh /*
430495ed39SKyle Evans ** MAXABITS is the largest integer such that MAXASIZE fits in an
440495ed39SKyle Evans ** unsigned int.
458e3e3a7aSWarner Losh */
468e3e3a7aSWarner Losh #define MAXABITS	cast_int(sizeof(int) * CHAR_BIT - 1)
470495ed39SKyle Evans 
488e3e3a7aSWarner Losh 
498e3e3a7aSWarner Losh /*
500495ed39SKyle Evans ** MAXASIZE is the maximum size of the array part. It is the minimum
510495ed39SKyle Evans ** between 2^MAXABITS and the maximum size that, measured in bytes,
520495ed39SKyle Evans ** fits in a 'size_t'.
530495ed39SKyle Evans */
540495ed39SKyle Evans #define MAXASIZE	luaM_limitN(1u << MAXABITS, TValue)
550495ed39SKyle Evans 
560495ed39SKyle Evans /*
570495ed39SKyle Evans ** MAXHBITS is the largest integer such that 2^MAXHBITS fits in a
580495ed39SKyle Evans ** signed int.
598e3e3a7aSWarner Losh */
608e3e3a7aSWarner Losh #define MAXHBITS	(MAXABITS - 1)
618e3e3a7aSWarner Losh 
628e3e3a7aSWarner Losh 
630495ed39SKyle Evans /*
640495ed39SKyle Evans ** MAXHSIZE is the maximum size of the hash part. It is the minimum
650495ed39SKyle Evans ** between 2^MAXHBITS and the maximum size such that, measured in bytes,
660495ed39SKyle Evans ** it fits in a 'size_t'.
670495ed39SKyle Evans */
680495ed39SKyle Evans #define MAXHSIZE	luaM_limitN(1u << MAXHBITS, Node)
690495ed39SKyle Evans 
700495ed39SKyle Evans 
718c784bb8SWarner Losh /*
728c784bb8SWarner Losh ** When the original hash value is good, hashing by a power of 2
738c784bb8SWarner Losh ** avoids the cost of '%'.
748c784bb8SWarner Losh */
758e3e3a7aSWarner Losh #define hashpow2(t,n)		(gnode(t, lmod((n), sizenode(t))))
768e3e3a7aSWarner Losh 
778c784bb8SWarner Losh /*
788c784bb8SWarner Losh ** for other types, it is better to avoid modulo by power of 2, as
798c784bb8SWarner Losh ** they can have many 2 factors.
808c784bb8SWarner Losh */
818c784bb8SWarner Losh #define hashmod(t,n)	(gnode(t, ((n) % ((sizenode(t)-1)|1))))
828c784bb8SWarner Losh 
838c784bb8SWarner Losh 
848e3e3a7aSWarner Losh #define hashstr(t,str)		hashpow2(t, (str)->hash)
858e3e3a7aSWarner Losh #define hashboolean(t,p)	hashpow2(t, p)
868e3e3a7aSWarner Losh 
878e3e3a7aSWarner Losh 
888e3e3a7aSWarner Losh #define hashpointer(t,p)	hashmod(t, point2uint(p))
898e3e3a7aSWarner Losh 
908e3e3a7aSWarner Losh 
918e3e3a7aSWarner Losh #define dummynode		(&dummynode_)
928e3e3a7aSWarner Losh 
938e3e3a7aSWarner Losh static const Node dummynode_ = {
940495ed39SKyle Evans   {{NULL}, LUA_VEMPTY,  /* value's value and type */
950495ed39SKyle Evans    LUA_VNIL, 0, {NULL}}  /* key type, next, and key value */
968e3e3a7aSWarner Losh };
978e3e3a7aSWarner Losh 
988e3e3a7aSWarner Losh 
990495ed39SKyle Evans static const TValue absentkey = {ABSTKEYCONSTANT};
1000495ed39SKyle Evans 
1010495ed39SKyle Evans 
1028c784bb8SWarner Losh /*
1038c784bb8SWarner Losh ** Hash for integers. To allow a good hash, use the remainder operator
1048c784bb8SWarner Losh ** ('%'). If integer fits as a non-negative int, compute an int
1058c784bb8SWarner Losh ** remainder, which is faster. Otherwise, use an unsigned-integer
1068c784bb8SWarner Losh ** remainder, which uses all bits and ensures a non-negative result.
1078c784bb8SWarner Losh */
hashint(const Table * t,lua_Integer i)1088c784bb8SWarner Losh static Node *hashint (const Table *t, lua_Integer i) {
1098c784bb8SWarner Losh   lua_Unsigned ui = l_castS2U(i);
110*a9490b81SWarner Losh   if (ui <= cast_uint(INT_MAX))
1118c784bb8SWarner Losh     return hashmod(t, cast_int(ui));
1128c784bb8SWarner Losh   else
1138c784bb8SWarner Losh     return hashmod(t, ui);
1148c784bb8SWarner Losh }
1158c784bb8SWarner Losh 
1160495ed39SKyle Evans 
1178e3e3a7aSWarner Losh /*
1188e3e3a7aSWarner Losh ** Hash for floating-point numbers.
1198e3e3a7aSWarner Losh ** The main computation should be just
1208e3e3a7aSWarner Losh **     n = frexp(n, &i); return (n * INT_MAX) + i
1218e3e3a7aSWarner Losh ** but there are some numerical subtleties.
1228e3e3a7aSWarner Losh ** In a two-complement representation, INT_MAX does not has an exact
1238e3e3a7aSWarner Losh ** representation as a float, but INT_MIN does; because the absolute
1248e3e3a7aSWarner Losh ** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the
1258e3e3a7aSWarner Losh ** absolute value of the product 'frexp * -INT_MIN' is smaller or equal
1268e3e3a7aSWarner Losh ** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when
1278e3e3a7aSWarner Losh ** adding 'i'; the use of '~u' (instead of '-u') avoids problems with
1288e3e3a7aSWarner Losh ** INT_MIN.
1298e3e3a7aSWarner Losh */
1308e3e3a7aSWarner Losh #if !defined(l_hashfloat)
l_hashfloat(lua_Number n)1318e3e3a7aSWarner Losh static int l_hashfloat (lua_Number n) {
1328e3e3a7aSWarner Losh   int i;
1338e3e3a7aSWarner Losh   lua_Integer ni;
1348e3e3a7aSWarner Losh   n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN);
1358e3e3a7aSWarner Losh   if (!lua_numbertointeger(n, &ni)) {  /* is 'n' inf/-inf/NaN? */
1368e3e3a7aSWarner Losh     lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL));
1378e3e3a7aSWarner Losh     return 0;
1388e3e3a7aSWarner Losh   }
1398e3e3a7aSWarner Losh   else {  /* normal case */
1400495ed39SKyle Evans     unsigned int u = cast_uint(i) + cast_uint(ni);
1410495ed39SKyle Evans     return cast_int(u <= cast_uint(INT_MAX) ? u : ~u);
1428e3e3a7aSWarner Losh   }
1438e3e3a7aSWarner Losh }
1448e3e3a7aSWarner Losh #endif
1458e3e3a7aSWarner Losh 
1468e3e3a7aSWarner Losh 
1478e3e3a7aSWarner Losh /*
1480495ed39SKyle Evans ** returns the 'main' position of an element in a table (that is,
1498c784bb8SWarner Losh ** the index of its hash value).
1508e3e3a7aSWarner Losh */
mainpositionTV(const Table * t,const TValue * key)1518c784bb8SWarner Losh static Node *mainpositionTV (const Table *t, const TValue *key) {
1528c784bb8SWarner Losh   switch (ttypetag(key)) {
1538c784bb8SWarner Losh     case LUA_VNUMINT: {
1548c784bb8SWarner Losh       lua_Integer i = ivalue(key);
1558c784bb8SWarner Losh       return hashint(t, i);
1568c784bb8SWarner Losh     }
1578c784bb8SWarner Losh     case LUA_VNUMFLT: {
1588c784bb8SWarner Losh       lua_Number n = fltvalue(key);
1598c784bb8SWarner Losh       return hashmod(t, l_hashfloat(n));
1608c784bb8SWarner Losh     }
1618c784bb8SWarner Losh     case LUA_VSHRSTR: {
1628c784bb8SWarner Losh       TString *ts = tsvalue(key);
1638c784bb8SWarner Losh       return hashstr(t, ts);
1648c784bb8SWarner Losh     }
1658c784bb8SWarner Losh     case LUA_VLNGSTR: {
1668c784bb8SWarner Losh       TString *ts = tsvalue(key);
1678c784bb8SWarner Losh       return hashpow2(t, luaS_hashlongstr(ts));
1688c784bb8SWarner Losh     }
1690495ed39SKyle Evans     case LUA_VFALSE:
1700495ed39SKyle Evans       return hashboolean(t, 0);
1710495ed39SKyle Evans     case LUA_VTRUE:
1720495ed39SKyle Evans       return hashboolean(t, 1);
1738c784bb8SWarner Losh     case LUA_VLIGHTUSERDATA: {
1748c784bb8SWarner Losh       void *p = pvalue(key);
1758c784bb8SWarner Losh       return hashpointer(t, p);
1768c784bb8SWarner Losh     }
1778c784bb8SWarner Losh     case LUA_VLCF: {
1788c784bb8SWarner Losh       lua_CFunction f = fvalue(key);
1798c784bb8SWarner Losh       return hashpointer(t, f);
1808c784bb8SWarner Losh     }
1818c784bb8SWarner Losh     default: {
1828c784bb8SWarner Losh       GCObject *o = gcvalue(key);
1838c784bb8SWarner Losh       return hashpointer(t, o);
1848c784bb8SWarner Losh     }
1858e3e3a7aSWarner Losh   }
1868e3e3a7aSWarner Losh }
1878e3e3a7aSWarner Losh 
1888e3e3a7aSWarner Losh 
mainpositionfromnode(const Table * t,Node * nd)1898c784bb8SWarner Losh l_sinline Node *mainpositionfromnode (const Table *t, Node *nd) {
1908c784bb8SWarner Losh   TValue key;
1918c784bb8SWarner Losh   getnodekey(cast(lua_State *, NULL), &key, nd);
1928c784bb8SWarner Losh   return mainpositionTV(t, &key);
1938e3e3a7aSWarner Losh }
1940495ed39SKyle Evans 
1950495ed39SKyle Evans 
1960495ed39SKyle Evans /*
1970495ed39SKyle Evans ** Check whether key 'k1' is equal to the key in node 'n2'. This
1980495ed39SKyle Evans ** equality is raw, so there are no metamethods. Floats with integer
1990495ed39SKyle Evans ** values have been normalized, so integers cannot be equal to
2000495ed39SKyle Evans ** floats. It is assumed that 'eqshrstr' is simply pointer equality, so
2010495ed39SKyle Evans ** that short strings are handled in the default case.
2020495ed39SKyle Evans ** A true 'deadok' means to accept dead keys as equal to their original
2030495ed39SKyle Evans ** values. All dead keys are compared in the default case, by pointer
2040495ed39SKyle Evans ** identity. (Only collectable objects can produce dead keys.) Note that
2050495ed39SKyle Evans ** dead long strings are also compared by identity.
2060495ed39SKyle Evans ** Once a key is dead, its corresponding value may be collected, and
2070495ed39SKyle Evans ** then another value can be created with the same address. If this
2080495ed39SKyle Evans ** other value is given to 'next', 'equalkey' will signal a false
2090495ed39SKyle Evans ** positive. In a regular traversal, this situation should never happen,
2100495ed39SKyle Evans ** as all keys given to 'next' came from the table itself, and therefore
2110495ed39SKyle Evans ** could not have been collected. Outside a regular traversal, we
2120495ed39SKyle Evans ** have garbage in, garbage out. What is relevant is that this false
2130495ed39SKyle Evans ** positive does not break anything.  (In particular, 'next' will return
2140495ed39SKyle Evans ** some other valid item on the table or nil.)
2150495ed39SKyle Evans */
equalkey(const TValue * k1,const Node * n2,int deadok)2160495ed39SKyle Evans static int equalkey (const TValue *k1, const Node *n2, int deadok) {
2170495ed39SKyle Evans   if ((rawtt(k1) != keytt(n2)) &&  /* not the same variants? */
2180495ed39SKyle Evans        !(deadok && keyisdead(n2) && iscollectable(k1)))
2190495ed39SKyle Evans    return 0;  /* cannot be same key */
2200495ed39SKyle Evans   switch (keytt(n2)) {
2210495ed39SKyle Evans     case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE:
2220495ed39SKyle Evans       return 1;
2230495ed39SKyle Evans     case LUA_VNUMINT:
2240495ed39SKyle Evans       return (ivalue(k1) == keyival(n2));
2250495ed39SKyle Evans     case LUA_VNUMFLT:
2260495ed39SKyle Evans       return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2)));
2270495ed39SKyle Evans     case LUA_VLIGHTUSERDATA:
2280495ed39SKyle Evans       return pvalue(k1) == pvalueraw(keyval(n2));
2290495ed39SKyle Evans     case LUA_VLCF:
2300495ed39SKyle Evans       return fvalue(k1) == fvalueraw(keyval(n2));
2310495ed39SKyle Evans     case ctb(LUA_VLNGSTR):
2320495ed39SKyle Evans       return luaS_eqlngstr(tsvalue(k1), keystrval(n2));
2330495ed39SKyle Evans     default:
2340495ed39SKyle Evans       return gcvalue(k1) == gcvalueraw(keyval(n2));
2350495ed39SKyle Evans   }
2360495ed39SKyle Evans }
2370495ed39SKyle Evans 
2380495ed39SKyle Evans 
2390495ed39SKyle Evans /*
2400495ed39SKyle Evans ** True if value of 'alimit' is equal to the real size of the array
2410495ed39SKyle Evans ** part of table 't'. (Otherwise, the array part must be larger than
2420495ed39SKyle Evans ** 'alimit'.)
2430495ed39SKyle Evans */
2440495ed39SKyle Evans #define limitequalsasize(t)	(isrealasize(t) || ispow2((t)->alimit))
2450495ed39SKyle Evans 
2460495ed39SKyle Evans 
2470495ed39SKyle Evans /*
2480495ed39SKyle Evans ** Returns the real size of the 'array' array
2490495ed39SKyle Evans */
luaH_realasize(const Table * t)2500495ed39SKyle Evans LUAI_FUNC unsigned int luaH_realasize (const Table *t) {
2510495ed39SKyle Evans   if (limitequalsasize(t))
2520495ed39SKyle Evans     return t->alimit;  /* this is the size */
2530495ed39SKyle Evans   else {
2540495ed39SKyle Evans     unsigned int size = t->alimit;
2550495ed39SKyle Evans     /* compute the smallest power of 2 not smaller than 'n' */
2560495ed39SKyle Evans     size |= (size >> 1);
2570495ed39SKyle Evans     size |= (size >> 2);
2580495ed39SKyle Evans     size |= (size >> 4);
2590495ed39SKyle Evans     size |= (size >> 8);
260*a9490b81SWarner Losh #if (UINT_MAX >> 14) > 3  /* unsigned int has more than 16 bits */
2610495ed39SKyle Evans     size |= (size >> 16);
2620495ed39SKyle Evans #if (UINT_MAX >> 30) > 3
2630495ed39SKyle Evans     size |= (size >> 32);  /* unsigned int has more than 32 bits */
2640495ed39SKyle Evans #endif
265*a9490b81SWarner Losh #endif
2660495ed39SKyle Evans     size++;
2670495ed39SKyle Evans     lua_assert(ispow2(size) && size/2 < t->alimit && t->alimit < size);
2680495ed39SKyle Evans     return size;
2690495ed39SKyle Evans   }
2700495ed39SKyle Evans }
2710495ed39SKyle Evans 
2720495ed39SKyle Evans 
2730495ed39SKyle Evans /*
2740495ed39SKyle Evans ** Check whether real size of the array is a power of 2.
2750495ed39SKyle Evans ** (If it is not, 'alimit' cannot be changed to any other value
2760495ed39SKyle Evans ** without changing the real size.)
2770495ed39SKyle Evans */
ispow2realasize(const Table * t)2780495ed39SKyle Evans static int ispow2realasize (const Table *t) {
2790495ed39SKyle Evans   return (!isrealasize(t) || ispow2(t->alimit));
2800495ed39SKyle Evans }
2810495ed39SKyle Evans 
2820495ed39SKyle Evans 
setlimittosize(Table * t)2830495ed39SKyle Evans static unsigned int setlimittosize (Table *t) {
2840495ed39SKyle Evans   t->alimit = luaH_realasize(t);
2850495ed39SKyle Evans   setrealasize(t);
2860495ed39SKyle Evans   return t->alimit;
2870495ed39SKyle Evans }
2880495ed39SKyle Evans 
2890495ed39SKyle Evans 
2900495ed39SKyle Evans #define limitasasize(t)	check_exp(isrealasize(t), t->alimit)
2910495ed39SKyle Evans 
2920495ed39SKyle Evans 
2930495ed39SKyle Evans 
2940495ed39SKyle Evans /*
2950495ed39SKyle Evans ** "Generic" get version. (Not that generic: not valid for integers,
2960495ed39SKyle Evans ** which may be in array part, nor for floats with integral values.)
2970495ed39SKyle Evans ** See explanation about 'deadok' in function 'equalkey'.
2980495ed39SKyle Evans */
getgeneric(Table * t,const TValue * key,int deadok)2990495ed39SKyle Evans static const TValue *getgeneric (Table *t, const TValue *key, int deadok) {
3000495ed39SKyle Evans   Node *n = mainpositionTV(t, key);
3010495ed39SKyle Evans   for (;;) {  /* check whether 'key' is somewhere in the chain */
3020495ed39SKyle Evans     if (equalkey(key, n, deadok))
3030495ed39SKyle Evans       return gval(n);  /* that's it */
3040495ed39SKyle Evans     else {
3050495ed39SKyle Evans       int nx = gnext(n);
3060495ed39SKyle Evans       if (nx == 0)
3070495ed39SKyle Evans         return &absentkey;  /* not found */
3080495ed39SKyle Evans       n += nx;
3090495ed39SKyle Evans     }
3100495ed39SKyle Evans   }
3110495ed39SKyle Evans }
3120495ed39SKyle Evans 
3130495ed39SKyle Evans 
3140495ed39SKyle Evans /*
3150495ed39SKyle Evans ** returns the index for 'k' if 'k' is an appropriate key to live in
3160495ed39SKyle Evans ** the array part of a table, 0 otherwise.
3170495ed39SKyle Evans */
arrayindex(lua_Integer k)3180495ed39SKyle Evans static unsigned int arrayindex (lua_Integer k) {
3190495ed39SKyle Evans   if (l_castS2U(k) - 1u < MAXASIZE)  /* 'k' in [1, MAXASIZE]? */
3200495ed39SKyle Evans     return cast_uint(k);  /* 'key' is an appropriate array index */
3210495ed39SKyle Evans   else
3220495ed39SKyle Evans     return 0;
3238e3e3a7aSWarner Losh }
3248e3e3a7aSWarner Losh 
3258e3e3a7aSWarner Losh 
3268e3e3a7aSWarner Losh /*
3278e3e3a7aSWarner Losh ** returns the index of a 'key' for table traversals. First goes all
3288e3e3a7aSWarner Losh ** elements in the array part, then elements in the hash part. The
3298e3e3a7aSWarner Losh ** beginning of a traversal is signaled by 0.
3308e3e3a7aSWarner Losh */
findindex(lua_State * L,Table * t,TValue * key,unsigned int asize)3310495ed39SKyle Evans static unsigned int findindex (lua_State *L, Table *t, TValue *key,
3320495ed39SKyle Evans                                unsigned int asize) {
3338e3e3a7aSWarner Losh   unsigned int i;
3348e3e3a7aSWarner Losh   if (ttisnil(key)) return 0;  /* first iteration */
3350495ed39SKyle Evans   i = ttisinteger(key) ? arrayindex(ivalue(key)) : 0;
3360495ed39SKyle Evans   if (i - 1u < asize)  /* is 'key' inside array part? */
3378e3e3a7aSWarner Losh     return i;  /* yes; that's the index */
3388e3e3a7aSWarner Losh   else {
3390495ed39SKyle Evans     const TValue *n = getgeneric(t, key, 1);
3408c784bb8SWarner Losh     if (l_unlikely(isabstkey(n)))
3418e3e3a7aSWarner Losh       luaG_runerror(L, "invalid key to 'next'");  /* key not found */
3420495ed39SKyle Evans     i = cast_int(nodefromval(n) - gnode(t, 0));  /* key index in hash table */
3430495ed39SKyle Evans     /* hash elements are numbered after array ones */
3440495ed39SKyle Evans     return (i + 1) + asize;
3458e3e3a7aSWarner Losh   }
3468e3e3a7aSWarner Losh }
3478e3e3a7aSWarner Losh 
3488e3e3a7aSWarner Losh 
luaH_next(lua_State * L,Table * t,StkId key)3498e3e3a7aSWarner Losh int luaH_next (lua_State *L, Table *t, StkId key) {
3500495ed39SKyle Evans   unsigned int asize = luaH_realasize(t);
3510495ed39SKyle Evans   unsigned int i = findindex(L, t, s2v(key), asize);  /* find original key */
3520495ed39SKyle Evans   for (; i < asize; i++) {  /* try first array part */
3530495ed39SKyle Evans     if (!isempty(&t->array[i])) {  /* a non-empty entry? */
3540495ed39SKyle Evans       setivalue(s2v(key), i + 1);
3558e3e3a7aSWarner Losh       setobj2s(L, key + 1, &t->array[i]);
3568e3e3a7aSWarner Losh       return 1;
3578e3e3a7aSWarner Losh     }
3588e3e3a7aSWarner Losh   }
3590495ed39SKyle Evans   for (i -= asize; cast_int(i) < sizenode(t); i++) {  /* hash part */
3600495ed39SKyle Evans     if (!isempty(gval(gnode(t, i)))) {  /* a non-empty entry? */
3610495ed39SKyle Evans       Node *n = gnode(t, i);
3620495ed39SKyle Evans       getnodekey(L, s2v(key), n);
3630495ed39SKyle Evans       setobj2s(L, key + 1, gval(n));
3648e3e3a7aSWarner Losh       return 1;
3658e3e3a7aSWarner Losh     }
3668e3e3a7aSWarner Losh   }
3678e3e3a7aSWarner Losh   return 0;  /* no more elements */
3688e3e3a7aSWarner Losh }
3698e3e3a7aSWarner Losh 
3708e3e3a7aSWarner Losh 
freehash(lua_State * L,Table * t)3710495ed39SKyle Evans static void freehash (lua_State *L, Table *t) {
3720495ed39SKyle Evans   if (!isdummy(t))
3730495ed39SKyle Evans     luaM_freearray(L, t->node, cast_sizet(sizenode(t)));
3740495ed39SKyle Evans }
3750495ed39SKyle Evans 
3760495ed39SKyle Evans 
3778e3e3a7aSWarner Losh /*
3788e3e3a7aSWarner Losh ** {=============================================================
3798e3e3a7aSWarner Losh ** Rehash
3808e3e3a7aSWarner Losh ** ==============================================================
3818e3e3a7aSWarner Losh */
3828e3e3a7aSWarner Losh 
3838e3e3a7aSWarner Losh /*
3848e3e3a7aSWarner Losh ** Compute the optimal size for the array part of table 't'. 'nums' is a
3858e3e3a7aSWarner Losh ** "count array" where 'nums[i]' is the number of integers in the table
3868e3e3a7aSWarner Losh ** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of
3878e3e3a7aSWarner Losh ** integer keys in the table and leaves with the number of keys that
3880495ed39SKyle Evans ** will go to the array part; return the optimal size.  (The condition
3890495ed39SKyle Evans ** 'twotoi > 0' in the for loop stops the loop if 'twotoi' overflows.)
3908e3e3a7aSWarner Losh */
computesizes(unsigned int nums[],unsigned int * pna)3918e3e3a7aSWarner Losh static unsigned int computesizes (unsigned int nums[], unsigned int *pna) {
3928e3e3a7aSWarner Losh   int i;
3938e3e3a7aSWarner Losh   unsigned int twotoi;  /* 2^i (candidate for optimal size) */
3948e3e3a7aSWarner Losh   unsigned int a = 0;  /* number of elements smaller than 2^i */
3958e3e3a7aSWarner Losh   unsigned int na = 0;  /* number of elements to go to array part */
3968e3e3a7aSWarner Losh   unsigned int optimal = 0;  /* optimal size for array part */
3978e3e3a7aSWarner Losh   /* loop while keys can fill more than half of total size */
398e112e9d2SKyle Evans   for (i = 0, twotoi = 1;
399e112e9d2SKyle Evans        twotoi > 0 && *pna > twotoi / 2;
400e112e9d2SKyle Evans        i++, twotoi *= 2) {
4018e3e3a7aSWarner Losh     a += nums[i];
4028e3e3a7aSWarner Losh     if (a > twotoi/2) {  /* more than half elements present? */
4038e3e3a7aSWarner Losh       optimal = twotoi;  /* optimal size (till now) */
4048e3e3a7aSWarner Losh       na = a;  /* all elements up to 'optimal' will go to array part */
4058e3e3a7aSWarner Losh     }
4068e3e3a7aSWarner Losh   }
4078e3e3a7aSWarner Losh   lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal);
4088e3e3a7aSWarner Losh   *pna = na;
4098e3e3a7aSWarner Losh   return optimal;
4108e3e3a7aSWarner Losh }
4118e3e3a7aSWarner Losh 
4128e3e3a7aSWarner Losh 
countint(lua_Integer key,unsigned int * nums)4130495ed39SKyle Evans static int countint (lua_Integer key, unsigned int *nums) {
4148e3e3a7aSWarner Losh   unsigned int k = arrayindex(key);
4158e3e3a7aSWarner Losh   if (k != 0) {  /* is 'key' an appropriate array index? */
4168e3e3a7aSWarner Losh     nums[luaO_ceillog2(k)]++;  /* count as such */
4178e3e3a7aSWarner Losh     return 1;
4188e3e3a7aSWarner Losh   }
4198e3e3a7aSWarner Losh   else
4208e3e3a7aSWarner Losh     return 0;
4218e3e3a7aSWarner Losh }
4228e3e3a7aSWarner Losh 
4238e3e3a7aSWarner Losh 
4248e3e3a7aSWarner Losh /*
4258e3e3a7aSWarner Losh ** Count keys in array part of table 't': Fill 'nums[i]' with
4268e3e3a7aSWarner Losh ** number of keys that will go into corresponding slice and return
4278e3e3a7aSWarner Losh ** total number of non-nil keys.
4288e3e3a7aSWarner Losh */
numusearray(const Table * t,unsigned int * nums)4298e3e3a7aSWarner Losh static unsigned int numusearray (const Table *t, unsigned int *nums) {
4308e3e3a7aSWarner Losh   int lg;
4318e3e3a7aSWarner Losh   unsigned int ttlg;  /* 2^lg */
4328e3e3a7aSWarner Losh   unsigned int ause = 0;  /* summation of 'nums' */
4338e3e3a7aSWarner Losh   unsigned int i = 1;  /* count to traverse all array keys */
4340495ed39SKyle Evans   unsigned int asize = limitasasize(t);  /* real array size */
4358e3e3a7aSWarner Losh   /* traverse each slice */
4368e3e3a7aSWarner Losh   for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
4378e3e3a7aSWarner Losh     unsigned int lc = 0;  /* counter */
4388e3e3a7aSWarner Losh     unsigned int lim = ttlg;
4390495ed39SKyle Evans     if (lim > asize) {
4400495ed39SKyle Evans       lim = asize;  /* adjust upper limit */
4418e3e3a7aSWarner Losh       if (i > lim)
4428e3e3a7aSWarner Losh         break;  /* no more elements to count */
4438e3e3a7aSWarner Losh     }
4448e3e3a7aSWarner Losh     /* count elements in range (2^(lg - 1), 2^lg] */
4458e3e3a7aSWarner Losh     for (; i <= lim; i++) {
4460495ed39SKyle Evans       if (!isempty(&t->array[i-1]))
4478e3e3a7aSWarner Losh         lc++;
4488e3e3a7aSWarner Losh     }
4498e3e3a7aSWarner Losh     nums[lg] += lc;
4508e3e3a7aSWarner Losh     ause += lc;
4518e3e3a7aSWarner Losh   }
4528e3e3a7aSWarner Losh   return ause;
4538e3e3a7aSWarner Losh }
4548e3e3a7aSWarner Losh 
4558e3e3a7aSWarner Losh 
numusehash(const Table * t,unsigned int * nums,unsigned int * pna)4568e3e3a7aSWarner Losh static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) {
4578e3e3a7aSWarner Losh   int totaluse = 0;  /* total number of elements */
4588e3e3a7aSWarner Losh   int ause = 0;  /* elements added to 'nums' (can go to array part) */
4598e3e3a7aSWarner Losh   int i = sizenode(t);
4608e3e3a7aSWarner Losh   while (i--) {
4618e3e3a7aSWarner Losh     Node *n = &t->node[i];
4620495ed39SKyle Evans     if (!isempty(gval(n))) {
4630495ed39SKyle Evans       if (keyisinteger(n))
4640495ed39SKyle Evans         ause += countint(keyival(n), nums);
4658e3e3a7aSWarner Losh       totaluse++;
4668e3e3a7aSWarner Losh     }
4678e3e3a7aSWarner Losh   }
4688e3e3a7aSWarner Losh   *pna += ause;
4698e3e3a7aSWarner Losh   return totaluse;
4708e3e3a7aSWarner Losh }
4718e3e3a7aSWarner Losh 
4728e3e3a7aSWarner Losh 
4730495ed39SKyle Evans /*
4740495ed39SKyle Evans ** Creates an array for the hash part of a table with the given
4750495ed39SKyle Evans ** size, or reuses the dummy node if size is zero.
4760495ed39SKyle Evans ** The computation for size overflow is in two steps: the first
4770495ed39SKyle Evans ** comparison ensures that the shift in the second one does not
4780495ed39SKyle Evans ** overflow.
4790495ed39SKyle Evans */
setnodevector(lua_State * L,Table * t,unsigned int size)4808e3e3a7aSWarner Losh static void setnodevector (lua_State *L, Table *t, unsigned int size) {
4818e3e3a7aSWarner Losh   if (size == 0) {  /* no elements to hash part? */
4828e3e3a7aSWarner Losh     t->node = cast(Node *, dummynode);  /* use common 'dummynode' */
4838e3e3a7aSWarner Losh     t->lsizenode = 0;
4848e3e3a7aSWarner Losh     t->lastfree = NULL;  /* signal that it is using dummy node */
4858e3e3a7aSWarner Losh   }
4868e3e3a7aSWarner Losh   else {
4878e3e3a7aSWarner Losh     int i;
4888e3e3a7aSWarner Losh     int lsize = luaO_ceillog2(size);
4890495ed39SKyle Evans     if (lsize > MAXHBITS || (1u << lsize) > MAXHSIZE)
4908e3e3a7aSWarner Losh       luaG_runerror(L, "table overflow");
4918e3e3a7aSWarner Losh     size = twoto(lsize);
4928e3e3a7aSWarner Losh     t->node = luaM_newvector(L, size, Node);
493*a9490b81SWarner Losh     for (i = 0; i < cast_int(size); i++) {
4948e3e3a7aSWarner Losh       Node *n = gnode(t, i);
4958e3e3a7aSWarner Losh       gnext(n) = 0;
4960495ed39SKyle Evans       setnilkey(n);
4970495ed39SKyle Evans       setempty(gval(n));
4988e3e3a7aSWarner Losh     }
4998e3e3a7aSWarner Losh     t->lsizenode = cast_byte(lsize);
5008e3e3a7aSWarner Losh     t->lastfree = gnode(t, size);  /* all positions are free */
5018e3e3a7aSWarner Losh   }
5028e3e3a7aSWarner Losh }
5038e3e3a7aSWarner Losh 
5048e3e3a7aSWarner Losh 
5050495ed39SKyle Evans /*
5060495ed39SKyle Evans ** (Re)insert all elements from the hash part of 'ot' into table 't'.
5070495ed39SKyle Evans */
reinsert(lua_State * L,Table * ot,Table * t)5080495ed39SKyle Evans static void reinsert (lua_State *L, Table *ot, Table *t) {
5098e3e3a7aSWarner Losh   int j;
5100495ed39SKyle Evans   int size = sizenode(ot);
5110495ed39SKyle Evans   for (j = 0; j < size; j++) {
5120495ed39SKyle Evans     Node *old = gnode(ot, j);
5130495ed39SKyle Evans     if (!isempty(gval(old))) {
5148e3e3a7aSWarner Losh       /* doesn't need barrier/invalidate cache, as entry was
5158e3e3a7aSWarner Losh          already present in the table */
5160495ed39SKyle Evans       TValue k;
5170495ed39SKyle Evans       getnodekey(L, &k, old);
5188c784bb8SWarner Losh       luaH_set(L, t, &k, gval(old));
5198e3e3a7aSWarner Losh     }
5208e3e3a7aSWarner Losh   }
5210495ed39SKyle Evans }
5220495ed39SKyle Evans 
5230495ed39SKyle Evans 
5240495ed39SKyle Evans /*
5250495ed39SKyle Evans ** Exchange the hash part of 't1' and 't2'.
5260495ed39SKyle Evans */
exchangehashpart(Table * t1,Table * t2)5270495ed39SKyle Evans static void exchangehashpart (Table *t1, Table *t2) {
5280495ed39SKyle Evans   lu_byte lsizenode = t1->lsizenode;
5290495ed39SKyle Evans   Node *node = t1->node;
5300495ed39SKyle Evans   Node *lastfree = t1->lastfree;
5310495ed39SKyle Evans   t1->lsizenode = t2->lsizenode;
5320495ed39SKyle Evans   t1->node = t2->node;
5330495ed39SKyle Evans   t1->lastfree = t2->lastfree;
5340495ed39SKyle Evans   t2->lsizenode = lsizenode;
5350495ed39SKyle Evans   t2->node = node;
5360495ed39SKyle Evans   t2->lastfree = lastfree;
5370495ed39SKyle Evans }
5380495ed39SKyle Evans 
5390495ed39SKyle Evans 
5400495ed39SKyle Evans /*
5410495ed39SKyle Evans ** Resize table 't' for the new given sizes. Both allocations (for
5420495ed39SKyle Evans ** the hash part and for the array part) can fail, which creates some
5430495ed39SKyle Evans ** subtleties. If the first allocation, for the hash part, fails, an
5440495ed39SKyle Evans ** error is raised and that is it. Otherwise, it copies the elements from
5450495ed39SKyle Evans ** the shrinking part of the array (if it is shrinking) into the new
5460495ed39SKyle Evans ** hash. Then it reallocates the array part.  If that fails, the table
5470495ed39SKyle Evans ** is in its original state; the function frees the new hash part and then
5480495ed39SKyle Evans ** raises the allocation error. Otherwise, it sets the new hash part
5490495ed39SKyle Evans ** into the table, initializes the new part of the array (if any) with
5500495ed39SKyle Evans ** nils and reinserts the elements of the old hash back into the new
5510495ed39SKyle Evans ** parts of the table.
5520495ed39SKyle Evans */
luaH_resize(lua_State * L,Table * t,unsigned int newasize,unsigned int nhsize)5530495ed39SKyle Evans void luaH_resize (lua_State *L, Table *t, unsigned int newasize,
5540495ed39SKyle Evans                                           unsigned int nhsize) {
5550495ed39SKyle Evans   unsigned int i;
5560495ed39SKyle Evans   Table newt;  /* to keep the new hash part */
5570495ed39SKyle Evans   unsigned int oldasize = setlimittosize(t);
5580495ed39SKyle Evans   TValue *newarray;
5590495ed39SKyle Evans   /* create new hash part with appropriate size into 'newt' */
5600495ed39SKyle Evans   setnodevector(L, &newt, nhsize);
5610495ed39SKyle Evans   if (newasize < oldasize) {  /* will array shrink? */
5620495ed39SKyle Evans     t->alimit = newasize;  /* pretend array has new size... */
5630495ed39SKyle Evans     exchangehashpart(t, &newt);  /* and new hash */
5640495ed39SKyle Evans     /* re-insert into the new hash the elements from vanishing slice */
5650495ed39SKyle Evans     for (i = newasize; i < oldasize; i++) {
5660495ed39SKyle Evans       if (!isempty(&t->array[i]))
5670495ed39SKyle Evans         luaH_setint(L, t, i + 1, &t->array[i]);
5680495ed39SKyle Evans     }
5690495ed39SKyle Evans     t->alimit = oldasize;  /* restore current size... */
5700495ed39SKyle Evans     exchangehashpart(t, &newt);  /* and hash (in case of errors) */
5710495ed39SKyle Evans   }
5720495ed39SKyle Evans   /* allocate new array */
5730495ed39SKyle Evans   newarray = luaM_reallocvector(L, t->array, oldasize, newasize, TValue);
5748c784bb8SWarner Losh   if (l_unlikely(newarray == NULL && newasize > 0)) {  /* allocation failed? */
5750495ed39SKyle Evans     freehash(L, &newt);  /* release new hash part */
5760495ed39SKyle Evans     luaM_error(L);  /* raise error (with array unchanged) */
5770495ed39SKyle Evans   }
5780495ed39SKyle Evans   /* allocation ok; initialize new part of the array */
5790495ed39SKyle Evans   exchangehashpart(t, &newt);  /* 't' has the new hash ('newt' has the old) */
5800495ed39SKyle Evans   t->array = newarray;  /* set new array part */
5810495ed39SKyle Evans   t->alimit = newasize;
5820495ed39SKyle Evans   for (i = oldasize; i < newasize; i++)  /* clear new slice of the array */
5830495ed39SKyle Evans      setempty(&t->array[i]);
5840495ed39SKyle Evans   /* re-insert elements from old hash part into new parts */
5850495ed39SKyle Evans   reinsert(L, &newt, t);  /* 'newt' now has the old hash */
5860495ed39SKyle Evans   freehash(L, &newt);  /* free old hash part */
5878e3e3a7aSWarner Losh }
5888e3e3a7aSWarner Losh 
5898e3e3a7aSWarner Losh 
luaH_resizearray(lua_State * L,Table * t,unsigned int nasize)5908e3e3a7aSWarner Losh void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
5918e3e3a7aSWarner Losh   int nsize = allocsizenode(t);
5928e3e3a7aSWarner Losh   luaH_resize(L, t, nasize, nsize);
5938e3e3a7aSWarner Losh }
5948e3e3a7aSWarner Losh 
5958e3e3a7aSWarner Losh /*
5968e3e3a7aSWarner Losh ** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
5978e3e3a7aSWarner Losh */
rehash(lua_State * L,Table * t,const TValue * ek)5988e3e3a7aSWarner Losh static void rehash (lua_State *L, Table *t, const TValue *ek) {
5998e3e3a7aSWarner Losh   unsigned int asize;  /* optimal size for array part */
6008e3e3a7aSWarner Losh   unsigned int na;  /* number of keys in the array part */
6018e3e3a7aSWarner Losh   unsigned int nums[MAXABITS + 1];
6028e3e3a7aSWarner Losh   int i;
6038e3e3a7aSWarner Losh   int totaluse;
6048e3e3a7aSWarner Losh   for (i = 0; i <= MAXABITS; i++) nums[i] = 0;  /* reset counts */
6050495ed39SKyle Evans   setlimittosize(t);
6068e3e3a7aSWarner Losh   na = numusearray(t, nums);  /* count keys in array part */
6078e3e3a7aSWarner Losh   totaluse = na;  /* all those keys are integer keys */
6088e3e3a7aSWarner Losh   totaluse += numusehash(t, nums, &na);  /* count keys in hash part */
6098e3e3a7aSWarner Losh   /* count extra key */
6100495ed39SKyle Evans   if (ttisinteger(ek))
6110495ed39SKyle Evans     na += countint(ivalue(ek), nums);
6128e3e3a7aSWarner Losh   totaluse++;
6138e3e3a7aSWarner Losh   /* compute new size for array part */
6148e3e3a7aSWarner Losh   asize = computesizes(nums, &na);
6158e3e3a7aSWarner Losh   /* resize the table to new computed sizes */
6168e3e3a7aSWarner Losh   luaH_resize(L, t, asize, totaluse - na);
6178e3e3a7aSWarner Losh }
6188e3e3a7aSWarner Losh 
6198e3e3a7aSWarner Losh 
6208e3e3a7aSWarner Losh 
6218e3e3a7aSWarner Losh /*
6228e3e3a7aSWarner Losh ** }=============================================================
6238e3e3a7aSWarner Losh */
6248e3e3a7aSWarner Losh 
6258e3e3a7aSWarner Losh 
luaH_new(lua_State * L)6268e3e3a7aSWarner Losh Table *luaH_new (lua_State *L) {
6270495ed39SKyle Evans   GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
6288e3e3a7aSWarner Losh   Table *t = gco2t(o);
6298e3e3a7aSWarner Losh   t->metatable = NULL;
6300495ed39SKyle Evans   t->flags = cast_byte(maskflags);  /* table has no metamethod fields */
6318e3e3a7aSWarner Losh   t->array = NULL;
6320495ed39SKyle Evans   t->alimit = 0;
6338e3e3a7aSWarner Losh   setnodevector(L, t, 0);
6348e3e3a7aSWarner Losh   return t;
6358e3e3a7aSWarner Losh }
6368e3e3a7aSWarner Losh 
6378e3e3a7aSWarner Losh 
luaH_free(lua_State * L,Table * t)6388e3e3a7aSWarner Losh void luaH_free (lua_State *L, Table *t) {
6390495ed39SKyle Evans   freehash(L, t);
6400495ed39SKyle Evans   luaM_freearray(L, t->array, luaH_realasize(t));
6418e3e3a7aSWarner Losh   luaM_free(L, t);
6428e3e3a7aSWarner Losh }
6438e3e3a7aSWarner Losh 
6448e3e3a7aSWarner Losh 
getfreepos(Table * t)6458e3e3a7aSWarner Losh static Node *getfreepos (Table *t) {
6468e3e3a7aSWarner Losh   if (!isdummy(t)) {
6478e3e3a7aSWarner Losh     while (t->lastfree > t->node) {
6488e3e3a7aSWarner Losh       t->lastfree--;
6490495ed39SKyle Evans       if (keyisnil(t->lastfree))
6508e3e3a7aSWarner Losh         return t->lastfree;
6518e3e3a7aSWarner Losh     }
6528e3e3a7aSWarner Losh   }
6538e3e3a7aSWarner Losh   return NULL;  /* could not find a free place */
6548e3e3a7aSWarner Losh }
6558e3e3a7aSWarner Losh 
6568e3e3a7aSWarner Losh 
6578e3e3a7aSWarner Losh 
6588e3e3a7aSWarner Losh /*
6598e3e3a7aSWarner Losh ** inserts a new key into a hash table; first, check whether key's main
6608e3e3a7aSWarner Losh ** position is free. If not, check whether colliding node is in its main
6618e3e3a7aSWarner Losh ** position or not: if it is not, move colliding node to an empty place and
6628e3e3a7aSWarner Losh ** put new key in its main position; otherwise (colliding node is in its main
6638e3e3a7aSWarner Losh ** position), new key goes to an empty position.
6648e3e3a7aSWarner Losh */
luaH_newkey(lua_State * L,Table * t,const TValue * key,TValue * value)6658c784bb8SWarner Losh void luaH_newkey (lua_State *L, Table *t, const TValue *key, TValue *value) {
6668e3e3a7aSWarner Losh   Node *mp;
6678e3e3a7aSWarner Losh   TValue aux;
6688c784bb8SWarner Losh   if (l_unlikely(ttisnil(key)))
6690495ed39SKyle Evans     luaG_runerror(L, "table index is nil");
6708e3e3a7aSWarner Losh   else if (ttisfloat(key)) {
6710495ed39SKyle Evans     lua_Number f = fltvalue(key);
6728e3e3a7aSWarner Losh     lua_Integer k;
6730495ed39SKyle Evans     if (luaV_flttointeger(f, &k, F2Ieq)) {  /* does key fit in an integer? */
6748e3e3a7aSWarner Losh       setivalue(&aux, k);
6758e3e3a7aSWarner Losh       key = &aux;  /* insert it as an integer */
6768e3e3a7aSWarner Losh     }
6778c784bb8SWarner Losh     else if (l_unlikely(luai_numisnan(f)))
6788e3e3a7aSWarner Losh       luaG_runerror(L, "table index is NaN");
6798e3e3a7aSWarner Losh   }
6808c784bb8SWarner Losh   if (ttisnil(value))
6818c784bb8SWarner Losh     return;  /* do not insert nil values */
6820495ed39SKyle Evans   mp = mainpositionTV(t, key);
6830495ed39SKyle Evans   if (!isempty(gval(mp)) || isdummy(t)) {  /* main position is taken? */
6848e3e3a7aSWarner Losh     Node *othern;
6858e3e3a7aSWarner Losh     Node *f = getfreepos(t);  /* get a free place */
6868e3e3a7aSWarner Losh     if (f == NULL) {  /* cannot find a free place? */
6878e3e3a7aSWarner Losh       rehash(L, t, key);  /* grow table */
6888e3e3a7aSWarner Losh       /* whatever called 'newkey' takes care of TM cache */
6898c784bb8SWarner Losh       luaH_set(L, t, key, value);  /* insert key into grown table */
6908c784bb8SWarner Losh       return;
6918e3e3a7aSWarner Losh     }
6928e3e3a7aSWarner Losh     lua_assert(!isdummy(t));
6938c784bb8SWarner Losh     othern = mainpositionfromnode(t, mp);
6948e3e3a7aSWarner Losh     if (othern != mp) {  /* is colliding node out of its main position? */
6958e3e3a7aSWarner Losh       /* yes; move colliding node into free position */
6968e3e3a7aSWarner Losh       while (othern + gnext(othern) != mp)  /* find previous */
6978e3e3a7aSWarner Losh         othern += gnext(othern);
6988e3e3a7aSWarner Losh       gnext(othern) = cast_int(f - othern);  /* rechain to point to 'f' */
6998e3e3a7aSWarner Losh       *f = *mp;  /* copy colliding node into free pos. (mp->next also goes) */
7008e3e3a7aSWarner Losh       if (gnext(mp) != 0) {
7018e3e3a7aSWarner Losh         gnext(f) += cast_int(mp - f);  /* correct 'next' */
7028e3e3a7aSWarner Losh         gnext(mp) = 0;  /* now 'mp' is free */
7038e3e3a7aSWarner Losh       }
7040495ed39SKyle Evans       setempty(gval(mp));
7058e3e3a7aSWarner Losh     }
7068e3e3a7aSWarner Losh     else {  /* colliding node is in its own main position */
7078e3e3a7aSWarner Losh       /* new node will go into free position */
7088e3e3a7aSWarner Losh       if (gnext(mp) != 0)
7098e3e3a7aSWarner Losh         gnext(f) = cast_int((mp + gnext(mp)) - f);  /* chain new position */
7108e3e3a7aSWarner Losh       else lua_assert(gnext(f) == 0);
7118e3e3a7aSWarner Losh       gnext(mp) = cast_int(f - mp);
7128e3e3a7aSWarner Losh       mp = f;
7138e3e3a7aSWarner Losh     }
7148e3e3a7aSWarner Losh   }
7150495ed39SKyle Evans   setnodekey(L, mp, key);
7160495ed39SKyle Evans   luaC_barrierback(L, obj2gco(t), key);
7170495ed39SKyle Evans   lua_assert(isempty(gval(mp)));
7188c784bb8SWarner Losh   setobj2t(L, gval(mp), value);
7198e3e3a7aSWarner Losh }
7208e3e3a7aSWarner Losh 
7218e3e3a7aSWarner Losh 
7228e3e3a7aSWarner Losh /*
7230495ed39SKyle Evans ** Search function for integers. If integer is inside 'alimit', get it
7240495ed39SKyle Evans ** directly from the array part. Otherwise, if 'alimit' is not equal to
7250495ed39SKyle Evans ** the real size of the array, key still can be in the array part. In
7260495ed39SKyle Evans ** this case, try to avoid a call to 'luaH_realasize' when key is just
7270495ed39SKyle Evans ** one more than the limit (so that it can be incremented without
7280495ed39SKyle Evans ** changing the real size of the array).
7298e3e3a7aSWarner Losh */
luaH_getint(Table * t,lua_Integer key)7308e3e3a7aSWarner Losh const TValue *luaH_getint (Table *t, lua_Integer key) {
7310495ed39SKyle Evans   if (l_castS2U(key) - 1u < t->alimit)  /* 'key' in [1, t->alimit]? */
7328e3e3a7aSWarner Losh     return &t->array[key - 1];
7330495ed39SKyle Evans   else if (!limitequalsasize(t) &&  /* key still may be in the array part? */
7340495ed39SKyle Evans            (l_castS2U(key) == t->alimit + 1 ||
7350495ed39SKyle Evans             l_castS2U(key) - 1u < luaH_realasize(t))) {
7360495ed39SKyle Evans     t->alimit = cast_uint(key);  /* probably '#t' is here now */
7370495ed39SKyle Evans     return &t->array[key - 1];
7380495ed39SKyle Evans   }
7398e3e3a7aSWarner Losh   else {
7408e3e3a7aSWarner Losh     Node *n = hashint(t, key);
7418e3e3a7aSWarner Losh     for (;;) {  /* check whether 'key' is somewhere in the chain */
7420495ed39SKyle Evans       if (keyisinteger(n) && keyival(n) == key)
7438e3e3a7aSWarner Losh         return gval(n);  /* that's it */
7448e3e3a7aSWarner Losh       else {
7458e3e3a7aSWarner Losh         int nx = gnext(n);
7468e3e3a7aSWarner Losh         if (nx == 0) break;
7478e3e3a7aSWarner Losh         n += nx;
7488e3e3a7aSWarner Losh       }
7498e3e3a7aSWarner Losh     }
7500495ed39SKyle Evans     return &absentkey;
7518e3e3a7aSWarner Losh   }
7528e3e3a7aSWarner Losh }
7538e3e3a7aSWarner Losh 
7548e3e3a7aSWarner Losh 
7558e3e3a7aSWarner Losh /*
7568e3e3a7aSWarner Losh ** search function for short strings
7578e3e3a7aSWarner Losh */
luaH_getshortstr(Table * t,TString * key)7588e3e3a7aSWarner Losh const TValue *luaH_getshortstr (Table *t, TString *key) {
7598e3e3a7aSWarner Losh   Node *n = hashstr(t, key);
7600495ed39SKyle Evans   lua_assert(key->tt == LUA_VSHRSTR);
7618e3e3a7aSWarner Losh   for (;;) {  /* check whether 'key' is somewhere in the chain */
7620495ed39SKyle Evans     if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
7638e3e3a7aSWarner Losh       return gval(n);  /* that's it */
7648e3e3a7aSWarner Losh     else {
7658e3e3a7aSWarner Losh       int nx = gnext(n);
7668e3e3a7aSWarner Losh       if (nx == 0)
7670495ed39SKyle Evans         return &absentkey;  /* not found */
7688e3e3a7aSWarner Losh       n += nx;
7698e3e3a7aSWarner Losh     }
7708e3e3a7aSWarner Losh   }
7718e3e3a7aSWarner Losh }
7728e3e3a7aSWarner Losh 
7738e3e3a7aSWarner Losh 
luaH_getstr(Table * t,TString * key)7748e3e3a7aSWarner Losh const TValue *luaH_getstr (Table *t, TString *key) {
7750495ed39SKyle Evans   if (key->tt == LUA_VSHRSTR)
7768e3e3a7aSWarner Losh     return luaH_getshortstr(t, key);
7778e3e3a7aSWarner Losh   else {  /* for long strings, use generic case */
7788e3e3a7aSWarner Losh     TValue ko;
7798e3e3a7aSWarner Losh     setsvalue(cast(lua_State *, NULL), &ko, key);
7800495ed39SKyle Evans     return getgeneric(t, &ko, 0);
7818e3e3a7aSWarner Losh   }
7828e3e3a7aSWarner Losh }
7838e3e3a7aSWarner Losh 
7848e3e3a7aSWarner Losh 
7858e3e3a7aSWarner Losh /*
7868e3e3a7aSWarner Losh ** main search function
7878e3e3a7aSWarner Losh */
luaH_get(Table * t,const TValue * key)7888e3e3a7aSWarner Losh const TValue *luaH_get (Table *t, const TValue *key) {
7890495ed39SKyle Evans   switch (ttypetag(key)) {
7900495ed39SKyle Evans     case LUA_VSHRSTR: return luaH_getshortstr(t, tsvalue(key));
7910495ed39SKyle Evans     case LUA_VNUMINT: return luaH_getint(t, ivalue(key));
7920495ed39SKyle Evans     case LUA_VNIL: return &absentkey;
7930495ed39SKyle Evans     case LUA_VNUMFLT: {
7948e3e3a7aSWarner Losh       lua_Integer k;
7950495ed39SKyle Evans       if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
7968e3e3a7aSWarner Losh         return luaH_getint(t, k);  /* use specialized version */
7978e3e3a7aSWarner Losh       /* else... */
7988e3e3a7aSWarner Losh     }  /* FALLTHROUGH */
7998e3e3a7aSWarner Losh     default:
8000495ed39SKyle Evans       return getgeneric(t, key, 0);
8018e3e3a7aSWarner Losh   }
8028e3e3a7aSWarner Losh }
8038e3e3a7aSWarner Losh 
8048e3e3a7aSWarner Losh 
8058e3e3a7aSWarner Losh /*
8068c784bb8SWarner Losh ** Finish a raw "set table" operation, where 'slot' is where the value
8078c784bb8SWarner Losh ** should have been (the result of a previous "get table").
8088c784bb8SWarner Losh ** Beware: when using this function you probably need to check a GC
8098c784bb8SWarner Losh ** barrier and invalidate the TM cache.
8108c784bb8SWarner Losh */
luaH_finishset(lua_State * L,Table * t,const TValue * key,const TValue * slot,TValue * value)8118c784bb8SWarner Losh void luaH_finishset (lua_State *L, Table *t, const TValue *key,
8128c784bb8SWarner Losh                                    const TValue *slot, TValue *value) {
8138c784bb8SWarner Losh   if (isabstkey(slot))
8148c784bb8SWarner Losh     luaH_newkey(L, t, key, value);
8158c784bb8SWarner Losh   else
8168c784bb8SWarner Losh     setobj2t(L, cast(TValue *, slot), value);
8178c784bb8SWarner Losh }
8188c784bb8SWarner Losh 
8198c784bb8SWarner Losh 
8208c784bb8SWarner Losh /*
8218e3e3a7aSWarner Losh ** beware: when using this function you probably need to check a GC
8228e3e3a7aSWarner Losh ** barrier and invalidate the TM cache.
8238e3e3a7aSWarner Losh */
luaH_set(lua_State * L,Table * t,const TValue * key,TValue * value)8248c784bb8SWarner Losh void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) {
8258c784bb8SWarner Losh   const TValue *slot = luaH_get(t, key);
8268c784bb8SWarner Losh   luaH_finishset(L, t, key, slot, value);
8278e3e3a7aSWarner Losh }
8288e3e3a7aSWarner Losh 
8298e3e3a7aSWarner Losh 
luaH_setint(lua_State * L,Table * t,lua_Integer key,TValue * value)8308e3e3a7aSWarner Losh void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
8318e3e3a7aSWarner Losh   const TValue *p = luaH_getint(t, key);
8328c784bb8SWarner Losh   if (isabstkey(p)) {
8338e3e3a7aSWarner Losh     TValue k;
8348e3e3a7aSWarner Losh     setivalue(&k, key);
8358c784bb8SWarner Losh     luaH_newkey(L, t, &k, value);
8368e3e3a7aSWarner Losh   }
8378c784bb8SWarner Losh   else
8388c784bb8SWarner Losh     setobj2t(L, cast(TValue *, p), value);
8398e3e3a7aSWarner Losh }
8408e3e3a7aSWarner Losh 
8418e3e3a7aSWarner Losh 
8420495ed39SKyle Evans /*
8430495ed39SKyle Evans ** Try to find a boundary in the hash part of table 't'. From the
8440495ed39SKyle Evans ** caller, we know that 'j' is zero or present and that 'j + 1' is
8450495ed39SKyle Evans ** present. We want to find a larger key that is absent from the
8460495ed39SKyle Evans ** table, so that we can do a binary search between the two keys to
8470495ed39SKyle Evans ** find a boundary. We keep doubling 'j' until we get an absent index.
8480495ed39SKyle Evans ** If the doubling would overflow, we try LUA_MAXINTEGER. If it is
8490495ed39SKyle Evans ** absent, we are ready for the binary search. ('j', being max integer,
8500495ed39SKyle Evans ** is larger or equal to 'i', but it cannot be equal because it is
8510495ed39SKyle Evans ** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a
8520495ed39SKyle Evans ** boundary. ('j + 1' cannot be a present integer key because it is
8530495ed39SKyle Evans ** not a valid integer in Lua.)
8540495ed39SKyle Evans */
hash_search(Table * t,lua_Unsigned j)8550495ed39SKyle Evans static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
8560495ed39SKyle Evans   lua_Unsigned i;
8570495ed39SKyle Evans   if (j == 0) j++;  /* the caller ensures 'j + 1' is present */
8580495ed39SKyle Evans   do {
8590495ed39SKyle Evans     i = j;  /* 'i' is a present index */
8600495ed39SKyle Evans     if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
8618e3e3a7aSWarner Losh       j *= 2;
8620495ed39SKyle Evans     else {
8630495ed39SKyle Evans       j = LUA_MAXINTEGER;
8640495ed39SKyle Evans       if (isempty(luaH_getint(t, j)))  /* t[j] not present? */
8650495ed39SKyle Evans         break;  /* 'j' now is an absent index */
8660495ed39SKyle Evans       else  /* weird case */
8670495ed39SKyle Evans         return j;  /* well, max integer is a boundary... */
8688e3e3a7aSWarner Losh     }
8690495ed39SKyle Evans   } while (!isempty(luaH_getint(t, j)));  /* repeat until an absent t[j] */
8700495ed39SKyle Evans   /* i < j  &&  t[i] present  &&  t[j] absent */
8710495ed39SKyle Evans   while (j - i > 1u) {  /* do a binary search between them */
872e112e9d2SKyle Evans     lua_Unsigned m = (i + j) / 2;
8730495ed39SKyle Evans     if (isempty(luaH_getint(t, m))) j = m;
8740495ed39SKyle Evans     else i = m;
8750495ed39SKyle Evans   }
8760495ed39SKyle Evans   return i;
8770495ed39SKyle Evans }
8780495ed39SKyle Evans 
8790495ed39SKyle Evans 
binsearch(const TValue * array,unsigned int i,unsigned int j)8800495ed39SKyle Evans static unsigned int binsearch (const TValue *array, unsigned int i,
8810495ed39SKyle Evans                                                     unsigned int j) {
8820495ed39SKyle Evans   while (j - i > 1u) {  /* binary search */
8830495ed39SKyle Evans     unsigned int m = (i + j) / 2;
8840495ed39SKyle Evans     if (isempty(&array[m - 1])) j = m;
8858e3e3a7aSWarner Losh     else i = m;
8868e3e3a7aSWarner Losh   }
8878e3e3a7aSWarner Losh   return i;
8888e3e3a7aSWarner Losh }
8898e3e3a7aSWarner Losh 
8908e3e3a7aSWarner Losh 
8918e3e3a7aSWarner Losh /*
8920495ed39SKyle Evans ** Try to find a boundary in table 't'. (A 'boundary' is an integer index
8930495ed39SKyle Evans ** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent
8940495ed39SKyle Evans ** and 'maxinteger' if t[maxinteger] is present.)
8950495ed39SKyle Evans ** (In the next explanation, we use Lua indices, that is, with base 1.
8960495ed39SKyle Evans ** The code itself uses base 0 when indexing the array part of the table.)
8970495ed39SKyle Evans ** The code starts with 'limit = t->alimit', a position in the array
8980495ed39SKyle Evans ** part that may be a boundary.
8990495ed39SKyle Evans **
9000495ed39SKyle Evans ** (1) If 't[limit]' is empty, there must be a boundary before it.
9010495ed39SKyle Evans ** As a common case (e.g., after 't[#t]=nil'), check whether 'limit-1'
9020495ed39SKyle Evans ** is present. If so, it is a boundary. Otherwise, do a binary search
9030495ed39SKyle Evans ** between 0 and limit to find a boundary. In both cases, try to
9040495ed39SKyle Evans ** use this boundary as the new 'alimit', as a hint for the next call.
9050495ed39SKyle Evans **
9060495ed39SKyle Evans ** (2) If 't[limit]' is not empty and the array has more elements
9070495ed39SKyle Evans ** after 'limit', try to find a boundary there. Again, try first
9080495ed39SKyle Evans ** the special case (which should be quite frequent) where 'limit+1'
9090495ed39SKyle Evans ** is empty, so that 'limit' is a boundary. Otherwise, check the
9100495ed39SKyle Evans ** last element of the array part. If it is empty, there must be a
9110495ed39SKyle Evans ** boundary between the old limit (present) and the last element
9120495ed39SKyle Evans ** (absent), which is found with a binary search. (This boundary always
9130495ed39SKyle Evans ** can be a new limit.)
9140495ed39SKyle Evans **
9150495ed39SKyle Evans ** (3) The last case is when there are no elements in the array part
9160495ed39SKyle Evans ** (limit == 0) or its last element (the new limit) is present.
9170495ed39SKyle Evans ** In this case, must check the hash part. If there is no hash part
9180495ed39SKyle Evans ** or 'limit+1' is absent, 'limit' is a boundary.  Otherwise, call
9190495ed39SKyle Evans ** 'hash_search' to find a boundary in the hash part of the table.
9200495ed39SKyle Evans ** (In those cases, the boundary is not inside the array part, and
9210495ed39SKyle Evans ** therefore cannot be used as a new limit.)
9228e3e3a7aSWarner Losh */
luaH_getn(Table * t)923e112e9d2SKyle Evans lua_Unsigned luaH_getn (Table *t) {
9240495ed39SKyle Evans   unsigned int limit = t->alimit;
9250495ed39SKyle Evans   if (limit > 0 && isempty(&t->array[limit - 1])) {  /* (1)? */
9260495ed39SKyle Evans     /* there must be a boundary before 'limit' */
9270495ed39SKyle Evans     if (limit >= 2 && !isempty(&t->array[limit - 2])) {
9280495ed39SKyle Evans       /* 'limit - 1' is a boundary; can it be a new limit? */
9290495ed39SKyle Evans       if (ispow2realasize(t) && !ispow2(limit - 1)) {
9300495ed39SKyle Evans         t->alimit = limit - 1;
9310495ed39SKyle Evans         setnorealasize(t);  /* now 'alimit' is not the real size */
9328e3e3a7aSWarner Losh       }
9330495ed39SKyle Evans       return limit - 1;
9348e3e3a7aSWarner Losh     }
9350495ed39SKyle Evans     else {  /* must search for a boundary in [0, limit] */
9360495ed39SKyle Evans       unsigned int boundary = binsearch(t->array, 0, limit);
9370495ed39SKyle Evans       /* can this boundary represent the real size of the array? */
9380495ed39SKyle Evans       if (ispow2realasize(t) && boundary > luaH_realasize(t) / 2) {
9390495ed39SKyle Evans         t->alimit = boundary;  /* use it as the new limit */
9400495ed39SKyle Evans         setnorealasize(t);
9410495ed39SKyle Evans       }
9420495ed39SKyle Evans       return boundary;
9430495ed39SKyle Evans     }
9440495ed39SKyle Evans   }
9450495ed39SKyle Evans   /* 'limit' is zero or present in table */
9460495ed39SKyle Evans   if (!limitequalsasize(t)) {  /* (2)? */
9470495ed39SKyle Evans     /* 'limit' > 0 and array has more elements after 'limit' */
9480495ed39SKyle Evans     if (isempty(&t->array[limit]))  /* 'limit + 1' is empty? */
9490495ed39SKyle Evans       return limit;  /* this is the boundary */
9500495ed39SKyle Evans     /* else, try last element in the array */
9510495ed39SKyle Evans     limit = luaH_realasize(t);
9520495ed39SKyle Evans     if (isempty(&t->array[limit - 1])) {  /* empty? */
9530495ed39SKyle Evans       /* there must be a boundary in the array after old limit,
9540495ed39SKyle Evans          and it must be a valid new limit */
9550495ed39SKyle Evans       unsigned int boundary = binsearch(t->array, t->alimit, limit);
9560495ed39SKyle Evans       t->alimit = boundary;
9570495ed39SKyle Evans       return boundary;
9580495ed39SKyle Evans     }
9590495ed39SKyle Evans     /* else, new limit is present in the table; check the hash part */
9600495ed39SKyle Evans   }
9610495ed39SKyle Evans   /* (3) 'limit' is the last element and either is zero or present in table */
9620495ed39SKyle Evans   lua_assert(limit == luaH_realasize(t) &&
9630495ed39SKyle Evans              (limit == 0 || !isempty(&t->array[limit - 1])));
9640495ed39SKyle Evans   if (isdummy(t) || isempty(luaH_getint(t, cast(lua_Integer, limit + 1))))
9650495ed39SKyle Evans     return limit;  /* 'limit + 1' is absent */
9660495ed39SKyle Evans   else  /* 'limit + 1' is also present */
9670495ed39SKyle Evans     return hash_search(t, limit);
9688e3e3a7aSWarner Losh }
9698e3e3a7aSWarner Losh 
9708e3e3a7aSWarner Losh 
9718e3e3a7aSWarner Losh 
9728e3e3a7aSWarner Losh #if defined(LUA_DEBUG)
9738e3e3a7aSWarner Losh 
9740495ed39SKyle Evans /* export these functions for the test library */
9750495ed39SKyle Evans 
luaH_mainposition(const Table * t,const TValue * key)9768e3e3a7aSWarner Losh Node *luaH_mainposition (const Table *t, const TValue *key) {
9770495ed39SKyle Evans   return mainpositionTV(t, key);
9788e3e3a7aSWarner Losh }
9798e3e3a7aSWarner Losh 
9808e3e3a7aSWarner Losh #endif
981