ltable.c 39 KB

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