ltable.c 40 KB

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