ltable.c 38 KB

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