ltable.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325
  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 (l_numbits(int) - 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(1 << 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, avoiding 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. ** Return the index 'k' (converted to an unsigned) if it is inside
  251. ** the range [1, limit].
  252. */
  253. static unsigned checkrange (lua_Integer k, unsigned limit) {
  254. return (l_castS2U(k) - 1u < limit) ? cast_uint(k) : 0;
  255. }
  256. /*
  257. ** Return the index 'k' if 'k' is an appropriate key to live in the
  258. ** array part of a table, 0 otherwise.
  259. */
  260. #define arrayindex(k) checkrange(k, MAXASIZE)
  261. /*
  262. ** Check whether an integer key is in the array part of a table and
  263. ** return its index there, or zero.
  264. */
  265. #define ikeyinarray(t,k) checkrange(k, t->asize)
  266. /*
  267. ** Check whether a key is in the array part of a table and return its
  268. ** index there, or zero.
  269. */
  270. static unsigned keyinarray (Table *t, const TValue *key) {
  271. return (ttisinteger(key)) ? ikeyinarray(t, ivalue(key)) : 0;
  272. }
  273. /*
  274. ** returns the index of a 'key' for table traversals. First goes all
  275. ** elements in the array part, then elements in the hash part. The
  276. ** beginning of a traversal is signaled by 0.
  277. */
  278. static unsigned findindex (lua_State *L, Table *t, TValue *key,
  279. unsigned asize) {
  280. unsigned int i;
  281. if (ttisnil(key)) return 0; /* first iteration */
  282. i = keyinarray(t, key);
  283. if (i != 0) /* is 'key' inside array part? */
  284. return i; /* yes; that's the index */
  285. else {
  286. const TValue *n = getgeneric(t, key, 1);
  287. if (l_unlikely(isabstkey(n)))
  288. luaG_runerror(L, "invalid key to 'next'"); /* key not found */
  289. i = cast_uint(nodefromval(n) - gnode(t, 0)); /* key index in hash table */
  290. /* hash elements are numbered after array ones */
  291. return (i + 1) + asize;
  292. }
  293. }
  294. int luaH_next (lua_State *L, Table *t, StkId key) {
  295. unsigned int asize = t->asize;
  296. unsigned int i = findindex(L, t, s2v(key), asize); /* find original key */
  297. for (; i < asize; i++) { /* try first array part */
  298. lu_byte tag = *getArrTag(t, i);
  299. if (!tagisempty(tag)) { /* a non-empty entry? */
  300. setivalue(s2v(key), cast_int(i) + 1);
  301. farr2val(t, i, tag, s2v(key + 1));
  302. return 1;
  303. }
  304. }
  305. for (i -= asize; i < sizenode(t); i++) { /* hash part */
  306. if (!isempty(gval(gnode(t, i)))) { /* a non-empty entry? */
  307. Node *n = gnode(t, i);
  308. getnodekey(L, s2v(key), n);
  309. setobj2s(L, key + 1, gval(n));
  310. return 1;
  311. }
  312. }
  313. return 0; /* no more elements */
  314. }
  315. /* Extra space in Node array if it has a lastfree entry */
  316. #define extraLastfree(t) (haslastfree(t) ? sizeof(Limbox) : 0)
  317. /* 'node' size in bytes */
  318. static size_t sizehash (Table *t) {
  319. return cast_sizet(sizenode(t)) * sizeof(Node) + extraLastfree(t);
  320. }
  321. static void freehash (lua_State *L, Table *t) {
  322. if (!isdummy(t)) {
  323. /* get pointer to the beginning of Node array */
  324. char *arr = cast_charp(t->node) - extraLastfree(t);
  325. luaM_freearray(L, arr, sizehash(t));
  326. }
  327. }
  328. /*
  329. ** {=============================================================
  330. ** Rehash
  331. ** ==============================================================
  332. */
  333. static int insertkey (Table *t, const TValue *key, TValue *value);
  334. static void newcheckedkey (Table *t, const TValue *key, TValue *value);
  335. /*
  336. ** Structure to count the keys in a table.
  337. ** 'total' is the total number of keys in the table.
  338. ** 'na' is the number of *array indices* in the table (see 'arrayindex').
  339. ** 'deleted' is true if there are deleted nodes in the hash part.
  340. ** 'nums' is a "count array" where 'nums[i]' is the number of integer
  341. ** keys between 2^(i - 1) + 1 and 2^i. Note that 'na' is the summation
  342. ** of 'nums'.
  343. */
  344. typedef struct {
  345. unsigned total;
  346. unsigned na;
  347. int deleted;
  348. unsigned nums[MAXABITS + 1];
  349. } Counters;
  350. /*
  351. ** Check whether it is worth to use 'na' array entries instead of 'nh'
  352. ** hash nodes. (A hash node uses ~3 times more memory than an array
  353. ** entry: Two values plus 'next' versus one value.) Evaluate with size_t
  354. ** to avoid overflows.
  355. */
  356. #define arrayXhash(na,nh) (cast_sizet(na) <= cast_sizet(nh) * 3)
  357. /*
  358. ** Compute the optimal size for the array part of table 't'.
  359. ** This size maximizes the number of elements going to the array part
  360. ** while satisfying the condition 'arrayXhash' with the use of memory if
  361. ** all those elements went to the hash part.
  362. ** 'ct->na' enters with the total number of array indices in the table
  363. ** and leaves with the number of keys that will go to the array part;
  364. ** return the optimal size for the array part.
  365. */
  366. static unsigned computesizes (Counters *ct) {
  367. int i;
  368. unsigned int twotoi; /* 2^i (candidate for optimal size) */
  369. unsigned int a = 0; /* number of elements smaller than 2^i */
  370. unsigned int na = 0; /* number of elements to go to array part */
  371. unsigned int optimal = 0; /* optimal size for array part */
  372. /* traverse slices while 'twotoi' does not overflow and total of array
  373. indices still can satisfy 'arrayXhash' against the array size */
  374. for (i = 0, twotoi = 1;
  375. twotoi > 0 && arrayXhash(twotoi, ct->na);
  376. i++, twotoi *= 2) {
  377. unsigned nums = ct->nums[i];
  378. a += nums;
  379. if (nums > 0 && /* grows array only if it gets more elements... */
  380. arrayXhash(twotoi, a)) { /* ...while using "less memory" */
  381. optimal = twotoi; /* optimal size (till now) */
  382. na = a; /* all elements up to 'optimal' will go to array part */
  383. }
  384. }
  385. ct->na = na;
  386. return optimal;
  387. }
  388. static void countint (lua_Integer key, Counters *ct) {
  389. unsigned int k = arrayindex(key);
  390. if (k != 0) { /* is 'key' an array index? */
  391. ct->nums[luaO_ceillog2(k)]++; /* count as such */
  392. ct->na++;
  393. }
  394. }
  395. l_sinline int arraykeyisempty (const Table *t, unsigned key) {
  396. int tag = *getArrTag(t, key - 1);
  397. return tagisempty(tag);
  398. }
  399. /*
  400. ** Count keys in array part of table 't'.
  401. */
  402. static void numusearray (const Table *t, Counters *ct) {
  403. int lg;
  404. unsigned int ttlg; /* 2^lg */
  405. unsigned int ause = 0; /* summation of 'nums' */
  406. unsigned int i = 1; /* index to traverse all array keys */
  407. unsigned int asize = t->asize;
  408. /* traverse each slice */
  409. for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
  410. unsigned int lc = 0; /* counter */
  411. unsigned int lim = ttlg;
  412. if (lim > asize) {
  413. lim = asize; /* adjust upper limit */
  414. if (i > lim)
  415. break; /* no more elements to count */
  416. }
  417. /* count elements in range (2^(lg - 1), 2^lg] */
  418. for (; i <= lim; i++) {
  419. if (!arraykeyisempty(t, i))
  420. lc++;
  421. }
  422. ct->nums[lg] += lc;
  423. ause += lc;
  424. }
  425. ct->total += ause;
  426. ct->na += ause;
  427. }
  428. /*
  429. ** Count keys in hash part of table 't'. As this only happens during
  430. ** a rehash, all nodes have been used. A node can have a nil value only
  431. ** if it was deleted after being created.
  432. */
  433. static void numusehash (const Table *t, Counters *ct) {
  434. unsigned i = sizenode(t);
  435. unsigned total = 0;
  436. while (i--) {
  437. Node *n = &t->node[i];
  438. if (isempty(gval(n))) {
  439. lua_assert(!keyisnil(n)); /* entry was deleted; key cannot be nil */
  440. ct->deleted = 1;
  441. }
  442. else {
  443. total++;
  444. if (keyisinteger(n))
  445. countint(keyival(n), ct);
  446. }
  447. }
  448. ct->total += total;
  449. }
  450. /*
  451. ** Convert an "abstract size" (number of slots in an array) to
  452. ** "concrete size" (number of bytes in the array).
  453. */
  454. static size_t concretesize (unsigned int size) {
  455. if (size == 0)
  456. return 0;
  457. else /* space for the two arrays plus an unsigned in between */
  458. return size * (sizeof(Value) + 1) + sizeof(unsigned);
  459. }
  460. /*
  461. ** Resize the array part of a table. If new size is equal to the old,
  462. ** do nothing. Else, if new size is zero, free the old array. (It must
  463. ** be present, as the sizes are different.) Otherwise, allocate a new
  464. ** array, move the common elements to new proper position, and then
  465. ** frees the old array.
  466. ** We could reallocate the array, but we still would need to move the
  467. ** elements to their new position, so the copy implicit in realloc is a
  468. ** waste. Moreover, most allocators will move the array anyway when the
  469. ** new size is double the old one (the most common case).
  470. */
  471. static Value *resizearray (lua_State *L , Table *t,
  472. unsigned oldasize,
  473. unsigned newasize) {
  474. if (oldasize == newasize)
  475. return t->array; /* nothing to be done */
  476. else if (newasize == 0) { /* erasing array? */
  477. Value *op = t->array - oldasize; /* original array's real address */
  478. luaM_freemem(L, op, concretesize(oldasize)); /* free it */
  479. return NULL;
  480. }
  481. else {
  482. size_t newasizeb = concretesize(newasize);
  483. Value *np = cast(Value *,
  484. luaM_reallocvector(L, NULL, 0, newasizeb, lu_byte));
  485. if (np == NULL) /* allocation error? */
  486. return NULL;
  487. np += newasize; /* shift pointer to the end of value segment */
  488. if (oldasize > 0) {
  489. /* move common elements to new position */
  490. size_t oldasizeb = concretesize(oldasize);
  491. Value *op = t->array; /* original array */
  492. unsigned tomove = (oldasize < newasize) ? oldasize : newasize;
  493. size_t tomoveb = (oldasize < newasize) ? oldasizeb : newasizeb;
  494. lua_assert(tomoveb > 0);
  495. memcpy(np - tomove, op - tomove, tomoveb);
  496. luaM_freemem(L, op - oldasize, oldasizeb); /* free old block */
  497. }
  498. return np;
  499. }
  500. }
  501. /*
  502. ** Creates an array for the hash part of a table with the given
  503. ** size, or reuses the dummy node if size is zero.
  504. ** The computation for size overflow is in two steps: the first
  505. ** comparison ensures that the shift in the second one does not
  506. ** overflow.
  507. */
  508. static void setnodevector (lua_State *L, Table *t, unsigned size) {
  509. if (size == 0) { /* no elements to hash part? */
  510. t->node = cast(Node *, dummynode); /* use common 'dummynode' */
  511. t->lsizenode = 0;
  512. setdummy(t); /* signal that it is using dummy node */
  513. }
  514. else {
  515. int i;
  516. int lsize = luaO_ceillog2(size);
  517. if (lsize > MAXHBITS || (1 << lsize) > MAXHSIZE)
  518. luaG_runerror(L, "table overflow");
  519. size = twoto(lsize);
  520. if (lsize < LIMFORLAST) /* no 'lastfree' field? */
  521. t->node = luaM_newvector(L, size, Node);
  522. else {
  523. size_t bsize = size * sizeof(Node) + sizeof(Limbox);
  524. char *node = luaM_newblock(L, bsize);
  525. t->node = cast(Node *, node + sizeof(Limbox));
  526. getlastfree(t) = gnode(t, size); /* all positions are free */
  527. }
  528. t->lsizenode = cast_byte(lsize);
  529. setnodummy(t);
  530. for (i = 0; i < cast_int(size); i++) {
  531. Node *n = gnode(t, i);
  532. gnext(n) = 0;
  533. setnilkey(n);
  534. setempty(gval(n));
  535. }
  536. }
  537. }
  538. /*
  539. ** (Re)insert all elements from the hash part of 'ot' into table 't'.
  540. */
  541. static void reinserthash (lua_State *L, Table *ot, Table *t) {
  542. unsigned j;
  543. unsigned size = sizenode(ot);
  544. for (j = 0; j < size; j++) {
  545. Node *old = gnode(ot, j);
  546. if (!isempty(gval(old))) {
  547. /* doesn't need barrier/invalidate cache, as entry was
  548. already present in the table */
  549. TValue k;
  550. getnodekey(L, &k, old);
  551. newcheckedkey(t, &k, gval(old));
  552. }
  553. }
  554. }
  555. /*
  556. ** Exchange the hash part of 't1' and 't2'. (In 'flags', only the
  557. ** dummy bit must be exchanged: The 'isrealasize' is not related
  558. ** to the hash part, and the metamethod bits do not change during
  559. ** a resize, so the "real" table can keep their values.)
  560. */
  561. static void exchangehashpart (Table *t1, Table *t2) {
  562. lu_byte lsizenode = t1->lsizenode;
  563. Node *node = t1->node;
  564. int bitdummy1 = t1->flags & BITDUMMY;
  565. t1->lsizenode = t2->lsizenode;
  566. t1->node = t2->node;
  567. t1->flags = cast_byte((t1->flags & NOTBITDUMMY) | (t2->flags & BITDUMMY));
  568. t2->lsizenode = lsizenode;
  569. t2->node = node;
  570. t2->flags = cast_byte((t2->flags & NOTBITDUMMY) | bitdummy1);
  571. }
  572. /*
  573. ** Re-insert into the new hash part of a table the elements from the
  574. ** vanishing slice of the array part.
  575. */
  576. static void reinsertOldSlice (Table *t, unsigned oldasize,
  577. unsigned newasize) {
  578. unsigned i;
  579. for (i = newasize; i < oldasize; i++) { /* traverse vanishing slice */
  580. lu_byte tag = *getArrTag(t, i);
  581. if (!tagisempty(tag)) { /* a non-empty entry? */
  582. TValue key, aux;
  583. setivalue(&key, l_castU2S(i) + 1); /* make the key */
  584. farr2val(t, i, tag, &aux); /* copy value into 'aux' */
  585. insertkey(t, &key, &aux); /* insert entry into the hash part */
  586. }
  587. }
  588. }
  589. /*
  590. ** Clear new slice of the array.
  591. */
  592. static void clearNewSlice (Table *t, unsigned oldasize, unsigned newasize) {
  593. for (; oldasize < newasize; oldasize++)
  594. *getArrTag(t, oldasize) = LUA_VEMPTY;
  595. }
  596. /*
  597. ** Resize table 't' for the new given sizes. Both allocations (for
  598. ** the hash part and for the array part) can fail, which creates some
  599. ** subtleties. If the first allocation, for the hash part, fails, an
  600. ** error is raised and that is it. Otherwise, it copies the elements from
  601. ** the shrinking part of the array (if it is shrinking) into the new
  602. ** hash. Then it reallocates the array part. If that fails, the table
  603. ** is in its original state; the function frees the new hash part and then
  604. ** raises the allocation error. Otherwise, it sets the new hash part
  605. ** into the table, initializes the new part of the array (if any) with
  606. ** nils and reinserts the elements of the old hash back into the new
  607. ** parts of the table.
  608. ** Note that if the new size for the array part ('newasize') is equal to
  609. ** the old one ('oldasize'), this function will do nothing with that
  610. ** part.
  611. */
  612. void luaH_resize (lua_State *L, Table *t, unsigned newasize,
  613. unsigned nhsize) {
  614. Table newt; /* to keep the new hash part */
  615. unsigned oldasize = t->asize;
  616. Value *newarray;
  617. if (newasize > MAXASIZE)
  618. luaG_runerror(L, "table overflow");
  619. /* create new hash part with appropriate size into 'newt' */
  620. newt.flags = 0;
  621. setnodevector(L, &newt, nhsize);
  622. if (newasize < oldasize) { /* will array shrink? */
  623. /* re-insert into the new hash the elements from vanishing slice */
  624. exchangehashpart(t, &newt); /* pretend table has new hash */
  625. reinsertOldSlice(t, oldasize, newasize);
  626. exchangehashpart(t, &newt); /* restore old hash (in case of errors) */
  627. }
  628. /* allocate new array */
  629. newarray = resizearray(L, t, oldasize, newasize);
  630. if (l_unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */
  631. freehash(L, &newt); /* release new hash part */
  632. luaM_error(L); /* raise error (with array unchanged) */
  633. }
  634. /* allocation ok; initialize new part of the array */
  635. exchangehashpart(t, &newt); /* 't' has the new hash ('newt' has the old) */
  636. t->array = newarray; /* set new array part */
  637. t->asize = newasize;
  638. if (newarray != NULL)
  639. *lenhint(t) = newasize / 2u; /* set an initial hint */
  640. clearNewSlice(t, oldasize, newasize);
  641. /* re-insert elements from old hash part into new parts */
  642. reinserthash(L, &newt, t); /* 'newt' now has the old hash */
  643. freehash(L, &newt); /* free old hash part */
  644. }
  645. void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
  646. unsigned nsize = allocsizenode(t);
  647. luaH_resize(L, t, nasize, nsize);
  648. }
  649. /*
  650. ** Rehash a table. First, count its keys. If there are array indices
  651. ** outside the array part, compute the new best size for that part.
  652. ** Then, resize the table.
  653. */
  654. static void rehash (lua_State *L, Table *t, const TValue *ek) {
  655. unsigned asize; /* optimal size for array part */
  656. Counters ct;
  657. unsigned i;
  658. unsigned nsize; /* size for the hash part */
  659. /* reset counts */
  660. for (i = 0; i <= MAXABITS; i++) ct.nums[i] = 0;
  661. ct.na = 0;
  662. ct.deleted = 0;
  663. ct.total = 1; /* count extra key */
  664. if (ttisinteger(ek))
  665. countint(ivalue(ek), &ct); /* extra key may go to array */
  666. numusehash(t, &ct); /* count keys in hash part */
  667. if (ct.na == 0) {
  668. /* no new keys to enter array part; keep it with the same size */
  669. asize = t->asize;
  670. }
  671. else { /* compute best size for array part */
  672. numusearray(t, &ct); /* count keys in array part */
  673. asize = computesizes(&ct); /* compute new size for array part */
  674. }
  675. /* all keys not in the array part go to the hash part */
  676. nsize = ct.total - ct.na;
  677. if (ct.deleted) { /* table has deleted entries? */
  678. /* insertion-deletion-insertion: give hash some extra size to
  679. avoid repeated resizings */
  680. nsize += nsize >> 2;
  681. }
  682. /* resize the table to new computed sizes */
  683. luaH_resize(L, t, asize, nsize);
  684. }
  685. /*
  686. ** }=============================================================
  687. */
  688. Table *luaH_new (lua_State *L) {
  689. GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
  690. Table *t = gco2t(o);
  691. t->metatable = NULL;
  692. t->flags = maskflags; /* table has no metamethod fields */
  693. t->array = NULL;
  694. t->asize = 0;
  695. setnodevector(L, t, 0);
  696. return t;
  697. }
  698. lu_mem luaH_size (Table *t) {
  699. lu_mem sz = cast(lu_mem, sizeof(Table)) + concretesize(t->asize);
  700. if (!isdummy(t))
  701. sz += sizehash(t);
  702. return sz;
  703. }
  704. /*
  705. ** Frees a table.
  706. */
  707. void luaH_free (lua_State *L, Table *t) {
  708. freehash(L, t);
  709. resizearray(L, t, t->asize, 0);
  710. luaM_free(L, t);
  711. }
  712. static Node *getfreepos (Table *t) {
  713. if (haslastfree(t)) { /* does it have 'lastfree' information? */
  714. /* look for a spot before 'lastfree', updating 'lastfree' */
  715. while (getlastfree(t) > t->node) {
  716. Node *free = --getlastfree(t);
  717. if (keyisnil(free))
  718. return free;
  719. }
  720. }
  721. else { /* no 'lastfree' information */
  722. unsigned i = sizenode(t);
  723. while (i--) { /* do a linear search */
  724. Node *free = gnode(t, i);
  725. if (keyisnil(free))
  726. return free;
  727. }
  728. }
  729. return NULL; /* could not find a free place */
  730. }
  731. /*
  732. ** Inserts a new key into a hash table; first, check whether key's main
  733. ** position is free. If not, check whether colliding node is in its main
  734. ** position or not: if it is not, move colliding node to an empty place
  735. ** and put new key in its main position; otherwise (colliding node is in
  736. ** its main position), new key goes to an empty position. Return 0 if
  737. ** could not insert key (could not find a free space).
  738. */
  739. static int insertkey (Table *t, const TValue *key, TValue *value) {
  740. Node *mp = mainpositionTV(t, key);
  741. /* table cannot already contain the key */
  742. lua_assert(isabstkey(getgeneric(t, key, 0)));
  743. if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */
  744. Node *othern;
  745. Node *f = getfreepos(t); /* get a free place */
  746. if (f == NULL) /* cannot find a free place? */
  747. return 0;
  748. lua_assert(!isdummy(t));
  749. othern = mainpositionfromnode(t, mp);
  750. if (othern != mp) { /* is colliding node out of its main position? */
  751. /* yes; move colliding node into free position */
  752. while (othern + gnext(othern) != mp) /* find previous */
  753. othern += gnext(othern);
  754. gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */
  755. *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  756. if (gnext(mp) != 0) {
  757. gnext(f) += cast_int(mp - f); /* correct 'next' */
  758. gnext(mp) = 0; /* now 'mp' is free */
  759. }
  760. setempty(gval(mp));
  761. }
  762. else { /* colliding node is in its own main position */
  763. /* new node will go into free position */
  764. if (gnext(mp) != 0)
  765. gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */
  766. else lua_assert(gnext(f) == 0);
  767. gnext(mp) = cast_int(f - mp);
  768. mp = f;
  769. }
  770. }
  771. setnodekey(mp, key);
  772. lua_assert(isempty(gval(mp)));
  773. setobj2t(cast(lua_State *, 0), gval(mp), value);
  774. return 1;
  775. }
  776. /*
  777. ** Insert a key in a table where there is space for that key, the
  778. ** key is valid, and the value is not nil.
  779. */
  780. static void newcheckedkey (Table *t, const TValue *key, TValue *value) {
  781. unsigned i = keyinarray(t, key);
  782. if (i > 0) /* is key in the array part? */
  783. obj2arr(t, i - 1, value); /* set value in the array */
  784. else {
  785. int done = insertkey(t, key, value); /* insert key in the hash part */
  786. lua_assert(done); /* it cannot fail */
  787. cast(void, done); /* to avoid warnings */
  788. }
  789. }
  790. static void luaH_newkey (lua_State *L, Table *t, const TValue *key,
  791. TValue *value) {
  792. if (!ttisnil(value)) { /* do not insert nil values */
  793. int done = insertkey(t, key, value);
  794. if (!done) { /* could not find a free place? */
  795. rehash(L, t, key); /* grow table */
  796. newcheckedkey(t, key, value); /* insert key in grown table */
  797. }
  798. luaC_barrierback(L, obj2gco(t), key);
  799. /* for debugging only: any new key may force an emergency collection */
  800. condchangemem(L, (void)0, (void)0, 1);
  801. }
  802. }
  803. static const TValue *getintfromhash (Table *t, lua_Integer key) {
  804. Node *n = hashint(t, key);
  805. lua_assert(!ikeyinarray(t, key));
  806. for (;;) { /* check whether 'key' is somewhere in the chain */
  807. if (keyisinteger(n) && keyival(n) == key)
  808. return gval(n); /* that's it */
  809. else {
  810. int nx = gnext(n);
  811. if (nx == 0) break;
  812. n += nx;
  813. }
  814. }
  815. return &absentkey;
  816. }
  817. static int hashkeyisempty (Table *t, lua_Unsigned key) {
  818. const TValue *val = getintfromhash(t, l_castU2S(key));
  819. return isempty(val);
  820. }
  821. static lu_byte finishnodeget (const TValue *val, TValue *res) {
  822. if (!ttisnil(val)) {
  823. setobj(((lua_State*)NULL), res, val);
  824. }
  825. return ttypetag(val);
  826. }
  827. lu_byte luaH_getint (Table *t, lua_Integer key, TValue *res) {
  828. unsigned k = ikeyinarray(t, key);
  829. if (k > 0) {
  830. lu_byte tag = *getArrTag(t, k - 1);
  831. if (!tagisempty(tag))
  832. farr2val(t, k - 1, tag, res);
  833. return tag;
  834. }
  835. else
  836. return finishnodeget(getintfromhash(t, key), res);
  837. }
  838. /*
  839. ** search function for short strings
  840. */
  841. const TValue *luaH_Hgetshortstr (Table *t, TString *key) {
  842. Node *n = hashstr(t, key);
  843. lua_assert(strisshr(key));
  844. for (;;) { /* check whether 'key' is somewhere in the chain */
  845. if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
  846. return gval(n); /* that's it */
  847. else {
  848. int nx = gnext(n);
  849. if (nx == 0)
  850. return &absentkey; /* not found */
  851. n += nx;
  852. }
  853. }
  854. }
  855. lu_byte luaH_getshortstr (Table *t, TString *key, TValue *res) {
  856. return finishnodeget(luaH_Hgetshortstr(t, key), res);
  857. }
  858. static const TValue *Hgetlongstr (Table *t, TString *key) {
  859. TValue ko;
  860. lua_assert(!strisshr(key));
  861. setsvalue(cast(lua_State *, NULL), &ko, key);
  862. return getgeneric(t, &ko, 0); /* for long strings, use generic case */
  863. }
  864. static const TValue *Hgetstr (Table *t, TString *key) {
  865. if (strisshr(key))
  866. return luaH_Hgetshortstr(t, key);
  867. else
  868. return Hgetlongstr(t, key);
  869. }
  870. lu_byte luaH_getstr (Table *t, TString *key, TValue *res) {
  871. return finishnodeget(Hgetstr(t, key), res);
  872. }
  873. /*
  874. ** main search function
  875. */
  876. lu_byte luaH_get (Table *t, const TValue *key, TValue *res) {
  877. const TValue *slot;
  878. switch (ttypetag(key)) {
  879. case LUA_VSHRSTR:
  880. slot = luaH_Hgetshortstr(t, tsvalue(key));
  881. break;
  882. case LUA_VNUMINT:
  883. return luaH_getint(t, ivalue(key), res);
  884. case LUA_VNIL:
  885. slot = &absentkey;
  886. break;
  887. case LUA_VNUMFLT: {
  888. lua_Integer k;
  889. if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
  890. return luaH_getint(t, k, res); /* use specialized version */
  891. /* else... */
  892. } /* FALLTHROUGH */
  893. default:
  894. slot = getgeneric(t, key, 0);
  895. break;
  896. }
  897. return finishnodeget(slot, res);
  898. }
  899. /*
  900. ** When a 'pset' cannot be completed, this function returns an encoding
  901. ** of its result, to be used by 'luaH_finishset'.
  902. */
  903. static int retpsetcode (Table *t, const TValue *slot) {
  904. if (isabstkey(slot))
  905. return HNOTFOUND; /* no slot with that key */
  906. else /* return node encoded */
  907. return cast_int((cast(Node*, slot) - t->node)) + HFIRSTNODE;
  908. }
  909. static int finishnodeset (Table *t, const TValue *slot, TValue *val) {
  910. if (!ttisnil(slot)) {
  911. setobj(((lua_State*)NULL), cast(TValue*, slot), val);
  912. return HOK; /* success */
  913. }
  914. else
  915. return retpsetcode(t, slot);
  916. }
  917. static int rawfinishnodeset (const TValue *slot, TValue *val) {
  918. if (isabstkey(slot))
  919. return 0; /* no slot with that key */
  920. else {
  921. setobj(((lua_State*)NULL), cast(TValue*, slot), val);
  922. return 1; /* success */
  923. }
  924. }
  925. int luaH_psetint (Table *t, lua_Integer key, TValue *val) {
  926. lua_assert(!ikeyinarray(t, key));
  927. return finishnodeset(t, getintfromhash(t, key), val);
  928. }
  929. static int psetint (Table *t, lua_Integer key, TValue *val) {
  930. int hres;
  931. luaH_fastseti(t, key, val, hres);
  932. return hres;
  933. }
  934. /*
  935. ** This function could be just this:
  936. ** return finishnodeset(t, luaH_Hgetshortstr(t, key), val);
  937. ** However, it optimizes the common case created by constructors (e.g.,
  938. ** {x=1, y=2}), which creates a key in a table that has no metatable,
  939. ** it is not old/black, and it already has space for the key.
  940. */
  941. int luaH_psetshortstr (Table *t, TString *key, TValue *val) {
  942. const TValue *slot = luaH_Hgetshortstr(t, key);
  943. if (!ttisnil(slot)) { /* key already has a value? (all too common) */
  944. setobj(((lua_State*)NULL), cast(TValue*, slot), val); /* update it */
  945. return HOK; /* done */
  946. }
  947. else if (checknoTM(t->metatable, TM_NEWINDEX)) { /* no metamethod? */
  948. if (ttisnil(val)) /* new value is nil? */
  949. return HOK; /* done (value is already nil/absent) */
  950. if (isabstkey(slot) && /* key is absent? */
  951. !(isblack(t) && iswhite(key))) { /* and don't need barrier? */
  952. TValue tk; /* key as a TValue */
  953. setsvalue(cast(lua_State *, NULL), &tk, key);
  954. if (insertkey(t, &tk, val)) { /* insert key, if there is space */
  955. invalidateTMcache(t);
  956. return HOK;
  957. }
  958. }
  959. }
  960. /* Else, either table has new-index metamethod, or it needs barrier,
  961. or it needs to rehash for the new key. In any of these cases, the
  962. operation cannot be completed here. Return a code for the caller. */
  963. return retpsetcode(t, slot);
  964. }
  965. int luaH_psetstr (Table *t, TString *key, TValue *val) {
  966. if (strisshr(key))
  967. return luaH_psetshortstr(t, key, val);
  968. else
  969. return finishnodeset(t, Hgetlongstr(t, key), val);
  970. }
  971. int luaH_pset (Table *t, const TValue *key, TValue *val) {
  972. switch (ttypetag(key)) {
  973. case LUA_VSHRSTR: return luaH_psetshortstr(t, tsvalue(key), val);
  974. case LUA_VNUMINT: return psetint(t, ivalue(key), val);
  975. case LUA_VNIL: return HNOTFOUND;
  976. case LUA_VNUMFLT: {
  977. lua_Integer k;
  978. if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
  979. return psetint(t, k, val); /* use specialized version */
  980. /* else... */
  981. } /* FALLTHROUGH */
  982. default:
  983. return finishnodeset(t, getgeneric(t, key, 0), val);
  984. }
  985. }
  986. /*
  987. ** Finish a raw "set table" operation, where 'hres' encodes where the
  988. ** value should have been (the result of a previous 'pset' operation).
  989. ** Beware: when using this function the caller probably need to check a
  990. ** GC barrier and invalidate the TM cache.
  991. */
  992. void luaH_finishset (lua_State *L, Table *t, const TValue *key,
  993. TValue *value, int hres) {
  994. lua_assert(hres != HOK);
  995. if (hres == HNOTFOUND) {
  996. TValue aux;
  997. if (l_unlikely(ttisnil(key)))
  998. luaG_runerror(L, "table index is nil");
  999. else if (ttisfloat(key)) {
  1000. lua_Number f = fltvalue(key);
  1001. lua_Integer k;
  1002. if (luaV_flttointeger(f, &k, F2Ieq)) {
  1003. setivalue(&aux, k); /* key is equal to an integer */
  1004. key = &aux; /* insert it as an integer */
  1005. }
  1006. else if (l_unlikely(luai_numisnan(f)))
  1007. luaG_runerror(L, "table index is NaN");
  1008. }
  1009. luaH_newkey(L, t, key, value);
  1010. }
  1011. else if (hres > 0) { /* regular Node? */
  1012. setobj2t(L, gval(gnode(t, hres - HFIRSTNODE)), value);
  1013. }
  1014. else { /* array entry */
  1015. hres = ~hres; /* real index */
  1016. obj2arr(t, cast_uint(hres), value);
  1017. }
  1018. }
  1019. /*
  1020. ** beware: when using this function you probably need to check a GC
  1021. ** barrier and invalidate the TM cache.
  1022. */
  1023. void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) {
  1024. int hres = luaH_pset(t, key, value);
  1025. if (hres != HOK)
  1026. luaH_finishset(L, t, key, value, hres);
  1027. }
  1028. /*
  1029. ** Ditto for a GC barrier. (No need to invalidate the TM cache, as
  1030. ** integers cannot be keys to metamethods.)
  1031. */
  1032. void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
  1033. unsigned ik = ikeyinarray(t, key);
  1034. if (ik > 0)
  1035. obj2arr(t, ik - 1, value);
  1036. else {
  1037. int ok = rawfinishnodeset(getintfromhash(t, key), value);
  1038. if (!ok) {
  1039. TValue k;
  1040. setivalue(&k, key);
  1041. luaH_newkey(L, t, &k, value);
  1042. }
  1043. }
  1044. }
  1045. /*
  1046. ** Try to find a boundary in the hash part of table 't'. From the
  1047. ** caller, we know that 'j' is zero or present and that 'j + 1' is
  1048. ** present. We want to find a larger key that is absent from the
  1049. ** table, so that we can do a binary search between the two keys to
  1050. ** find a boundary. We keep doubling 'j' until we get an absent index.
  1051. ** If the doubling would overflow, we try LUA_MAXINTEGER. If it is
  1052. ** absent, we are ready for the binary search. ('j', being max integer,
  1053. ** is larger or equal to 'i', but it cannot be equal because it is
  1054. ** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a
  1055. ** boundary. ('j + 1' cannot be a present integer key because it is
  1056. ** not a valid integer in Lua.)
  1057. */
  1058. static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
  1059. lua_Unsigned i;
  1060. if (j == 0) j++; /* the caller ensures 'j + 1' is present */
  1061. do {
  1062. i = j; /* 'i' is a present index */
  1063. if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
  1064. j *= 2;
  1065. else {
  1066. j = LUA_MAXINTEGER;
  1067. if (hashkeyisempty(t, j)) /* t[j] not present? */
  1068. break; /* 'j' now is an absent index */
  1069. else /* weird case */
  1070. return j; /* well, max integer is a boundary... */
  1071. }
  1072. } while (!hashkeyisempty(t, j)); /* repeat until an absent t[j] */
  1073. /* i < j && t[i] present && t[j] absent */
  1074. while (j - i > 1u) { /* do a binary search between them */
  1075. lua_Unsigned m = (i + j) / 2;
  1076. if (hashkeyisempty(t, m)) j = m;
  1077. else i = m;
  1078. }
  1079. return i;
  1080. }
  1081. static unsigned int binsearch (Table *array, unsigned int i, unsigned int j) {
  1082. lua_assert(i <= j);
  1083. while (j - i > 1u) { /* binary search */
  1084. unsigned int m = (i + j) / 2;
  1085. if (arraykeyisempty(array, m)) j = m;
  1086. else i = m;
  1087. }
  1088. return i;
  1089. }
  1090. /* return a border, saving it as a hint for next call */
  1091. static lua_Unsigned newhint (Table *t, unsigned hint) {
  1092. lua_assert(hint <= t->asize);
  1093. *lenhint(t) = hint;
  1094. return hint;
  1095. }
  1096. /*
  1097. ** Try to find a border in table 't'. (A 'border' is an integer index
  1098. ** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent,
  1099. ** or 'maxinteger' if t[maxinteger] is present.)
  1100. ** If there is an array part, try to find a border there. First try
  1101. ** to find it in the vicinity of the previous result (hint), to handle
  1102. ** cases like 't[#t + 1] = val' or 't[#t] = nil', that move the border
  1103. ** by one entry. Otherwise, do a binary search to find the border.
  1104. ** If there is no array part, or its last element is non empty, the
  1105. ** border may be in the hash part.
  1106. */
  1107. lua_Unsigned luaH_getn (Table *t) {
  1108. unsigned asize = t->asize;
  1109. if (asize > 0) { /* is there an array part? */
  1110. const unsigned maxvicinity = 4;
  1111. unsigned limit = *lenhint(t); /* start with the hint */
  1112. if (limit == 0)
  1113. limit = 1; /* make limit a valid index in the array */
  1114. if (arraykeyisempty(t, limit)) { /* t[limit] empty? */
  1115. /* there must be a border before 'limit' */
  1116. unsigned i;
  1117. /* look for a border in the vicinity of the hint */
  1118. for (i = 0; i < maxvicinity && limit > 1; i++) {
  1119. limit--;
  1120. if (!arraykeyisempty(t, limit))
  1121. return newhint(t, limit); /* 'limit' is a border */
  1122. }
  1123. /* t[limit] still empty; search for a border in [0, limit) */
  1124. return newhint(t, binsearch(t, 0, limit));
  1125. }
  1126. else { /* 'limit' is present in table; look for a border after it */
  1127. unsigned i;
  1128. /* look for a border in the vicinity of the hint */
  1129. for (i = 0; i < maxvicinity && limit < asize; i++) {
  1130. limit++;
  1131. if (arraykeyisempty(t, limit))
  1132. return newhint(t, limit - 1); /* 'limit - 1' is a border */
  1133. }
  1134. if (arraykeyisempty(t, asize)) { /* last element empty? */
  1135. /* t[limit] not empty; search for a border in [limit, asize) */
  1136. return newhint(t, binsearch(t, limit, asize));
  1137. }
  1138. }
  1139. /* last element non empty; set a hint to speed up finding that again */
  1140. /* (keys in the hash part cannot be hints) */
  1141. *lenhint(t) = asize;
  1142. }
  1143. /* no array part or t[asize] is not empty; check the hash part */
  1144. lua_assert(asize == 0 || !arraykeyisempty(t, asize));
  1145. if (isdummy(t) || hashkeyisempty(t, asize + 1))
  1146. return asize; /* 'asize + 1' is empty */
  1147. else /* 'asize + 1' is also non empty */
  1148. return hash_search(t, asize);
  1149. }
  1150. #if defined(LUA_DEBUG)
  1151. /* export this function for the test library */
  1152. Node *luaH_mainposition (const Table *t, const TValue *key) {
  1153. return mainpositionTV(t, key);
  1154. }
  1155. #endif