/*1** $Id: ltable.c $2** Lua tables (hash)3** See Copyright Notice in lua.h4*/56#define ltable_c7#define LUA_CORE89#include "lprefix.h"101112/*13** Implementation of tables (aka arrays, objects, or hash tables).14** Tables keep its elements in two parts: an array part and a hash part.15** Non-negative integer keys are all candidates to be kept in the array16** part. The actual size of the array is the largest 'n' such that17** more than half the slots between 1 and n are in use.18** Hash uses a mix of chained scatter table with Brent's variation.19** A main invariant of these tables is that, if an element is not20** in its main position (i.e. the 'original' position that its hash gives21** to it), then the colliding element is in its own main position.22** Hence even when the load factor reaches 100%, performance remains good.23*/2425#include <math.h>26#include <limits.h>2728#include "lua.h"2930#include "ldebug.h"31#include "ldo.h"32#include "lgc.h"33#include "lmem.h"34#include "lobject.h"35#include "lstate.h"36#include "lstring.h"37#include "ltable.h"38#include "lvm.h"394041/*42** MAXABITS is the largest integer such that MAXASIZE fits in an43** unsigned int.44*/45#define MAXABITS cast_int(sizeof(int) * CHAR_BIT - 1)464748/*49** MAXASIZE is the maximum size of the array part. It is the minimum50** between 2^MAXABITS and the maximum size that, measured in bytes,51** fits in a 'size_t'.52*/53#define MAXASIZE luaM_limitN(1u << MAXABITS, TValue)5455/*56** MAXHBITS is the largest integer such that 2^MAXHBITS fits in a57** signed int.58*/59#define MAXHBITS (MAXABITS - 1)606162/*63** MAXHSIZE is the maximum size of the hash part. It is the minimum64** between 2^MAXHBITS and the maximum size such that, measured in bytes,65** it fits in a 'size_t'.66*/67#define MAXHSIZE luaM_limitN(1u << MAXHBITS, Node)686970/*71** When the original hash value is good, hashing by a power of 272** avoids the cost of '%'.73*/74#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))7576/*77** for other types, it is better to avoid modulo by power of 2, as78** they can have many 2 factors.79*/80#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))818283#define hashstr(t,str) hashpow2(t, (str)->hash)84#define hashboolean(t,p) hashpow2(t, p)858687#define hashpointer(t,p) hashmod(t, point2uint(p))888990#define dummynode (&dummynode_)9192static const Node dummynode_ = {93{{NULL}, LUA_VEMPTY, /* value's value and type */94LUA_VNIL, 0, {NULL}} /* key type, next, and key value */95};969798static const TValue absentkey = {ABSTKEYCONSTANT};99100101/*102** Hash for integers. To allow a good hash, use the remainder operator103** ('%'). If integer fits as a non-negative int, compute an int104** remainder, which is faster. Otherwise, use an unsigned-integer105** remainder, which uses all bits and ensures a non-negative result.106*/107static Node *hashint (const Table *t, lua_Integer i) {108lua_Unsigned ui = l_castS2U(i);109if (ui <= cast_uint(INT_MAX))110return hashmod(t, cast_int(ui));111else112return hashmod(t, ui);113}114115116/*117** Hash for floating-point numbers.118** The main computation should be just119** n = frexp(n, &i); return (n * INT_MAX) + i120** but there are some numerical subtleties.121** In a two-complement representation, INT_MAX does not has an exact122** representation as a float, but INT_MIN does; because the absolute123** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the124** absolute value of the product 'frexp * -INT_MIN' is smaller or equal125** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when126** adding 'i'; the use of '~u' (instead of '-u') avoids problems with127** INT_MIN.128*/129#if !defined(l_hashfloat)130static int l_hashfloat (lua_Number n) {131int i;132lua_Integer ni;133n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN);134if (!lua_numbertointeger(n, &ni)) { /* is 'n' inf/-inf/NaN? */135lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL));136return 0;137}138else { /* normal case */139unsigned int u = cast_uint(i) + cast_uint(ni);140return cast_int(u <= cast_uint(INT_MAX) ? u : ~u);141}142}143#endif144145146/*147** returns the 'main' position of an element in a table (that is,148** the index of its hash value).149*/150static Node *mainpositionTV (const Table *t, const TValue *key) {151switch (ttypetag(key)) {152case LUA_VNUMINT: {153lua_Integer i = ivalue(key);154return hashint(t, i);155}156case LUA_VNUMFLT: {157lua_Number n = fltvalue(key);158return hashmod(t, l_hashfloat(n));159}160case LUA_VSHRSTR: {161TString *ts = tsvalue(key);162return hashstr(t, ts);163}164case LUA_VLNGSTR: {165TString *ts = tsvalue(key);166return hashpow2(t, luaS_hashlongstr(ts));167}168case LUA_VFALSE:169return hashboolean(t, 0);170case LUA_VTRUE:171return hashboolean(t, 1);172case LUA_VLIGHTUSERDATA: {173void *p = pvalue(key);174return hashpointer(t, p);175}176case LUA_VLCF: {177lua_CFunction f = fvalue(key);178return hashpointer(t, f);179}180default: {181GCObject *o = gcvalue(key);182return hashpointer(t, o);183}184}185}186187188l_sinline Node *mainpositionfromnode (const Table *t, Node *nd) {189TValue key;190getnodekey(cast(lua_State *, NULL), &key, nd);191return mainpositionTV(t, &key);192}193194195/*196** Check whether key 'k1' is equal to the key in node 'n2'. This197** equality is raw, so there are no metamethods. Floats with integer198** values have been normalized, so integers cannot be equal to199** floats. It is assumed that 'eqshrstr' is simply pointer equality, so200** that short strings are handled in the default case.201** A true 'deadok' means to accept dead keys as equal to their original202** values. All dead keys are compared in the default case, by pointer203** identity. (Only collectable objects can produce dead keys.) Note that204** dead long strings are also compared by identity.205** Once a key is dead, its corresponding value may be collected, and206** then another value can be created with the same address. If this207** other value is given to 'next', 'equalkey' will signal a false208** positive. In a regular traversal, this situation should never happen,209** as all keys given to 'next' came from the table itself, and therefore210** could not have been collected. Outside a regular traversal, we211** have garbage in, garbage out. What is relevant is that this false212** positive does not break anything. (In particular, 'next' will return213** some other valid item on the table or nil.)214*/215static int equalkey (const TValue *k1, const Node *n2, int deadok) {216if ((rawtt(k1) != keytt(n2)) && /* not the same variants? */217!(deadok && keyisdead(n2) && iscollectable(k1)))218return 0; /* cannot be same key */219switch (keytt(n2)) {220case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE:221return 1;222case LUA_VNUMINT:223return (ivalue(k1) == keyival(n2));224case LUA_VNUMFLT:225return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2)));226case LUA_VLIGHTUSERDATA:227return pvalue(k1) == pvalueraw(keyval(n2));228case LUA_VLCF:229return fvalue(k1) == fvalueraw(keyval(n2));230case ctb(LUA_VLNGSTR):231return luaS_eqlngstr(tsvalue(k1), keystrval(n2));232default:233return gcvalue(k1) == gcvalueraw(keyval(n2));234}235}236237238/*239** True if value of 'alimit' is equal to the real size of the array240** part of table 't'. (Otherwise, the array part must be larger than241** 'alimit'.)242*/243#define limitequalsasize(t) (isrealasize(t) || ispow2((t)->alimit))244245246/*247** Returns the real size of the 'array' array248*/249LUAI_FUNC unsigned int luaH_realasize (const Table *t) {250if (limitequalsasize(t))251return t->alimit; /* this is the size */252else {253unsigned int size = t->alimit;254/* compute the smallest power of 2 not smaller than 'size' */255size |= (size >> 1);256size |= (size >> 2);257size |= (size >> 4);258size |= (size >> 8);259#if (UINT_MAX >> 14) > 3 /* unsigned int has more than 16 bits */260size |= (size >> 16);261#if (UINT_MAX >> 30) > 3262size |= (size >> 32); /* unsigned int has more than 32 bits */263#endif264#endif265size++;266lua_assert(ispow2(size) && size/2 < t->alimit && t->alimit < size);267return size;268}269}270271272/*273** Check whether real size of the array is a power of 2.274** (If it is not, 'alimit' cannot be changed to any other value275** without changing the real size.)276*/277static int ispow2realasize (const Table *t) {278return (!isrealasize(t) || ispow2(t->alimit));279}280281282static unsigned int setlimittosize (Table *t) {283t->alimit = luaH_realasize(t);284setrealasize(t);285return t->alimit;286}287288289#define limitasasize(t) check_exp(isrealasize(t), t->alimit)290291292293/*294** "Generic" get version. (Not that generic: not valid for integers,295** which may be in array part, nor for floats with integral values.)296** See explanation about 'deadok' in function 'equalkey'.297*/298static const TValue *getgeneric (Table *t, const TValue *key, int deadok) {299Node *n = mainpositionTV(t, key);300for (;;) { /* check whether 'key' is somewhere in the chain */301if (equalkey(key, n, deadok))302return gval(n); /* that's it */303else {304int nx = gnext(n);305if (nx == 0)306return &absentkey; /* not found */307n += nx;308}309}310}311312313/*314** returns the index for 'k' if 'k' is an appropriate key to live in315** the array part of a table, 0 otherwise.316*/317static unsigned int arrayindex (lua_Integer k) {318if (l_castS2U(k) - 1u < MAXASIZE) /* 'k' in [1, MAXASIZE]? */319return cast_uint(k); /* 'key' is an appropriate array index */320else321return 0;322}323324325/*326** returns the index of a 'key' for table traversals. First goes all327** elements in the array part, then elements in the hash part. The328** beginning of a traversal is signaled by 0.329*/330static unsigned int findindex (lua_State *L, Table *t, TValue *key,331unsigned int asize) {332unsigned int i;333if (ttisnil(key)) return 0; /* first iteration */334i = ttisinteger(key) ? arrayindex(ivalue(key)) : 0;335if (i - 1u < asize) /* is 'key' inside array part? */336return i; /* yes; that's the index */337else {338const TValue *n = getgeneric(t, key, 1);339if (l_unlikely(isabstkey(n)))340luaG_runerror(L, "invalid key to 'next'"); /* key not found */341i = cast_int(nodefromval(n) - gnode(t, 0)); /* key index in hash table */342/* hash elements are numbered after array ones */343return (i + 1) + asize;344}345}346347348int luaH_next (lua_State *L, Table *t, StkId key) {349unsigned int asize = luaH_realasize(t);350unsigned int i = findindex(L, t, s2v(key), asize); /* find original key */351for (; i < asize; i++) { /* try first array part */352if (!isempty(&t->array[i])) { /* a non-empty entry? */353setivalue(s2v(key), i + 1);354setobj2s(L, key + 1, &t->array[i]);355return 1;356}357}358for (i -= asize; cast_int(i) < sizenode(t); i++) { /* hash part */359if (!isempty(gval(gnode(t, i)))) { /* a non-empty entry? */360Node *n = gnode(t, i);361getnodekey(L, s2v(key), n);362setobj2s(L, key + 1, gval(n));363return 1;364}365}366return 0; /* no more elements */367}368369370static void freehash (lua_State *L, Table *t) {371if (!isdummy(t))372luaM_freearray(L, t->node, cast_sizet(sizenode(t)));373}374375376/*377** {=============================================================378** Rehash379** ==============================================================380*/381382/*383** Compute the optimal size for the array part of table 't'. 'nums' is a384** "count array" where 'nums[i]' is the number of integers in the table385** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of386** integer keys in the table and leaves with the number of keys that387** will go to the array part; return the optimal size. (The condition388** 'twotoi > 0' in the for loop stops the loop if 'twotoi' overflows.)389*/390static unsigned int computesizes (unsigned int nums[], unsigned int *pna) {391int i;392unsigned int twotoi; /* 2^i (candidate for optimal size) */393unsigned int a = 0; /* number of elements smaller than 2^i */394unsigned int na = 0; /* number of elements to go to array part */395unsigned int optimal = 0; /* optimal size for array part */396/* loop while keys can fill more than half of total size */397for (i = 0, twotoi = 1;398twotoi > 0 && *pna > twotoi / 2;399i++, twotoi *= 2) {400a += nums[i];401if (a > twotoi/2) { /* more than half elements present? */402optimal = twotoi; /* optimal size (till now) */403na = a; /* all elements up to 'optimal' will go to array part */404}405}406lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal);407*pna = na;408return optimal;409}410411412static int countint (lua_Integer key, unsigned int *nums) {413unsigned int k = arrayindex(key);414if (k != 0) { /* is 'key' an appropriate array index? */415nums[luaO_ceillog2(k)]++; /* count as such */416return 1;417}418else419return 0;420}421422423/*424** Count keys in array part of table 't': Fill 'nums[i]' with425** number of keys that will go into corresponding slice and return426** total number of non-nil keys.427*/428static unsigned int numusearray (const Table *t, unsigned int *nums) {429int lg;430unsigned int ttlg; /* 2^lg */431unsigned int ause = 0; /* summation of 'nums' */432unsigned int i = 1; /* count to traverse all array keys */433unsigned int asize = limitasasize(t); /* real array size */434/* traverse each slice */435for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {436unsigned int lc = 0; /* counter */437unsigned int lim = ttlg;438if (lim > asize) {439lim = asize; /* adjust upper limit */440if (i > lim)441break; /* no more elements to count */442}443/* count elements in range (2^(lg - 1), 2^lg] */444for (; i <= lim; i++) {445if (!isempty(&t->array[i-1]))446lc++;447}448nums[lg] += lc;449ause += lc;450}451return ause;452}453454455static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) {456int totaluse = 0; /* total number of elements */457int ause = 0; /* elements added to 'nums' (can go to array part) */458int i = sizenode(t);459while (i--) {460Node *n = &t->node[i];461if (!isempty(gval(n))) {462if (keyisinteger(n))463ause += countint(keyival(n), nums);464totaluse++;465}466}467*pna += ause;468return totaluse;469}470471472/*473** Creates an array for the hash part of a table with the given474** size, or reuses the dummy node if size is zero.475** The computation for size overflow is in two steps: the first476** comparison ensures that the shift in the second one does not477** overflow.478*/479static void setnodevector (lua_State *L, Table *t, unsigned int size) {480if (size == 0) { /* no elements to hash part? */481t->node = cast(Node *, dummynode); /* use common 'dummynode' */482t->lsizenode = 0;483t->lastfree = NULL; /* signal that it is using dummy node */484}485else {486int i;487int lsize = luaO_ceillog2(size);488if (lsize > MAXHBITS || (1u << lsize) > MAXHSIZE)489luaG_runerror(L, "table overflow");490size = twoto(lsize);491t->node = luaM_newvector(L, size, Node);492for (i = 0; i < cast_int(size); i++) {493Node *n = gnode(t, i);494gnext(n) = 0;495setnilkey(n);496setempty(gval(n));497}498t->lsizenode = cast_byte(lsize);499t->lastfree = gnode(t, size); /* all positions are free */500}501}502503504/*505** (Re)insert all elements from the hash part of 'ot' into table 't'.506*/507static void reinsert (lua_State *L, Table *ot, Table *t) {508int j;509int size = sizenode(ot);510for (j = 0; j < size; j++) {511Node *old = gnode(ot, j);512if (!isempty(gval(old))) {513/* doesn't need barrier/invalidate cache, as entry was514already present in the table */515TValue k;516getnodekey(L, &k, old);517luaH_set(L, t, &k, gval(old));518}519}520}521522523/*524** Exchange the hash part of 't1' and 't2'.525*/526static void exchangehashpart (Table *t1, Table *t2) {527lu_byte lsizenode = t1->lsizenode;528Node *node = t1->node;529Node *lastfree = t1->lastfree;530t1->lsizenode = t2->lsizenode;531t1->node = t2->node;532t1->lastfree = t2->lastfree;533t2->lsizenode = lsizenode;534t2->node = node;535t2->lastfree = lastfree;536}537538539/*540** Resize table 't' for the new given sizes. Both allocations (for541** the hash part and for the array part) can fail, which creates some542** subtleties. If the first allocation, for the hash part, fails, an543** error is raised and that is it. Otherwise, it copies the elements from544** the shrinking part of the array (if it is shrinking) into the new545** hash. Then it reallocates the array part. If that fails, the table546** is in its original state; the function frees the new hash part and then547** raises the allocation error. Otherwise, it sets the new hash part548** into the table, initializes the new part of the array (if any) with549** nils and reinserts the elements of the old hash back into the new550** parts of the table.551*/552void luaH_resize (lua_State *L, Table *t, unsigned int newasize,553unsigned int nhsize) {554unsigned int i;555Table newt; /* to keep the new hash part */556unsigned int oldasize = setlimittosize(t);557TValue *newarray;558/* create new hash part with appropriate size into 'newt' */559setnodevector(L, &newt, nhsize);560if (newasize < oldasize) { /* will array shrink? */561t->alimit = newasize; /* pretend array has new size... */562exchangehashpart(t, &newt); /* and new hash */563/* re-insert into the new hash the elements from vanishing slice */564for (i = newasize; i < oldasize; i++) {565if (!isempty(&t->array[i]))566luaH_setint(L, t, i + 1, &t->array[i]);567}568t->alimit = oldasize; /* restore current size... */569exchangehashpart(t, &newt); /* and hash (in case of errors) */570}571/* allocate new array */572newarray = luaM_reallocvector(L, t->array, oldasize, newasize, TValue);573if (l_unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */574freehash(L, &newt); /* release new hash part */575luaM_error(L); /* raise error (with array unchanged) */576}577/* allocation ok; initialize new part of the array */578exchangehashpart(t, &newt); /* 't' has the new hash ('newt' has the old) */579t->array = newarray; /* set new array part */580t->alimit = newasize;581for (i = oldasize; i < newasize; i++) /* clear new slice of the array */582setempty(&t->array[i]);583/* re-insert elements from old hash part into new parts */584reinsert(L, &newt, t); /* 'newt' now has the old hash */585freehash(L, &newt); /* free old hash part */586}587588589void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {590int nsize = allocsizenode(t);591luaH_resize(L, t, nasize, nsize);592}593594/*595** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i596*/597static void rehash (lua_State *L, Table *t, const TValue *ek) {598unsigned int asize; /* optimal size for array part */599unsigned int na; /* number of keys in the array part */600unsigned int nums[MAXABITS + 1];601int i;602int totaluse;603for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */604setlimittosize(t);605na = numusearray(t, nums); /* count keys in array part */606totaluse = na; /* all those keys are integer keys */607totaluse += numusehash(t, nums, &na); /* count keys in hash part */608/* count extra key */609if (ttisinteger(ek))610na += countint(ivalue(ek), nums);611totaluse++;612/* compute new size for array part */613asize = computesizes(nums, &na);614/* resize the table to new computed sizes */615luaH_resize(L, t, asize, totaluse - na);616}617618619620/*621** }=============================================================622*/623624625Table *luaH_new (lua_State *L) {626GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));627Table *t = gco2t(o);628t->metatable = NULL;629t->flags = cast_byte(maskflags); /* table has no metamethod fields */630t->array = NULL;631t->alimit = 0;632setnodevector(L, t, 0);633return t;634}635636637void luaH_free (lua_State *L, Table *t) {638freehash(L, t);639luaM_freearray(L, t->array, luaH_realasize(t));640luaM_free(L, t);641}642643644static Node *getfreepos (Table *t) {645if (!isdummy(t)) {646while (t->lastfree > t->node) {647t->lastfree--;648if (keyisnil(t->lastfree))649return t->lastfree;650}651}652return NULL; /* could not find a free place */653}654655656657/*658** inserts a new key into a hash table; first, check whether key's main659** position is free. If not, check whether colliding node is in its main660** position or not: if it is not, move colliding node to an empty place and661** put new key in its main position; otherwise (colliding node is in its main662** position), new key goes to an empty position.663*/664static void luaH_newkey (lua_State *L, Table *t, const TValue *key,665TValue *value) {666Node *mp;667TValue aux;668if (l_unlikely(ttisnil(key)))669luaG_runerror(L, "table index is nil");670else if (ttisfloat(key)) {671lua_Number f = fltvalue(key);672lua_Integer k;673if (luaV_flttointeger(f, &k, F2Ieq)) { /* does key fit in an integer? */674setivalue(&aux, k);675key = &aux; /* insert it as an integer */676}677else if (l_unlikely(luai_numisnan(f)))678luaG_runerror(L, "table index is NaN");679}680if (ttisnil(value))681return; /* do not insert nil values */682mp = mainpositionTV(t, key);683if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */684Node *othern;685Node *f = getfreepos(t); /* get a free place */686if (f == NULL) { /* cannot find a free place? */687rehash(L, t, key); /* grow table */688/* whatever called 'newkey' takes care of TM cache */689luaH_set(L, t, key, value); /* insert key into grown table */690return;691}692lua_assert(!isdummy(t));693othern = mainpositionfromnode(t, mp);694if (othern != mp) { /* is colliding node out of its main position? */695/* yes; move colliding node into free position */696while (othern + gnext(othern) != mp) /* find previous */697othern += gnext(othern);698gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */699*f = *mp; /* copy colliding node into free pos. (mp->next also goes) */700if (gnext(mp) != 0) {701gnext(f) += cast_int(mp - f); /* correct 'next' */702gnext(mp) = 0; /* now 'mp' is free */703}704setempty(gval(mp));705}706else { /* colliding node is in its own main position */707/* new node will go into free position */708if (gnext(mp) != 0)709gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */710else lua_assert(gnext(f) == 0);711gnext(mp) = cast_int(f - mp);712mp = f;713}714}715setnodekey(L, mp, key);716luaC_barrierback(L, obj2gco(t), key);717lua_assert(isempty(gval(mp)));718setobj2t(L, gval(mp), value);719}720721722/*723** Search function for integers. If integer is inside 'alimit', get it724** directly from the array part. Otherwise, if 'alimit' is not725** the real size of the array, the key still can be in the array part.726** In this case, do the "Xmilia trick" to check whether 'key-1' is727** smaller than the real size.728** The trick works as follow: let 'p' be an integer such that729** '2^(p+1) >= alimit > 2^p', or '2^(p+1) > alimit-1 >= 2^p'.730** That is, 2^(p+1) is the real size of the array, and 'p' is the highest731** bit on in 'alimit-1'. What we have to check becomes 'key-1 < 2^(p+1)'.732** We compute '(key-1) & ~(alimit-1)', which we call 'res'; it will733** have the 'p' bit cleared. If the key is outside the array, that is,734** 'key-1 >= 2^(p+1)', then 'res' will have some bit on higher than 'p',735** therefore it will be larger or equal to 'alimit', and the check736** will fail. If 'key-1 < 2^(p+1)', then 'res' has no bit on higher than737** 'p', and as the bit 'p' itself was cleared, 'res' will be smaller738** than 2^p, therefore smaller than 'alimit', and the check succeeds.739** As special cases, when 'alimit' is 0 the condition is trivially false,740** and when 'alimit' is 1 the condition simplifies to 'key-1 < alimit'.741** If key is 0 or negative, 'res' will have its higher bit on, so that742** if cannot be smaller than alimit.743*/744const TValue *luaH_getint (Table *t, lua_Integer key) {745lua_Unsigned alimit = t->alimit;746if (l_castS2U(key) - 1u < alimit) /* 'key' in [1, t->alimit]? */747return &t->array[key - 1];748else if (!isrealasize(t) && /* key still may be in the array part? */749(((l_castS2U(key) - 1u) & ~(alimit - 1u)) < alimit)) {750t->alimit = cast_uint(key); /* probably '#t' is here now */751return &t->array[key - 1];752}753else { /* key is not in the array part; check the hash */754Node *n = hashint(t, key);755for (;;) { /* check whether 'key' is somewhere in the chain */756if (keyisinteger(n) && keyival(n) == key)757return gval(n); /* that's it */758else {759int nx = gnext(n);760if (nx == 0) break;761n += nx;762}763}764return &absentkey;765}766}767768769/*770** search function for short strings771*/772const TValue *luaH_getshortstr (Table *t, TString *key) {773Node *n = hashstr(t, key);774lua_assert(key->tt == LUA_VSHRSTR);775for (;;) { /* check whether 'key' is somewhere in the chain */776if (keyisshrstr(n) && eqshrstr(keystrval(n), key))777return gval(n); /* that's it */778else {779int nx = gnext(n);780if (nx == 0)781return &absentkey; /* not found */782n += nx;783}784}785}786787788const TValue *luaH_getstr (Table *t, TString *key) {789if (key->tt == LUA_VSHRSTR)790return luaH_getshortstr(t, key);791else { /* for long strings, use generic case */792TValue ko;793setsvalue(cast(lua_State *, NULL), &ko, key);794return getgeneric(t, &ko, 0);795}796}797798799/*800** main search function801*/802const TValue *luaH_get (Table *t, const TValue *key) {803switch (ttypetag(key)) {804case LUA_VSHRSTR: return luaH_getshortstr(t, tsvalue(key));805case LUA_VNUMINT: return luaH_getint(t, ivalue(key));806case LUA_VNIL: return &absentkey;807case LUA_VNUMFLT: {808lua_Integer k;809if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */810return luaH_getint(t, k); /* use specialized version */811/* else... */812} /* FALLTHROUGH */813default:814return getgeneric(t, key, 0);815}816}817818819/*820** Finish a raw "set table" operation, where 'slot' is where the value821** should have been (the result of a previous "get table").822** Beware: when using this function you probably need to check a GC823** barrier and invalidate the TM cache.824*/825void luaH_finishset (lua_State *L, Table *t, const TValue *key,826const TValue *slot, TValue *value) {827if (isabstkey(slot))828luaH_newkey(L, t, key, value);829else830setobj2t(L, cast(TValue *, slot), value);831}832833834/*835** beware: when using this function you probably need to check a GC836** barrier and invalidate the TM cache.837*/838void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) {839const TValue *slot = luaH_get(t, key);840luaH_finishset(L, t, key, slot, value);841}842843844void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {845const TValue *p = luaH_getint(t, key);846if (isabstkey(p)) {847TValue k;848setivalue(&k, key);849luaH_newkey(L, t, &k, value);850}851else852setobj2t(L, cast(TValue *, p), value);853}854855856/*857** Try to find a boundary in the hash part of table 't'. From the858** caller, we know that 'j' is zero or present and that 'j + 1' is859** present. We want to find a larger key that is absent from the860** table, so that we can do a binary search between the two keys to861** find a boundary. We keep doubling 'j' until we get an absent index.862** If the doubling would overflow, we try LUA_MAXINTEGER. If it is863** absent, we are ready for the binary search. ('j', being max integer,864** is larger or equal to 'i', but it cannot be equal because it is865** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a866** boundary. ('j + 1' cannot be a present integer key because it is867** not a valid integer in Lua.)868*/869static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {870lua_Unsigned i;871if (j == 0) j++; /* the caller ensures 'j + 1' is present */872do {873i = j; /* 'i' is a present index */874if (j <= l_castS2U(LUA_MAXINTEGER) / 2)875j *= 2;876else {877j = LUA_MAXINTEGER;878if (isempty(luaH_getint(t, j))) /* t[j] not present? */879break; /* 'j' now is an absent index */880else /* weird case */881return j; /* well, max integer is a boundary... */882}883} while (!isempty(luaH_getint(t, j))); /* repeat until an absent t[j] */884/* i < j && t[i] present && t[j] absent */885while (j - i > 1u) { /* do a binary search between them */886lua_Unsigned m = (i + j) / 2;887if (isempty(luaH_getint(t, m))) j = m;888else i = m;889}890return i;891}892893894static unsigned int binsearch (const TValue *array, unsigned int i,895unsigned int j) {896while (j - i > 1u) { /* binary search */897unsigned int m = (i + j) / 2;898if (isempty(&array[m - 1])) j = m;899else i = m;900}901return i;902}903904905/*906** Try to find a boundary in table 't'. (A 'boundary' is an integer index907** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent908** and 'maxinteger' if t[maxinteger] is present.)909** (In the next explanation, we use Lua indices, that is, with base 1.910** The code itself uses base 0 when indexing the array part of the table.)911** The code starts with 'limit = t->alimit', a position in the array912** part that may be a boundary.913**914** (1) If 't[limit]' is empty, there must be a boundary before it.915** As a common case (e.g., after 't[#t]=nil'), check whether 'limit-1'916** is present. If so, it is a boundary. Otherwise, do a binary search917** between 0 and limit to find a boundary. In both cases, try to918** use this boundary as the new 'alimit', as a hint for the next call.919**920** (2) If 't[limit]' is not empty and the array has more elements921** after 'limit', try to find a boundary there. Again, try first922** the special case (which should be quite frequent) where 'limit+1'923** is empty, so that 'limit' is a boundary. Otherwise, check the924** last element of the array part. If it is empty, there must be a925** boundary between the old limit (present) and the last element926** (absent), which is found with a binary search. (This boundary always927** can be a new limit.)928**929** (3) The last case is when there are no elements in the array part930** (limit == 0) or its last element (the new limit) is present.931** In this case, must check the hash part. If there is no hash part932** or 'limit+1' is absent, 'limit' is a boundary. Otherwise, call933** 'hash_search' to find a boundary in the hash part of the table.934** (In those cases, the boundary is not inside the array part, and935** therefore cannot be used as a new limit.)936*/937lua_Unsigned luaH_getn (Table *t) {938unsigned int limit = t->alimit;939if (limit > 0 && isempty(&t->array[limit - 1])) { /* (1)? */940/* there must be a boundary before 'limit' */941if (limit >= 2 && !isempty(&t->array[limit - 2])) {942/* 'limit - 1' is a boundary; can it be a new limit? */943if (ispow2realasize(t) && !ispow2(limit - 1)) {944t->alimit = limit - 1;945setnorealasize(t); /* now 'alimit' is not the real size */946}947return limit - 1;948}949else { /* must search for a boundary in [0, limit] */950unsigned int boundary = binsearch(t->array, 0, limit);951/* can this boundary represent the real size of the array? */952if (ispow2realasize(t) && boundary > luaH_realasize(t) / 2) {953t->alimit = boundary; /* use it as the new limit */954setnorealasize(t);955}956return boundary;957}958}959/* 'limit' is zero or present in table */960if (!limitequalsasize(t)) { /* (2)? */961/* 'limit' > 0 and array has more elements after 'limit' */962if (isempty(&t->array[limit])) /* 'limit + 1' is empty? */963return limit; /* this is the boundary */964/* else, try last element in the array */965limit = luaH_realasize(t);966if (isempty(&t->array[limit - 1])) { /* empty? */967/* there must be a boundary in the array after old limit,968and it must be a valid new limit */969unsigned int boundary = binsearch(t->array, t->alimit, limit);970t->alimit = boundary;971return boundary;972}973/* else, new limit is present in the table; check the hash part */974}975/* (3) 'limit' is the last element and either is zero or present in table */976lua_assert(limit == luaH_realasize(t) &&977(limit == 0 || !isempty(&t->array[limit - 1])));978if (isdummy(t) || isempty(luaH_getint(t, cast(lua_Integer, limit + 1))))979return limit; /* 'limit + 1' is absent */980else /* 'limit + 1' is also present */981return hash_search(t, limit);982}983984985986#if defined(LUA_DEBUG)987988/* export these functions for the test library */989990Node *luaH_mainposition (const Table *t, const TValue *key) {991return mainpositionTV(t, key);992}993994#endif995996997