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