4 ** See Copyright Notice in lua.h
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.
43 ** MAXABITS is the largest integer such that MAXASIZE fits in an
46 #define MAXABITS cast_int(sizeof(int) * CHAR_BIT - 1)
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'.
54 #define MAXASIZE luaM_limitN(1u << MAXABITS, TValue)
57 ** MAXHBITS is the largest integer such that 2^MAXHBITS fits in a
60 #define MAXHBITS (MAXABITS - 1)
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'.
68 #define MAXHSIZE luaM_limitN(1u << MAXHBITS, Node)
71 #define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))
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)
79 ** for some types, it is better to avoid modulus by power of 2, as
80 ** they tend to have many 2 factors.
82 #define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))
85 #define hashpointer(t,p) hashmod(t, point2uint(p))
88 #define dummynode (&dummynode_)
90 static const Node dummynode_ = {
91 {{NULL}, LUA_VEMPTY, /* value's value and type */
92 LUA_VNIL, 0, {NULL}} /* key type, next, and key value */
96 static const TValue absentkey = {ABSTKEYCONSTANT};
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
113 #if !defined(l_hashfloat)
114 static int l_hashfloat (lua_Number n) {
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));
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);
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
136 static Node *mainposition (const Table *t, int ktt, const Value *kvl) {
137 switch (withvariant(ktt)) {
139 return hashint(t, ivalueraw(*kvl));
141 return hashmod(t, l_hashfloat(fltvalueraw(*kvl)));
143 return hashstr(t, tsvalueraw(*kvl));
145 return hashpow2(t, luaS_hashlongstr(tsvalueraw(*kvl)));
147 return hashboolean(t, 0);
149 return hashboolean(t, 1);
150 case LUA_VLIGHTUSERDATA:
151 return hashpointer(t, pvalueraw(*kvl));
153 return hashpointer(t, fvalueraw(*kvl));
155 return hashpointer(t, gcvalueraw(*kvl));
161 ** Returns the main position of an element given as a 'TValue'
163 static Node *mainpositionTV (const Table *t, const TValue *key) {
164 return mainposition(t, rawtt(key), valraw(key));
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.)
188 static 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 */
193 case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE:
196 return (ivalue(k1) == keyival(n2));
198 return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2)));
199 case LUA_VLIGHTUSERDATA:
200 return pvalue(k1) == pvalueraw(keyval(n2));
202 return fvalue(k1) == fvalueraw(keyval(n2));
203 case ctb(LUA_VLNGSTR):
204 return luaS_eqlngstr(tsvalue(k1), keystrval(n2));
206 return gcvalue(k1) == gcvalueraw(keyval(n2));
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
216 #define limitequalsasize(t) (isrealasize(t) || ispow2((t)->alimit))
220 ** Returns the real size of the 'array' array
222 LUAI_FUNC unsigned int luaH_realasize (const Table *t) {
223 if (limitequalsasize(t))
224 return t->alimit; /* this is the size */
226 unsigned int size = t->alimit;
227 /* compute the smallest power of 2 not smaller than 'n' */
232 size |= (size >> 16);
233 #if (UINT_MAX >> 30) > 3
234 size |= (size >> 32); /* unsigned int has more than 32 bits */
237 lua_assert(ispow2(size) && size/2 < t->alimit && t->alimit < size);
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.)
248 static int ispow2realasize (const Table *t) {
249 return (!isrealasize(t) || ispow2(t->alimit));
253 static unsigned int setlimittosize (Table *t) {
254 t->alimit = luaH_realasize(t);
260 #define limitasasize(t) check_exp(isrealasize(t), t->alimit)
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'.
269 static 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 */
277 return &absentkey; /* not found */
285 ** returns the index for 'k' if 'k' is an appropriate key to live in
286 ** the array part of a table, 0 otherwise.
288 static 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 */
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.
301 static unsigned int findindex (lua_State *L, Table *t, TValue *key,
302 unsigned int asize) {
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 */
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;
319 int 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]);
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));
337 return 0; /* no more elements */
341 static void freehash (lua_State *L, Table *t) {
343 luaM_freearray(L, t->node, cast_sizet(sizenode(t)));
348 ** {=============================================================
350 ** ==============================================================
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.)
361 static unsigned int computesizes (unsigned int nums[], unsigned int *pna) {
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;
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 */
377 lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal);
383 static 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 */
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.
399 static unsigned int numusearray (const Table *t, unsigned int *nums) {
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;
410 lim = asize; /* adjust upper limit */
412 break; /* no more elements to count */
414 /* count elements in range (2^(lg - 1), 2^lg] */
415 for (; i <= lim; i++) {
416 if (!isempty(&t->array[i-1]))
426 static 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) */
431 Node *n = &t->node[i];
432 if (!isempty(gval(n))) {
434 ause += countint(keyival(n), nums);
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
450 static 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' */
454 t->lastfree = NULL; /* signal that it is using dummy node */
458 int lsize = luaO_ceillog2(size);
459 if (lsize > MAXHBITS || (1u << lsize) > MAXHSIZE)
460 luaG_runerror(L, "table overflow");
462 t->node = luaM_newvector(L, size, Node);
463 for (i = 0; i < (int)size; i++) {
464 Node *n = gnode(t, i);
469 t->lsizenode = cast_byte(lsize);
470 t->lastfree = gnode(t, size); /* all positions are free */
476 ** (Re)insert all elements from the hash part of 'ot' into table 't'.
478 static void reinsert (lua_State *L, Table *ot, Table *t) {
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 */
487 getnodekey(L, &k, old);
488 setobjt2t(L, luaH_set(L, t, &k), gval(old));
495 ** Exchange the hash part of 't1' and 't2'.
497 static 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;
503 t1->lastfree = t2->lastfree;
504 t2->lsizenode = lsizenode;
506 t2->lastfree = lastfree;
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.
523 void luaH_resize (lua_State *L, Table *t, unsigned int newasize,
524 unsigned int nhsize) {
526 Table newt; /* to keep the new hash part */
527 unsigned int oldasize = setlimittosize(t);
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]);
539 t->alimit = oldasize; /* restore current size... */
540 exchangehashpart(t, &newt); /* and hash (in case of errors) */
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) */
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 */
560 void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
561 int nsize = allocsizenode(t);
562 luaH_resize(L, t, nasize, nsize);
566 ** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
568 static 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];
574 for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */
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 */
581 na += countint(ivalue(ek), nums);
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);
592 ** }=============================================================
596 Table *luaH_new (lua_State *L) {
597 GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
600 t->flags = cast_byte(maskflags); /* table has no metamethod fields */
603 setnodevector(L, t, 0);
608 void luaH_free (lua_State *L, Table *t) {
610 luaM_freearray(L, t->array, luaH_realasize(t));
615 static Node *getfreepos (Table *t) {
617 while (t->lastfree > t->node) {
619 if (keyisnil(t->lastfree))
623 return NULL; /* could not find a free place */
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.
635 TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
638 if (unlikely(ttisnil(key)))
639 luaG_runerror(L, "table index is nil");
640 else if (ttisfloat(key)) {
641 lua_Number f = fltvalue(key);
643 if (luaV_flttointeger(f, &k, F2Ieq)) { /* does key fit in an integer? */
645 key = &aux; /* insert it as an integer */
647 else if (unlikely(luai_numisnan(f)))
648 luaG_runerror(L, "table index is NaN");
650 mp = mainpositionTV(t, key);
651 if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */
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 */
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 */
673 else { /* colliding node is in its own main position */
674 /* new node will go into free position */
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);
682 setnodekey(L, mp, key);
683 luaC_barrierback(L, obj2gco(t), key);
684 lua_assert(isempty(gval(mp)));
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).
697 const 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];
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 */
723 ** search function for short strings
725 const 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 */
734 return &absentkey; /* not found */
741 const 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 */
746 setsvalue(cast(lua_State *, NULL), &ko, key);
747 return getgeneric(t, &ko, 0);
753 ** main search function
755 const 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;
762 if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
763 return luaH_getint(t, k); /* use specialized version */
767 return getgeneric(t, key, 0);
773 ** beware: when using this function you probably need to check a GC
774 ** barrier and invalidate the TM cache.
776 TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
777 const TValue *p = luaH_get(t, key);
779 return cast(TValue *, p);
780 else return luaH_newkey(L, t, key);
784 void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
785 const TValue *p = luaH_getint(t, key);
788 cell = cast(TValue *, p);
792 cell = luaH_newkey(L, t, &k);
794 setobj2t(L, cell, value);
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.)
811 static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
813 if (j == 0) j++; /* the caller ensures 'j + 1' is present */
815 i = j; /* 'i' is a present index */
816 if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
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... */
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;
836 static unsigned int binsearch (const TValue *array, unsigned int i,
838 while (j - i > 1u) { /* binary search */
839 unsigned int m = (i + j) / 2;
840 if (isempty(&array[m - 1])) j = m;
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.
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.
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.)
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.)
879 lua_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 */
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 */
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;
915 /* else, new limit is present in the table; check the hash part */
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);
928 #if defined(LUA_DEBUG)
930 /* export these functions for the test library */
932 Node *luaH_mainposition (const Table *t, const TValue *key) {
933 return mainpositionTV(t, key);
936 int luaH_isdummy (const Table *t) { return isdummy(t); }