1/*
2** $Id: ltable.c $
3** Lua tables (hash)
4** See Copyright Notice in lua.h
5*/
6
7#define ltable_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13/*
14** Implementation of tables (aka arrays, objects, or hash tables).
15** Tables keep its elements in two parts: an array part and a hash part.
16** Non-negative integer keys are all candidates to be kept in the array
17** part. The actual size of the array is the largest 'n' such that
18** more than half the slots between 1 and n are in use.
19** Hash uses a mix of chained scatter table with Brent's variation.
20** A main invariant of these tables is that, if an element is not
21** in its main position (i.e. the 'original' position that its hash gives
22** to it), then the colliding element is in its own main position.
23** Hence even when the load factor reaches 100%, performance remains good.
24*/
25
26#include <math.h>
27#include <limits.h>
28
29#include "lua.h"
30
31#include "ldebug.h"
32#include "ldo.h"
33#include "lgc.h"
34#include "lmem.h"
35#include "lobject.h"
36#include "lstate.h"
37#include "lstring.h"
38#include "ltable.h"
39#include "lvm.h"
40
41
42/*
43** MAXABITS is the largest integer such that MAXASIZE fits in an
44** unsigned int.
45*/
46#define MAXABITS	cast_int(sizeof(int) * CHAR_BIT - 1)
47
48
49/*
50** MAXASIZE is the maximum size of the array part. It is the minimum
51** between 2^MAXABITS and the maximum size that, measured in bytes,
52** fits in a 'size_t'.
53*/
54#define MAXASIZE	luaM_limitN(1u << MAXABITS, TValue)
55
56/*
57** MAXHBITS is the largest integer such that 2^MAXHBITS fits in a
58** signed int.
59*/
60#define MAXHBITS	(MAXABITS - 1)
61
62
63/*
64** MAXHSIZE is the maximum size of the hash part. It is the minimum
65** between 2^MAXHBITS and the maximum size such that, measured in bytes,
66** it fits in a 'size_t'.
67*/
68#define MAXHSIZE	luaM_limitN(1u << MAXHBITS, Node)
69
70
71#define hashpow2(t,n)		(gnode(t, lmod((n), sizenode(t))))
72
73#define hashstr(t,str)		hashpow2(t, (str)->hash)
74#define hashboolean(t,p)	hashpow2(t, p)
75#define hashint(t,i)		hashpow2(t, i)
76
77
78/*
79** for some types, it is better to avoid modulus by power of 2, as
80** they tend to have many 2 factors.
81*/
82#define hashmod(t,n)	(gnode(t, ((n) % ((sizenode(t)-1)|1))))
83
84
85#define hashpointer(t,p)	hashmod(t, point2uint(p))
86
87
88#define dummynode		(&dummynode_)
89
90static const Node dummynode_ = {
91  {{NULL}, LUA_VEMPTY,  /* value's value and type */
92   LUA_VNIL, 0, {NULL}}  /* key type, next, and key value */
93};
94
95
96static const TValue absentkey = {ABSTKEYCONSTANT};
97
98
99
100/*
101** Hash for floating-point numbers.
102** The main computation should be just
103**     n = frexp(n, &i); return (n * INT_MAX) + i
104** but there are some numerical subtleties.
105** In a two-complement representation, INT_MAX does not has an exact
106** representation as a float, but INT_MIN does; because the absolute
107** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the
108** absolute value of the product 'frexp * -INT_MIN' is smaller or equal
109** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when
110** adding 'i'; the use of '~u' (instead of '-u') avoids problems with
111** INT_MIN.
112*/
113#if !defined(l_hashfloat)
114static int l_hashfloat (lua_Number n) {
115  int i;
116  lua_Integer ni;
117  n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN);
118  if (!lua_numbertointeger(n, &ni)) {  /* is 'n' inf/-inf/NaN? */
119    lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL));
120    return 0;
121  }
122  else {  /* normal case */
123    unsigned int u = cast_uint(i) + cast_uint(ni);
124    return cast_int(u <= cast_uint(INT_MAX) ? u : ~u);
125  }
126}
127#endif
128
129
130/*
131** returns the 'main' position of an element in a table (that is,
132** the index of its hash value). The key comes broken (tag in 'ktt'
133** and value in 'vkl') so that we can call it on keys inserted into
134** nodes.
135*/
136static Node *mainposition (const Table *t, int ktt, const Value *kvl) {
137  switch (withvariant(ktt)) {
138    case LUA_VNUMINT:
139      return hashint(t, ivalueraw(*kvl));
140    case LUA_VNUMFLT:
141      return hashmod(t, l_hashfloat(fltvalueraw(*kvl)));
142    case LUA_VSHRSTR:
143      return hashstr(t, tsvalueraw(*kvl));
144    case LUA_VLNGSTR:
145      return hashpow2(t, luaS_hashlongstr(tsvalueraw(*kvl)));
146    case LUA_VFALSE:
147      return hashboolean(t, 0);
148    case LUA_VTRUE:
149      return hashboolean(t, 1);
150    case LUA_VLIGHTUSERDATA:
151      return hashpointer(t, pvalueraw(*kvl));
152    case LUA_VLCF:
153      return hashpointer(t, fvalueraw(*kvl));
154    default:
155      return hashpointer(t, gcvalueraw(*kvl));
156  }
157}
158
159
160/*
161** Returns the main position of an element given as a 'TValue'
162*/
163static Node *mainpositionTV (const Table *t, const TValue *key) {
164  return mainposition(t, rawtt(key), valraw(key));
165}
166
167
168/*
169** Check whether key 'k1' is equal to the key in node 'n2'. This
170** equality is raw, so there are no metamethods. Floats with integer
171** values have been normalized, so integers cannot be equal to
172** floats. It is assumed that 'eqshrstr' is simply pointer equality, so
173** that short strings are handled in the default case.
174** A true 'deadok' means to accept dead keys as equal to their original
175** values. All dead keys are compared in the default case, by pointer
176** identity. (Only collectable objects can produce dead keys.) Note that
177** dead long strings are also compared by identity.
178** Once a key is dead, its corresponding value may be collected, and
179** then another value can be created with the same address. If this
180** other value is given to 'next', 'equalkey' will signal a false
181** positive. In a regular traversal, this situation should never happen,
182** as all keys given to 'next' came from the table itself, and therefore
183** could not have been collected. Outside a regular traversal, we
184** have garbage in, garbage out. What is relevant is that this false
185** positive does not break anything.  (In particular, 'next' will return
186** some other valid item on the table or nil.)
187*/
188static int equalkey (const TValue *k1, const Node *n2, int deadok) {
189  if ((rawtt(k1) != keytt(n2)) &&  /* not the same variants? */
190       !(deadok && keyisdead(n2) && iscollectable(k1)))
191   return 0;  /* cannot be same key */
192  switch (keytt(n2)) {
193    case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE:
194      return 1;
195    case LUA_VNUMINT:
196      return (ivalue(k1) == keyival(n2));
197    case LUA_VNUMFLT:
198      return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2)));
199    case LUA_VLIGHTUSERDATA:
200      return pvalue(k1) == pvalueraw(keyval(n2));
201    case LUA_VLCF:
202      return fvalue(k1) == fvalueraw(keyval(n2));
203    case ctb(LUA_VLNGSTR):
204      return luaS_eqlngstr(tsvalue(k1), keystrval(n2));
205    default:
206      return gcvalue(k1) == gcvalueraw(keyval(n2));
207  }
208}
209
210
211/*
212** True if value of 'alimit' is equal to the real size of the array
213** part of table 't'. (Otherwise, the array part must be larger than
214** 'alimit'.)
215*/
216#define limitequalsasize(t)	(isrealasize(t) || ispow2((t)->alimit))
217
218
219/*
220** Returns the real size of the 'array' array
221*/
222LUAI_FUNC unsigned int luaH_realasize (const Table *t) {
223  if (limitequalsasize(t))
224    return t->alimit;  /* this is the size */
225  else {
226    unsigned int size = t->alimit;
227    /* compute the smallest power of 2 not smaller than 'n' */
228    size |= (size >> 1);
229    size |= (size >> 2);
230    size |= (size >> 4);
231    size |= (size >> 8);
232    size |= (size >> 16);
233#if (UINT_MAX >> 30) > 3
234    size |= (size >> 32);  /* unsigned int has more than 32 bits */
235#endif
236    size++;
237    lua_assert(ispow2(size) && size/2 < t->alimit && t->alimit < size);
238    return size;
239  }
240}
241
242
243/*
244** Check whether real size of the array is a power of 2.
245** (If it is not, 'alimit' cannot be changed to any other value
246** without changing the real size.)
247*/
248static int ispow2realasize (const Table *t) {
249  return (!isrealasize(t) || ispow2(t->alimit));
250}
251
252
253static unsigned int setlimittosize (Table *t) {
254  t->alimit = luaH_realasize(t);
255  setrealasize(t);
256  return t->alimit;
257}
258
259
260#define limitasasize(t)	check_exp(isrealasize(t), t->alimit)
261
262
263
264/*
265** "Generic" get version. (Not that generic: not valid for integers,
266** which may be in array part, nor for floats with integral values.)
267** See explanation about 'deadok' in function 'equalkey'.
268*/
269static const TValue *getgeneric (Table *t, const TValue *key, int deadok) {
270  Node *n = mainpositionTV(t, key);
271  for (;;) {  /* check whether 'key' is somewhere in the chain */
272    if (equalkey(key, n, deadok))
273      return gval(n);  /* that's it */
274    else {
275      int nx = gnext(n);
276      if (nx == 0)
277        return &absentkey;  /* not found */
278      n += nx;
279    }
280  }
281}
282
283
284/*
285** returns the index for 'k' if 'k' is an appropriate key to live in
286** the array part of a table, 0 otherwise.
287*/
288static unsigned int arrayindex (lua_Integer k) {
289  if (l_castS2U(k) - 1u < MAXASIZE)  /* 'k' in [1, MAXASIZE]? */
290    return cast_uint(k);  /* 'key' is an appropriate array index */
291  else
292    return 0;
293}
294
295
296/*
297** returns the index of a 'key' for table traversals. First goes all
298** elements in the array part, then elements in the hash part. The
299** beginning of a traversal is signaled by 0.
300*/
301static unsigned int findindex (lua_State *L, Table *t, TValue *key,
302                               unsigned int asize) {
303  unsigned int i;
304  if (ttisnil(key)) return 0;  /* first iteration */
305  i = ttisinteger(key) ? arrayindex(ivalue(key)) : 0;
306  if (i - 1u < asize)  /* is 'key' inside array part? */
307    return i;  /* yes; that's the index */
308  else {
309    const TValue *n = getgeneric(t, key, 1);
310    if (unlikely(isabstkey(n)))
311      luaG_runerror(L, "invalid key to 'next'");  /* key not found */
312    i = cast_int(nodefromval(n) - gnode(t, 0));  /* key index in hash table */
313    /* hash elements are numbered after array ones */
314    return (i + 1) + asize;
315  }
316}
317
318
319int luaH_next (lua_State *L, Table *t, StkId key) {
320  unsigned int asize = luaH_realasize(t);
321  unsigned int i = findindex(L, t, s2v(key), asize);  /* find original key */
322  for (; i < asize; i++) {  /* try first array part */
323    if (!isempty(&t->array[i])) {  /* a non-empty entry? */
324      setivalue(s2v(key), i + 1);
325      setobj2s(L, key + 1, &t->array[i]);
326      return 1;
327    }
328  }
329  for (i -= asize; cast_int(i) < sizenode(t); i++) {  /* hash part */
330    if (!isempty(gval(gnode(t, i)))) {  /* a non-empty entry? */
331      Node *n = gnode(t, i);
332      getnodekey(L, s2v(key), n);
333      setobj2s(L, key + 1, gval(n));
334      return 1;
335    }
336  }
337  return 0;  /* no more elements */
338}
339
340
341static void freehash (lua_State *L, Table *t) {
342  if (!isdummy(t))
343    luaM_freearray(L, t->node, cast_sizet(sizenode(t)));
344}
345
346
347/*
348** {=============================================================
349** Rehash
350** ==============================================================
351*/
352
353/*
354** Compute the optimal size for the array part of table 't'. 'nums' is a
355** "count array" where 'nums[i]' is the number of integers in the table
356** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of
357** integer keys in the table and leaves with the number of keys that
358** will go to the array part; return the optimal size.  (The condition
359** 'twotoi > 0' in the for loop stops the loop if 'twotoi' overflows.)
360*/
361static unsigned int computesizes (unsigned int nums[], unsigned int *pna) {
362  int i;
363  unsigned int twotoi;  /* 2^i (candidate for optimal size) */
364  unsigned int a = 0;  /* number of elements smaller than 2^i */
365  unsigned int na = 0;  /* number of elements to go to array part */
366  unsigned int optimal = 0;  /* optimal size for array part */
367  /* loop while keys can fill more than half of total size */
368  for (i = 0, twotoi = 1;
369       twotoi > 0 && *pna > twotoi / 2;
370       i++, twotoi *= 2) {
371    a += nums[i];
372    if (a > twotoi/2) {  /* more than half elements present? */
373      optimal = twotoi;  /* optimal size (till now) */
374      na = a;  /* all elements up to 'optimal' will go to array part */
375    }
376  }
377  lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal);
378  *pna = na;
379  return optimal;
380}
381
382
383static int countint (lua_Integer key, unsigned int *nums) {
384  unsigned int k = arrayindex(key);
385  if (k != 0) {  /* is 'key' an appropriate array index? */
386    nums[luaO_ceillog2(k)]++;  /* count as such */
387    return 1;
388  }
389  else
390    return 0;
391}
392
393
394/*
395** Count keys in array part of table 't': Fill 'nums[i]' with
396** number of keys that will go into corresponding slice and return
397** total number of non-nil keys.
398*/
399static unsigned int numusearray (const Table *t, unsigned int *nums) {
400  int lg;
401  unsigned int ttlg;  /* 2^lg */
402  unsigned int ause = 0;  /* summation of 'nums' */
403  unsigned int i = 1;  /* count to traverse all array keys */
404  unsigned int asize = limitasasize(t);  /* real array size */
405  /* traverse each slice */
406  for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
407    unsigned int lc = 0;  /* counter */
408    unsigned int lim = ttlg;
409    if (lim > asize) {
410      lim = asize;  /* adjust upper limit */
411      if (i > lim)
412        break;  /* no more elements to count */
413    }
414    /* count elements in range (2^(lg - 1), 2^lg] */
415    for (; i <= lim; i++) {
416      if (!isempty(&t->array[i-1]))
417        lc++;
418    }
419    nums[lg] += lc;
420    ause += lc;
421  }
422  return ause;
423}
424
425
426static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) {
427  int totaluse = 0;  /* total number of elements */
428  int ause = 0;  /* elements added to 'nums' (can go to array part) */
429  int i = sizenode(t);
430  while (i--) {
431    Node *n = &t->node[i];
432    if (!isempty(gval(n))) {
433      if (keyisinteger(n))
434        ause += countint(keyival(n), nums);
435      totaluse++;
436    }
437  }
438  *pna += ause;
439  return totaluse;
440}
441
442
443/*
444** Creates an array for the hash part of a table with the given
445** size, or reuses the dummy node if size is zero.
446** The computation for size overflow is in two steps: the first
447** comparison ensures that the shift in the second one does not
448** overflow.
449*/
450static void setnodevector (lua_State *L, Table *t, unsigned int size) {
451  if (size == 0) {  /* no elements to hash part? */
452    t->node = cast(Node *, dummynode);  /* use common 'dummynode' */
453    t->lsizenode = 0;
454    t->lastfree = NULL;  /* signal that it is using dummy node */
455  }
456  else {
457    int i;
458    int lsize = luaO_ceillog2(size);
459    if (lsize > MAXHBITS || (1u << lsize) > MAXHSIZE)
460      luaG_runerror(L, "table overflow");
461    size = twoto(lsize);
462    t->node = luaM_newvector(L, size, Node);
463    for (i = 0; i < (int)size; i++) {
464      Node *n = gnode(t, i);
465      gnext(n) = 0;
466      setnilkey(n);
467      setempty(gval(n));
468    }
469    t->lsizenode = cast_byte(lsize);
470    t->lastfree = gnode(t, size);  /* all positions are free */
471  }
472}
473
474
475/*
476** (Re)insert all elements from the hash part of 'ot' into table 't'.
477*/
478static void reinsert (lua_State *L, Table *ot, Table *t) {
479  int j;
480  int size = sizenode(ot);
481  for (j = 0; j < size; j++) {
482    Node *old = gnode(ot, j);
483    if (!isempty(gval(old))) {
484      /* doesn't need barrier/invalidate cache, as entry was
485         already present in the table */
486      TValue k;
487      getnodekey(L, &k, old);
488      setobjt2t(L, luaH_set(L, t, &k), gval(old));
489    }
490  }
491}
492
493
494/*
495** Exchange the hash part of 't1' and 't2'.
496*/
497static void exchangehashpart (Table *t1, Table *t2) {
498  lu_byte lsizenode = t1->lsizenode;
499  Node *node = t1->node;
500  Node *lastfree = t1->lastfree;
501  t1->lsizenode = t2->lsizenode;
502  t1->node = t2->node;
503  t1->lastfree = t2->lastfree;
504  t2->lsizenode = lsizenode;
505  t2->node = node;
506  t2->lastfree = lastfree;
507}
508
509
510/*
511** Resize table 't' for the new given sizes. Both allocations (for
512** the hash part and for the array part) can fail, which creates some
513** subtleties. If the first allocation, for the hash part, fails, an
514** error is raised and that is it. Otherwise, it copies the elements from
515** the shrinking part of the array (if it is shrinking) into the new
516** hash. Then it reallocates the array part.  If that fails, the table
517** is in its original state; the function frees the new hash part and then
518** raises the allocation error. Otherwise, it sets the new hash part
519** into the table, initializes the new part of the array (if any) with
520** nils and reinserts the elements of the old hash back into the new
521** parts of the table.
522*/
523void luaH_resize (lua_State *L, Table *t, unsigned int newasize,
524                                          unsigned int nhsize) {
525  unsigned int i;
526  Table newt;  /* to keep the new hash part */
527  unsigned int oldasize = setlimittosize(t);
528  TValue *newarray;
529  /* create new hash part with appropriate size into 'newt' */
530  setnodevector(L, &newt, nhsize);
531  if (newasize < oldasize) {  /* will array shrink? */
532    t->alimit = newasize;  /* pretend array has new size... */
533    exchangehashpart(t, &newt);  /* and new hash */
534    /* re-insert into the new hash the elements from vanishing slice */
535    for (i = newasize; i < oldasize; i++) {
536      if (!isempty(&t->array[i]))
537        luaH_setint(L, t, i + 1, &t->array[i]);
538    }
539    t->alimit = oldasize;  /* restore current size... */
540    exchangehashpart(t, &newt);  /* and hash (in case of errors) */
541  }
542  /* allocate new array */
543  newarray = luaM_reallocvector(L, t->array, oldasize, newasize, TValue);
544  if (unlikely(newarray == NULL && newasize > 0)) {  /* allocation failed? */
545    freehash(L, &newt);  /* release new hash part */
546    luaM_error(L);  /* raise error (with array unchanged) */
547  }
548  /* allocation ok; initialize new part of the array */
549  exchangehashpart(t, &newt);  /* 't' has the new hash ('newt' has the old) */
550  t->array = newarray;  /* set new array part */
551  t->alimit = newasize;
552  for (i = oldasize; i < newasize; i++)  /* clear new slice of the array */
553     setempty(&t->array[i]);
554  /* re-insert elements from old hash part into new parts */
555  reinsert(L, &newt, t);  /* 'newt' now has the old hash */
556  freehash(L, &newt);  /* free old hash part */
557}
558
559
560void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
561  int nsize = allocsizenode(t);
562  luaH_resize(L, t, nasize, nsize);
563}
564
565/*
566** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
567*/
568static void rehash (lua_State *L, Table *t, const TValue *ek) {
569  unsigned int asize;  /* optimal size for array part */
570  unsigned int na;  /* number of keys in the array part */
571  unsigned int nums[MAXABITS + 1];
572  int i;
573  int totaluse;
574  for (i = 0; i <= MAXABITS; i++) nums[i] = 0;  /* reset counts */
575  setlimittosize(t);
576  na = numusearray(t, nums);  /* count keys in array part */
577  totaluse = na;  /* all those keys are integer keys */
578  totaluse += numusehash(t, nums, &na);  /* count keys in hash part */
579  /* count extra key */
580  if (ttisinteger(ek))
581    na += countint(ivalue(ek), nums);
582  totaluse++;
583  /* compute new size for array part */
584  asize = computesizes(nums, &na);
585  /* resize the table to new computed sizes */
586  luaH_resize(L, t, asize, totaluse - na);
587}
588
589
590
591/*
592** }=============================================================
593*/
594
595
596Table *luaH_new (lua_State *L) {
597  GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
598  Table *t = gco2t(o);
599  t->metatable = NULL;
600  t->flags = cast_byte(maskflags);  /* table has no metamethod fields */
601  t->array = NULL;
602  t->alimit = 0;
603  setnodevector(L, t, 0);
604  return t;
605}
606
607
608void luaH_free (lua_State *L, Table *t) {
609  freehash(L, t);
610  luaM_freearray(L, t->array, luaH_realasize(t));
611  luaM_free(L, t);
612}
613
614
615static Node *getfreepos (Table *t) {
616  if (!isdummy(t)) {
617    while (t->lastfree > t->node) {
618      t->lastfree--;
619      if (keyisnil(t->lastfree))
620        return t->lastfree;
621    }
622  }
623  return NULL;  /* could not find a free place */
624}
625
626
627
628/*
629** inserts a new key into a hash table; first, check whether key's main
630** position is free. If not, check whether colliding node is in its main
631** position or not: if it is not, move colliding node to an empty place and
632** put new key in its main position; otherwise (colliding node is in its main
633** position), new key goes to an empty position.
634*/
635TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
636  Node *mp;
637  TValue aux;
638  if (unlikely(ttisnil(key)))
639    luaG_runerror(L, "table index is nil");
640  else if (ttisfloat(key)) {
641    lua_Number f = fltvalue(key);
642    lua_Integer k;
643    if (luaV_flttointeger(f, &k, F2Ieq)) {  /* does key fit in an integer? */
644      setivalue(&aux, k);
645      key = &aux;  /* insert it as an integer */
646    }
647    else if (unlikely(luai_numisnan(f)))
648      luaG_runerror(L, "table index is NaN");
649  }
650  mp = mainpositionTV(t, key);
651  if (!isempty(gval(mp)) || isdummy(t)) {  /* main position is taken? */
652    Node *othern;
653    Node *f = getfreepos(t);  /* get a free place */
654    if (f == NULL) {  /* cannot find a free place? */
655      rehash(L, t, key);  /* grow table */
656      /* whatever called 'newkey' takes care of TM cache */
657      return luaH_set(L, t, key);  /* insert key into grown table */
658    }
659    lua_assert(!isdummy(t));
660    othern = mainposition(t, keytt(mp), &keyval(mp));
661    if (othern != mp) {  /* is colliding node out of its main position? */
662      /* yes; move colliding node into free position */
663      while (othern + gnext(othern) != mp)  /* find previous */
664        othern += gnext(othern);
665      gnext(othern) = cast_int(f - othern);  /* rechain to point to 'f' */
666      *f = *mp;  /* copy colliding node into free pos. (mp->next also goes) */
667      if (gnext(mp) != 0) {
668        gnext(f) += cast_int(mp - f);  /* correct 'next' */
669        gnext(mp) = 0;  /* now 'mp' is free */
670      }
671      setempty(gval(mp));
672    }
673    else {  /* colliding node is in its own main position */
674      /* new node will go into free position */
675      if (gnext(mp) != 0)
676        gnext(f) = cast_int((mp + gnext(mp)) - f);  /* chain new position */
677      else lua_assert(gnext(f) == 0);
678      gnext(mp) = cast_int(f - mp);
679      mp = f;
680    }
681  }
682  setnodekey(L, mp, key);
683  luaC_barrierback(L, obj2gco(t), key);
684  lua_assert(isempty(gval(mp)));
685  return gval(mp);
686}
687
688
689/*
690** Search function for integers. If integer is inside 'alimit', get it
691** directly from the array part. Otherwise, if 'alimit' is not equal to
692** the real size of the array, key still can be in the array part. In
693** this case, try to avoid a call to 'luaH_realasize' when key is just
694** one more than the limit (so that it can be incremented without
695** changing the real size of the array).
696*/
697const TValue *luaH_getint (Table *t, lua_Integer key) {
698  if (l_castS2U(key) - 1u < t->alimit)  /* 'key' in [1, t->alimit]? */
699    return &t->array[key - 1];
700  else if (!limitequalsasize(t) &&  /* key still may be in the array part? */
701           (l_castS2U(key) == t->alimit + 1 ||
702            l_castS2U(key) - 1u < luaH_realasize(t))) {
703    t->alimit = cast_uint(key);  /* probably '#t' is here now */
704    return &t->array[key - 1];
705  }
706  else {
707    Node *n = hashint(t, key);
708    for (;;) {  /* check whether 'key' is somewhere in the chain */
709      if (keyisinteger(n) && keyival(n) == key)
710        return gval(n);  /* that's it */
711      else {
712        int nx = gnext(n);
713        if (nx == 0) break;
714        n += nx;
715      }
716    }
717    return &absentkey;
718  }
719}
720
721
722/*
723** search function for short strings
724*/
725const TValue *luaH_getshortstr (Table *t, TString *key) {
726  Node *n = hashstr(t, key);
727  lua_assert(key->tt == LUA_VSHRSTR);
728  for (;;) {  /* check whether 'key' is somewhere in the chain */
729    if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
730      return gval(n);  /* that's it */
731    else {
732      int nx = gnext(n);
733      if (nx == 0)
734        return &absentkey;  /* not found */
735      n += nx;
736    }
737  }
738}
739
740
741const TValue *luaH_getstr (Table *t, TString *key) {
742  if (key->tt == LUA_VSHRSTR)
743    return luaH_getshortstr(t, key);
744  else {  /* for long strings, use generic case */
745    TValue ko;
746    setsvalue(cast(lua_State *, NULL), &ko, key);
747    return getgeneric(t, &ko, 0);
748  }
749}
750
751
752/*
753** main search function
754*/
755const TValue *luaH_get (Table *t, const TValue *key) {
756  switch (ttypetag(key)) {
757    case LUA_VSHRSTR: return luaH_getshortstr(t, tsvalue(key));
758    case LUA_VNUMINT: return luaH_getint(t, ivalue(key));
759    case LUA_VNIL: return &absentkey;
760    case LUA_VNUMFLT: {
761      lua_Integer k;
762      if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
763        return luaH_getint(t, k);  /* use specialized version */
764      /* else... */
765    }  /* FALLTHROUGH */
766    default:
767      return getgeneric(t, key, 0);
768  }
769}
770
771
772/*
773** beware: when using this function you probably need to check a GC
774** barrier and invalidate the TM cache.
775*/
776TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
777  const TValue *p = luaH_get(t, key);
778  if (!isabstkey(p))
779    return cast(TValue *, p);
780  else return luaH_newkey(L, t, key);
781}
782
783
784void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
785  const TValue *p = luaH_getint(t, key);
786  TValue *cell;
787  if (!isabstkey(p))
788    cell = cast(TValue *, p);
789  else {
790    TValue k;
791    setivalue(&k, key);
792    cell = luaH_newkey(L, t, &k);
793  }
794  setobj2t(L, cell, value);
795}
796
797
798/*
799** Try to find a boundary in the hash part of table 't'. From the
800** caller, we know that 'j' is zero or present and that 'j + 1' is
801** present. We want to find a larger key that is absent from the
802** table, so that we can do a binary search between the two keys to
803** find a boundary. We keep doubling 'j' until we get an absent index.
804** If the doubling would overflow, we try LUA_MAXINTEGER. If it is
805** absent, we are ready for the binary search. ('j', being max integer,
806** is larger or equal to 'i', but it cannot be equal because it is
807** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a
808** boundary. ('j + 1' cannot be a present integer key because it is
809** not a valid integer in Lua.)
810*/
811static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
812  lua_Unsigned i;
813  if (j == 0) j++;  /* the caller ensures 'j + 1' is present */
814  do {
815    i = j;  /* 'i' is a present index */
816    if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
817      j *= 2;
818    else {
819      j = LUA_MAXINTEGER;
820      if (isempty(luaH_getint(t, j)))  /* t[j] not present? */
821        break;  /* 'j' now is an absent index */
822      else  /* weird case */
823        return j;  /* well, max integer is a boundary... */
824    }
825  } while (!isempty(luaH_getint(t, j)));  /* repeat until an absent t[j] */
826  /* i < j  &&  t[i] present  &&  t[j] absent */
827  while (j - i > 1u) {  /* do a binary search between them */
828    lua_Unsigned m = (i + j) / 2;
829    if (isempty(luaH_getint(t, m))) j = m;
830    else i = m;
831  }
832  return i;
833}
834
835
836static unsigned int binsearch (const TValue *array, unsigned int i,
837                                                    unsigned int j) {
838  while (j - i > 1u) {  /* binary search */
839    unsigned int m = (i + j) / 2;
840    if (isempty(&array[m - 1])) j = m;
841    else i = m;
842  }
843  return i;
844}
845
846
847/*
848** Try to find a boundary in table 't'. (A 'boundary' is an integer index
849** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent
850** and 'maxinteger' if t[maxinteger] is present.)
851** (In the next explanation, we use Lua indices, that is, with base 1.
852** The code itself uses base 0 when indexing the array part of the table.)
853** The code starts with 'limit = t->alimit', a position in the array
854** part that may be a boundary.
855**
856** (1) If 't[limit]' is empty, there must be a boundary before it.
857** As a common case (e.g., after 't[#t]=nil'), check whether 'limit-1'
858** is present. If so, it is a boundary. Otherwise, do a binary search
859** between 0 and limit to find a boundary. In both cases, try to
860** use this boundary as the new 'alimit', as a hint for the next call.
861**
862** (2) If 't[limit]' is not empty and the array has more elements
863** after 'limit', try to find a boundary there. Again, try first
864** the special case (which should be quite frequent) where 'limit+1'
865** is empty, so that 'limit' is a boundary. Otherwise, check the
866** last element of the array part. If it is empty, there must be a
867** boundary between the old limit (present) and the last element
868** (absent), which is found with a binary search. (This boundary always
869** can be a new limit.)
870**
871** (3) The last case is when there are no elements in the array part
872** (limit == 0) or its last element (the new limit) is present.
873** In this case, must check the hash part. If there is no hash part
874** or 'limit+1' is absent, 'limit' is a boundary.  Otherwise, call
875** 'hash_search' to find a boundary in the hash part of the table.
876** (In those cases, the boundary is not inside the array part, and
877** therefore cannot be used as a new limit.)
878*/
879lua_Unsigned luaH_getn (Table *t) {
880  unsigned int limit = t->alimit;
881  if (limit > 0 && isempty(&t->array[limit - 1])) {  /* (1)? */
882    /* there must be a boundary before 'limit' */
883    if (limit >= 2 && !isempty(&t->array[limit - 2])) {
884      /* 'limit - 1' is a boundary; can it be a new limit? */
885      if (ispow2realasize(t) && !ispow2(limit - 1)) {
886        t->alimit = limit - 1;
887        setnorealasize(t);  /* now 'alimit' is not the real size */
888      }
889      return limit - 1;
890    }
891    else {  /* must search for a boundary in [0, limit] */
892      unsigned int boundary = binsearch(t->array, 0, limit);
893      /* can this boundary represent the real size of the array? */
894      if (ispow2realasize(t) && boundary > luaH_realasize(t) / 2) {
895        t->alimit = boundary;  /* use it as the new limit */
896        setnorealasize(t);
897      }
898      return boundary;
899    }
900  }
901  /* 'limit' is zero or present in table */
902  if (!limitequalsasize(t)) {  /* (2)? */
903    /* 'limit' > 0 and array has more elements after 'limit' */
904    if (isempty(&t->array[limit]))  /* 'limit + 1' is empty? */
905      return limit;  /* this is the boundary */
906    /* else, try last element in the array */
907    limit = luaH_realasize(t);
908    if (isempty(&t->array[limit - 1])) {  /* empty? */
909      /* there must be a boundary in the array after old limit,
910         and it must be a valid new limit */
911      unsigned int boundary = binsearch(t->array, t->alimit, limit);
912      t->alimit = boundary;
913      return boundary;
914    }
915    /* else, new limit is present in the table; check the hash part */
916  }
917  /* (3) 'limit' is the last element and either is zero or present in table */
918  lua_assert(limit == luaH_realasize(t) &&
919             (limit == 0 || !isempty(&t->array[limit - 1])));
920  if (isdummy(t) || isempty(luaH_getint(t, cast(lua_Integer, limit + 1))))
921    return limit;  /* 'limit + 1' is absent */
922  else  /* 'limit + 1' is also present */
923    return hash_search(t, limit);
924}
925
926
927
928#if defined(LUA_DEBUG)
929
930/* export these functions for the test library */
931
932Node *luaH_mainposition (const Table *t, const TValue *key) {
933  return mainpositionTV(t, key);
934}
935
936int luaH_isdummy (const Table *t) { return isdummy(t); }
937
938#endif
939