ltable.c 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  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. ** Compute the optimal size for the array part of table 't'. 'nums' is a
  392. ** "count array" where 'nums[i]' is the number of integers in the table
  393. ** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of
  394. ** integer keys in the table and leaves with the number of keys that
  395. ** will go to the array part; return the optimal size. (The condition
  396. ** 'twotoi > 0' in the for loop stops the loop if 'twotoi' overflows.)
  397. */
  398. static unsigned computesizes (unsigned nums[], unsigned *pna) {
  399. int i;
  400. unsigned int twotoi; /* 2^i (candidate for optimal size) */
  401. unsigned int a = 0; /* number of elements smaller than 2^i */
  402. unsigned int na = 0; /* number of elements to go to array part */
  403. unsigned int optimal = 0; /* optimal size for array part */
  404. /* loop while keys can fill more than half of total size */
  405. for (i = 0, twotoi = 1;
  406. twotoi > 0 && *pna > twotoi / 2;
  407. i++, twotoi *= 2) {
  408. a += nums[i];
  409. if (a > twotoi/2) { /* more than half elements present? */
  410. optimal = twotoi; /* optimal size (till now) */
  411. na = a; /* all elements up to 'optimal' will go to array part */
  412. }
  413. }
  414. lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal);
  415. *pna = na;
  416. return optimal;
  417. }
  418. static unsigned countint (lua_Integer key, unsigned int *nums) {
  419. unsigned int k = arrayindex(key);
  420. if (k != 0) { /* is 'key' an appropriate array index? */
  421. nums[luaO_ceillog2(k)]++; /* count as such */
  422. return 1;
  423. }
  424. else
  425. return 0;
  426. }
  427. l_sinline int arraykeyisempty (const Table *t, lua_Unsigned key) {
  428. int tag = *getArrTag(t, key - 1);
  429. return tagisempty(tag);
  430. }
  431. /*
  432. ** Count keys in array part of table 't': Fill 'nums[i]' with
  433. ** number of keys that will go into corresponding slice and return
  434. ** total number of non-nil keys.
  435. */
  436. static unsigned numusearray (const Table *t, unsigned *nums) {
  437. int lg;
  438. unsigned int ttlg; /* 2^lg */
  439. unsigned int ause = 0; /* summation of 'nums' */
  440. unsigned int i = 1; /* index to traverse all array keys */
  441. unsigned int asize = limitasasize(t); /* real array size */
  442. /* traverse each slice */
  443. for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
  444. unsigned int lc = 0; /* counter */
  445. unsigned int lim = ttlg;
  446. if (lim > asize) {
  447. lim = asize; /* adjust upper limit */
  448. if (i > lim)
  449. break; /* no more elements to count */
  450. }
  451. /* count elements in range (2^(lg - 1), 2^lg] */
  452. for (; i <= lim; i++) {
  453. if (!arraykeyisempty(t, i))
  454. lc++;
  455. }
  456. nums[lg] += lc;
  457. ause += lc;
  458. }
  459. return ause;
  460. }
  461. static unsigned numusehash (const Table *t, unsigned *nums, unsigned *pna) {
  462. unsigned totaluse = 0; /* total number of elements */
  463. unsigned ause = 0; /* elements added to 'nums' (can go to array part) */
  464. unsigned i = sizenode(t);
  465. while (i--) {
  466. Node *n = &t->node[i];
  467. if (!isempty(gval(n))) {
  468. if (keyisinteger(n))
  469. ause += countint(keyival(n), nums);
  470. totaluse++;
  471. }
  472. }
  473. *pna += ause;
  474. return totaluse;
  475. }
  476. /*
  477. ** Convert an "abstract size" (number of slots in an array) to
  478. ** "concrete size" (number of bytes in the array).
  479. */
  480. static size_t concretesize (unsigned int size) {
  481. return size * sizeof(Value) + size; /* space for the two arrays */
  482. }
  483. /*
  484. ** Resize the array part of a table. If new size is equal to the old,
  485. ** do nothing. Else, if new size is zero, free the old array. (It must
  486. ** be present, as the sizes are different.) Otherwise, allocate a new
  487. ** array, move the common elements to new proper position, and then
  488. ** frees old array.
  489. ** When array grows, we could reallocate it, but we still would need
  490. ** to move the elements to their new position, so the copy implicit
  491. ** in realloc is a waste. When array shrinks, it always erases some
  492. ** elements that should still be in the array, so we must reallocate in
  493. ** two steps anyway. It is simpler to always reallocate in two steps.
  494. */
  495. static Value *resizearray (lua_State *L , Table *t,
  496. unsigned oldasize,
  497. unsigned newasize) {
  498. if (oldasize == newasize)
  499. return t->array; /* nothing to be done */
  500. else if (newasize == 0) { /* erasing array? */
  501. Value *op = t->array - oldasize; /* original array's real address */
  502. luaM_freemem(L, op, concretesize(oldasize)); /* free it */
  503. return NULL;
  504. }
  505. else {
  506. size_t newasizeb = concretesize(newasize);
  507. Value *np = cast(Value *,
  508. luaM_reallocvector(L, NULL, 0, newasizeb, lu_byte));
  509. if (np == NULL) /* allocation error? */
  510. return NULL;
  511. if (oldasize > 0) {
  512. Value *op = t->array - oldasize; /* real original array */
  513. unsigned tomove = (oldasize < newasize) ? oldasize : newasize;
  514. lua_assert(tomove > 0);
  515. /* move common elements to new position */
  516. memcpy(np + newasize - tomove,
  517. op + oldasize - tomove,
  518. concretesize(tomove));
  519. luaM_freemem(L, op, concretesize(oldasize));
  520. }
  521. return np + newasize; /* shift pointer to the end of value segment */
  522. }
  523. }
  524. /*
  525. ** Creates an array for the hash part of a table with the given
  526. ** size, or reuses the dummy node if size is zero.
  527. ** The computation for size overflow is in two steps: the first
  528. ** comparison ensures that the shift in the second one does not
  529. ** overflow.
  530. */
  531. static void setnodevector (lua_State *L, Table *t, unsigned size) {
  532. if (size == 0) { /* no elements to hash part? */
  533. t->node = cast(Node *, dummynode); /* use common 'dummynode' */
  534. t->lsizenode = 0;
  535. setdummy(t); /* signal that it is using dummy node */
  536. }
  537. else {
  538. int i;
  539. int lsize = luaO_ceillog2(size);
  540. if (lsize > MAXHBITS || (1u << lsize) > MAXHSIZE)
  541. luaG_runerror(L, "table overflow");
  542. size = twoto(lsize);
  543. if (lsize <= LIMFORLAST) /* no 'lastfree' field? */
  544. t->node = luaM_newvector(L, size, Node);
  545. else {
  546. size_t bsize = size * sizeof(Node) + sizeof(Limbox);
  547. char *node = luaM_newblock(L, bsize);
  548. t->node = cast(Node *, node + sizeof(Limbox));
  549. getlastfree(t) = gnode(t, size); /* all positions are free */
  550. }
  551. t->lsizenode = cast_byte(lsize);
  552. setnodummy(t);
  553. for (i = 0; i < cast_int(size); i++) {
  554. Node *n = gnode(t, i);
  555. gnext(n) = 0;
  556. setnilkey(n);
  557. setempty(gval(n));
  558. }
  559. }
  560. }
  561. /*
  562. ** (Re)insert all elements from the hash part of 'ot' into table 't'.
  563. */
  564. static void reinsert (lua_State *L, Table *ot, Table *t) {
  565. unsigned j;
  566. unsigned size = sizenode(ot);
  567. for (j = 0; j < size; j++) {
  568. Node *old = gnode(ot, j);
  569. if (!isempty(gval(old))) {
  570. /* doesn't need barrier/invalidate cache, as entry was
  571. already present in the table */
  572. TValue k;
  573. getnodekey(L, &k, old);
  574. luaH_set(L, t, &k, gval(old));
  575. }
  576. }
  577. }
  578. /*
  579. ** Exchange the hash part of 't1' and 't2'. (In 'flags', only the
  580. ** dummy bit must be exchanged: The 'isrealasize' is not related
  581. ** to the hash part, and the metamethod bits do not change during
  582. ** a resize, so the "real" table can keep their values.)
  583. */
  584. static void exchangehashpart (Table *t1, Table *t2) {
  585. lu_byte lsizenode = t1->lsizenode;
  586. Node *node = t1->node;
  587. int bitdummy1 = t1->flags & BITDUMMY;
  588. t1->lsizenode = t2->lsizenode;
  589. t1->node = t2->node;
  590. t1->flags = cast_byte((t1->flags & NOTBITDUMMY) | (t2->flags & BITDUMMY));
  591. t2->lsizenode = lsizenode;
  592. t2->node = node;
  593. t2->flags = cast_byte((t2->flags & NOTBITDUMMY) | bitdummy1);
  594. }
  595. /*
  596. ** Re-insert into the new hash part of a table the elements from the
  597. ** vanishing slice of the array part.
  598. */
  599. static void reinsertOldSlice (lua_State *L, Table *t, unsigned oldasize,
  600. unsigned newasize) {
  601. unsigned i;
  602. t->alimit = newasize; /* pretend array has new size... */
  603. for (i = newasize; i < oldasize; i++) { /* traverse vanishing slice */
  604. lu_byte tag = *getArrTag(t, i);
  605. if (!tagisempty(tag)) { /* a non-empty entry? */
  606. TValue aux;
  607. farr2val(t, i, tag, &aux); /* copy entry into 'aux' */
  608. /* re-insert it into the table */
  609. luaH_setint(L, t, cast_int(i) + 1, &aux);
  610. }
  611. }
  612. t->alimit = oldasize; /* restore current size... */
  613. }
  614. /*
  615. ** Clear new slice of the array.
  616. */
  617. static void clearNewSlice (Table *t, unsigned oldasize, unsigned newasize) {
  618. for (; oldasize < newasize; oldasize++)
  619. *getArrTag(t, oldasize) = LUA_VEMPTY;
  620. }
  621. /*
  622. ** Resize table 't' for the new given sizes. Both allocations (for
  623. ** the hash part and for the array part) can fail, which creates some
  624. ** subtleties. If the first allocation, for the hash part, fails, an
  625. ** error is raised and that is it. Otherwise, it copies the elements from
  626. ** the shrinking part of the array (if it is shrinking) into the new
  627. ** hash. Then it reallocates the array part. If that fails, the table
  628. ** is in its original state; the function frees the new hash part and then
  629. ** raises the allocation error. Otherwise, it sets the new hash part
  630. ** into the table, initializes the new part of the array (if any) with
  631. ** nils and reinserts the elements of the old hash back into the new
  632. ** parts of the table.
  633. */
  634. void luaH_resize (lua_State *L, Table *t, unsigned newasize,
  635. unsigned nhsize) {
  636. Table newt; /* to keep the new hash part */
  637. unsigned int oldasize = setlimittosize(t);
  638. Value *newarray;
  639. if (newasize > MAXASIZE)
  640. luaG_runerror(L, "table overflow");
  641. /* create new hash part with appropriate size into 'newt' */
  642. newt.flags = 0;
  643. setnodevector(L, &newt, nhsize);
  644. if (newasize < oldasize) { /* will array shrink? */
  645. /* re-insert into the new hash the elements from vanishing slice */
  646. exchangehashpart(t, &newt); /* pretend table has new hash */
  647. reinsertOldSlice(L, t, oldasize, newasize);
  648. exchangehashpart(t, &newt); /* restore old hash (in case of errors) */
  649. }
  650. /* allocate new array */
  651. newarray = resizearray(L, t, oldasize, newasize);
  652. if (l_unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */
  653. freehash(L, &newt); /* release new hash part */
  654. luaM_error(L); /* raise error (with array unchanged) */
  655. }
  656. /* allocation ok; initialize new part of the array */
  657. exchangehashpart(t, &newt); /* 't' has the new hash ('newt' has the old) */
  658. t->array = newarray; /* set new array part */
  659. t->alimit = newasize;
  660. clearNewSlice(t, oldasize, newasize);
  661. /* re-insert elements from old hash part into new parts */
  662. reinsert(L, &newt, t); /* 'newt' now has the old hash */
  663. freehash(L, &newt); /* free old hash part */
  664. }
  665. void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
  666. unsigned nsize = allocsizenode(t);
  667. luaH_resize(L, t, nasize, nsize);
  668. }
  669. /*
  670. ** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
  671. */
  672. static void rehash (lua_State *L, Table *t, const TValue *ek) {
  673. unsigned asize; /* optimal size for array part */
  674. unsigned na = 0; /* number of keys candidate for the array part */
  675. unsigned nums[MAXABITS + 1];
  676. unsigned i;
  677. unsigned totaluse; /* total number of keys */
  678. for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */
  679. setlimittosize(t);
  680. totaluse = 1; /* count extra key */
  681. if (ttisinteger(ek))
  682. na += countint(ivalue(ek), nums); /* extra key may go to array */
  683. totaluse += numusehash(t, nums, &na); /* count keys in hash part */
  684. if (na == 0) {
  685. /* no new keys to enter array part; keep it with the same size */
  686. asize = luaH_realasize(t);
  687. }
  688. else { /* compute best size for array part */
  689. unsigned n = numusearray(t, nums); /* count keys in array part */
  690. totaluse += n; /* all keys in array part are keys */
  691. na += n; /* all keys in array part are candidates for new array part */
  692. asize = computesizes(nums, &na); /* compute new size for array part */
  693. }
  694. /* resize the table to new computed sizes */
  695. luaH_resize(L, t, asize, totaluse - na);
  696. }
  697. /*
  698. ** }=============================================================
  699. */
  700. Table *luaH_new (lua_State *L) {
  701. GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
  702. Table *t = gco2t(o);
  703. t->metatable = NULL;
  704. t->flags = maskflags; /* table has no metamethod fields */
  705. t->array = NULL;
  706. t->alimit = 0;
  707. setnodevector(L, t, 0);
  708. return t;
  709. }
  710. size_t luaH_size (Table *t) {
  711. size_t sz = sizeof(Table)
  712. + luaH_realasize(t) * (sizeof(Value) + 1);
  713. if (!isdummy(t)) {
  714. sz += sizenode(t) * sizeof(Node);
  715. if (haslastfree(t))
  716. sz += sizeof(Limbox);
  717. }
  718. return sz;
  719. }
  720. /*
  721. ** Frees a table.
  722. */
  723. void luaH_free (lua_State *L, Table *t) {
  724. unsigned int realsize = luaH_realasize(t);
  725. freehash(L, t);
  726. resizearray(L, t, realsize, 0);
  727. luaM_free(L, t);
  728. }
  729. static Node *getfreepos (Table *t) {
  730. if (haslastfree(t)) { /* does it have 'lastfree' information? */
  731. /* look for a spot before 'lastfree', updating 'lastfree' */
  732. while (getlastfree(t) > t->node) {
  733. Node *free = --getlastfree(t);
  734. if (keyisnil(free))
  735. return free;
  736. }
  737. }
  738. else { /* no 'lastfree' information */
  739. if (!isdummy(t)) {
  740. unsigned i = sizenode(t);
  741. while (i--) { /* do a linear search */
  742. Node *free = gnode(t, i);
  743. if (keyisnil(free))
  744. return free;
  745. }
  746. }
  747. }
  748. return NULL; /* could not find a free place */
  749. }
  750. /*
  751. ** Inserts a new key into a hash table; first, check whether key's main
  752. ** position is free. If not, check whether colliding node is in its main
  753. ** position or not: if it is not, move colliding node to an empty place
  754. ** and put new key in its main position; otherwise (colliding node is in
  755. ** its main position), new key goes to an empty position.
  756. */
  757. static void luaH_newkey (lua_State *L, Table *t, const TValue *key,
  758. TValue *value) {
  759. Node *mp;
  760. TValue aux;
  761. if (l_unlikely(ttisnil(key)))
  762. luaG_runerror(L, "table index is nil");
  763. else if (ttisfloat(key)) {
  764. lua_Number f = fltvalue(key);
  765. lua_Integer k;
  766. if (luaV_flttointeger(f, &k, F2Ieq)) { /* does key fit in an integer? */
  767. setivalue(&aux, k);
  768. key = &aux; /* insert it as an integer */
  769. }
  770. else if (l_unlikely(luai_numisnan(f)))
  771. luaG_runerror(L, "table index is NaN");
  772. }
  773. if (ttisnil(value))
  774. return; /* do not insert nil values */
  775. mp = mainpositionTV(t, key);
  776. if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */
  777. Node *othern;
  778. Node *f = getfreepos(t); /* get a free place */
  779. if (f == NULL) { /* cannot find a free place? */
  780. rehash(L, t, key); /* grow table */
  781. /* whatever called 'newkey' takes care of TM cache */
  782. luaH_set(L, t, key, value); /* insert key into grown table */
  783. return;
  784. }
  785. lua_assert(!isdummy(t));
  786. othern = mainpositionfromnode(t, mp);
  787. if (othern != mp) { /* is colliding node out of its main position? */
  788. /* yes; move colliding node into free position */
  789. while (othern + gnext(othern) != mp) /* find previous */
  790. othern += gnext(othern);
  791. gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */
  792. *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  793. if (gnext(mp) != 0) {
  794. gnext(f) += cast_int(mp - f); /* correct 'next' */
  795. gnext(mp) = 0; /* now 'mp' is free */
  796. }
  797. setempty(gval(mp));
  798. }
  799. else { /* colliding node is in its own main position */
  800. /* new node will go into free position */
  801. if (gnext(mp) != 0)
  802. gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */
  803. else lua_assert(gnext(f) == 0);
  804. gnext(mp) = cast_int(f - mp);
  805. mp = f;
  806. }
  807. }
  808. setnodekey(L, mp, key);
  809. luaC_barrierback(L, obj2gco(t), key);
  810. lua_assert(isempty(gval(mp)));
  811. setobj2t(L, gval(mp), value);
  812. }
  813. static const TValue *getintfromhash (Table *t, lua_Integer key) {
  814. Node *n = hashint(t, key);
  815. lua_assert(l_castS2U(key) - 1u >= luaH_realasize(t));
  816. for (;;) { /* check whether 'key' is somewhere in the chain */
  817. if (keyisinteger(n) && keyival(n) == key)
  818. return gval(n); /* that's it */
  819. else {
  820. int nx = gnext(n);
  821. if (nx == 0) break;
  822. n += nx;
  823. }
  824. }
  825. return &absentkey;
  826. }
  827. static int hashkeyisempty (Table *t, lua_Unsigned key) {
  828. const TValue *val = getintfromhash(t, l_castU2S(key));
  829. return isempty(val);
  830. }
  831. static lu_byte finishnodeget (const TValue *val, TValue *res) {
  832. if (!ttisnil(val)) {
  833. setobj(((lua_State*)NULL), res, val);
  834. }
  835. return ttypetag(val);
  836. }
  837. lu_byte luaH_getint (Table *t, lua_Integer key, TValue *res) {
  838. if (keyinarray(t, key)) {
  839. lu_byte tag = *getArrTag(t, key - 1);
  840. if (!tagisempty(tag))
  841. farr2val(t, cast_uint(key) - 1, tag, res);
  842. return tag;
  843. }
  844. else
  845. return finishnodeget(getintfromhash(t, key), res);
  846. }
  847. /*
  848. ** search function for short strings
  849. */
  850. const TValue *luaH_Hgetshortstr (Table *t, TString *key) {
  851. Node *n = hashstr(t, key);
  852. lua_assert(key->tt == LUA_VSHRSTR);
  853. for (;;) { /* check whether 'key' is somewhere in the chain */
  854. if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
  855. return gval(n); /* that's it */
  856. else {
  857. int nx = gnext(n);
  858. if (nx == 0)
  859. return &absentkey; /* not found */
  860. n += nx;
  861. }
  862. }
  863. }
  864. lu_byte luaH_getshortstr (Table *t, TString *key, TValue *res) {
  865. return finishnodeget(luaH_Hgetshortstr(t, key), res);
  866. }
  867. static const TValue *Hgetstr (Table *t, TString *key) {
  868. if (key->tt == LUA_VSHRSTR)
  869. return luaH_Hgetshortstr(t, key);
  870. else { /* for long strings, use generic case */
  871. TValue ko;
  872. setsvalue(cast(lua_State *, NULL), &ko, key);
  873. return getgeneric(t, &ko, 0);
  874. }
  875. }
  876. lu_byte luaH_getstr (Table *t, TString *key, TValue *res) {
  877. return finishnodeget(Hgetstr(t, key), res);
  878. }
  879. TString *luaH_getstrkey (Table *t, TString *key) {
  880. const TValue *o = Hgetstr(t, key);
  881. if (!isabstkey(o)) /* string already present? */
  882. return keystrval(nodefromval(o)); /* get saved copy */
  883. else
  884. return NULL;
  885. }
  886. /*
  887. ** main search function
  888. */
  889. lu_byte luaH_get (Table *t, const TValue *key, TValue *res) {
  890. const TValue *slot;
  891. switch (ttypetag(key)) {
  892. case LUA_VSHRSTR:
  893. slot = luaH_Hgetshortstr(t, tsvalue(key));
  894. break;
  895. case LUA_VNUMINT:
  896. return luaH_getint(t, ivalue(key), res);
  897. case LUA_VNIL:
  898. slot = &absentkey;
  899. break;
  900. case LUA_VNUMFLT: {
  901. lua_Integer k;
  902. if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
  903. return luaH_getint(t, k, res); /* use specialized version */
  904. /* else... */
  905. } /* FALLTHROUGH */
  906. default:
  907. slot = getgeneric(t, key, 0);
  908. break;
  909. }
  910. return finishnodeget(slot, res);
  911. }
  912. static int finishnodeset (Table *t, const TValue *slot, TValue *val) {
  913. if (!ttisnil(slot)) {
  914. setobj(((lua_State*)NULL), cast(TValue*, slot), val);
  915. return HOK; /* success */
  916. }
  917. else if (isabstkey(slot))
  918. return HNOTFOUND; /* no slot with that key */
  919. else /* return node encoded */
  920. return cast_int((cast(Node*, slot) - t->node)) + HFIRSTNODE;
  921. }
  922. static int rawfinishnodeset (const TValue *slot, TValue *val) {
  923. if (isabstkey(slot))
  924. return 0; /* no slot with that key */
  925. else {
  926. setobj(((lua_State*)NULL), cast(TValue*, slot), val);
  927. return 1; /* success */
  928. }
  929. }
  930. int luaH_psetint (Table *t, lua_Integer key, TValue *val) {
  931. if (keyinarray(t, key)) {
  932. lu_byte *tag = getArrTag(t, key - 1);
  933. if (!tagisempty(*tag) || checknoTM(t->metatable, TM_NEWINDEX)) {
  934. fval2arr(t, cast_uint(key) - 1, tag, val);
  935. return HOK; /* success */
  936. }
  937. else
  938. return ~cast_int(key - 1); /* empty slot in the array part */
  939. }
  940. else
  941. return finishnodeset(t, getintfromhash(t, key), val);
  942. }
  943. int luaH_psetshortstr (Table *t, TString *key, TValue *val) {
  944. return finishnodeset(t, luaH_Hgetshortstr(t, key), val);
  945. }
  946. int luaH_psetstr (Table *t, TString *key, TValue *val) {
  947. return finishnodeset(t, Hgetstr(t, key), val);
  948. }
  949. int luaH_pset (Table *t, const TValue *key, TValue *val) {
  950. switch (ttypetag(key)) {
  951. case LUA_VSHRSTR: return luaH_psetshortstr(t, tsvalue(key), val);
  952. case LUA_VNUMINT: return luaH_psetint(t, ivalue(key), val);
  953. case LUA_VNIL: return HNOTFOUND;
  954. case LUA_VNUMFLT: {
  955. lua_Integer k;
  956. if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
  957. return luaH_psetint(t, k, val); /* use specialized version */
  958. /* else... */
  959. } /* FALLTHROUGH */
  960. default:
  961. return finishnodeset(t, getgeneric(t, key, 0), val);
  962. }
  963. }
  964. /*
  965. ** Finish a raw "set table" operation, where 'slot' is where the value
  966. ** should have been (the result of a previous "get table").
  967. ** Beware: when using this function you probably need to check a GC
  968. ** barrier and invalidate the TM cache.
  969. */
  970. void luaH_finishset (lua_State *L, Table *t, const TValue *key,
  971. TValue *value, int hres) {
  972. lua_assert(hres != HOK);
  973. if (hres == HNOTFOUND) {
  974. luaH_newkey(L, t, key, value);
  975. }
  976. else if (hres > 0) { /* regular Node? */
  977. setobj2t(L, gval(gnode(t, hres - HFIRSTNODE)), value);
  978. }
  979. else { /* array entry */
  980. hres = ~hres; /* real index */
  981. obj2arr(t, cast_uint(hres), value);
  982. }
  983. }
  984. /*
  985. ** beware: when using this function you probably need to check a GC
  986. ** barrier and invalidate the TM cache.
  987. */
  988. void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) {
  989. int hres = luaH_pset(t, key, value);
  990. if (hres != HOK)
  991. luaH_finishset(L, t, key, value, hres);
  992. }
  993. /*
  994. ** Ditto for a GC barrier. (No need to invalidate the TM cache, as
  995. ** integers cannot be keys to metamethods.)
  996. */
  997. void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
  998. if (keyinarray(t, key))
  999. obj2arr(t, cast_uint(key) - 1, value);
  1000. else {
  1001. int ok = rawfinishnodeset(getintfromhash(t, key), value);
  1002. if (!ok) {
  1003. TValue k;
  1004. setivalue(&k, key);
  1005. luaH_newkey(L, t, &k, value);
  1006. }
  1007. }
  1008. }
  1009. /*
  1010. ** Try to find a boundary in the hash part of table 't'. From the
  1011. ** caller, we know that 'j' is zero or present and that 'j + 1' is
  1012. ** present. We want to find a larger key that is absent from the
  1013. ** table, so that we can do a binary search between the two keys to
  1014. ** find a boundary. We keep doubling 'j' until we get an absent index.
  1015. ** If the doubling would overflow, we try LUA_MAXINTEGER. If it is
  1016. ** absent, we are ready for the binary search. ('j', being max integer,
  1017. ** is larger or equal to 'i', but it cannot be equal because it is
  1018. ** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a
  1019. ** boundary. ('j + 1' cannot be a present integer key because it is
  1020. ** not a valid integer in Lua.)
  1021. */
  1022. static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
  1023. lua_Unsigned i;
  1024. if (j == 0) j++; /* the caller ensures 'j + 1' is present */
  1025. do {
  1026. i = j; /* 'i' is a present index */
  1027. if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
  1028. j *= 2;
  1029. else {
  1030. j = LUA_MAXINTEGER;
  1031. if (hashkeyisempty(t, j)) /* t[j] not present? */
  1032. break; /* 'j' now is an absent index */
  1033. else /* weird case */
  1034. return j; /* well, max integer is a boundary... */
  1035. }
  1036. } while (!hashkeyisempty(t, j)); /* repeat until an absent t[j] */
  1037. /* i < j && t[i] present && t[j] absent */
  1038. while (j - i > 1u) { /* do a binary search between them */
  1039. lua_Unsigned m = (i + j) / 2;
  1040. if (hashkeyisempty(t, m)) j = m;
  1041. else i = m;
  1042. }
  1043. return i;
  1044. }
  1045. static unsigned int binsearch (Table *array, unsigned int i, unsigned int j) {
  1046. while (j - i > 1u) { /* binary search */
  1047. unsigned int m = (i + j) / 2;
  1048. if (arraykeyisempty(array, m)) j = m;
  1049. else i = m;
  1050. }
  1051. return i;
  1052. }
  1053. /*
  1054. ** Try to find a boundary in table 't'. (A 'boundary' is an integer index
  1055. ** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent
  1056. ** and 'maxinteger' if t[maxinteger] is present.)
  1057. ** (In the next explanation, we use Lua indices, that is, with base 1.
  1058. ** The code itself uses base 0 when indexing the array part of the table.)
  1059. ** The code starts with 'limit = t->alimit', a position in the array
  1060. ** part that may be a boundary.
  1061. **
  1062. ** (1) If 't[limit]' is empty, there must be a boundary before it.
  1063. ** As a common case (e.g., after 't[#t]=nil'), check whether 'limit-1'
  1064. ** is present. If so, it is a boundary. Otherwise, do a binary search
  1065. ** between 0 and limit to find a boundary. In both cases, try to
  1066. ** use this boundary as the new 'alimit', as a hint for the next call.
  1067. **
  1068. ** (2) If 't[limit]' is not empty and the array has more elements
  1069. ** after 'limit', try to find a boundary there. Again, try first
  1070. ** the special case (which should be quite frequent) where 'limit+1'
  1071. ** is empty, so that 'limit' is a boundary. Otherwise, check the
  1072. ** last element of the array part. If it is empty, there must be a
  1073. ** boundary between the old limit (present) and the last element
  1074. ** (absent), which is found with a binary search. (This boundary always
  1075. ** can be a new limit.)
  1076. **
  1077. ** (3) The last case is when there are no elements in the array part
  1078. ** (limit == 0) or its last element (the new limit) is present.
  1079. ** In this case, must check the hash part. If there is no hash part
  1080. ** or 'limit+1' is absent, 'limit' is a boundary. Otherwise, call
  1081. ** 'hash_search' to find a boundary in the hash part of the table.
  1082. ** (In those cases, the boundary is not inside the array part, and
  1083. ** therefore cannot be used as a new limit.)
  1084. */
  1085. lua_Unsigned luaH_getn (Table *t) {
  1086. unsigned int limit = t->alimit;
  1087. if (limit > 0 && arraykeyisempty(t, limit)) { /* (1)? */
  1088. /* there must be a boundary before 'limit' */
  1089. if (limit >= 2 && !arraykeyisempty(t, limit - 1)) {
  1090. /* 'limit - 1' is a boundary; can it be a new limit? */
  1091. if (ispow2realasize(t) && !ispow2(limit - 1)) {
  1092. t->alimit = limit - 1;
  1093. setnorealasize(t); /* now 'alimit' is not the real size */
  1094. }
  1095. return limit - 1;
  1096. }
  1097. else { /* must search for a boundary in [0, limit] */
  1098. unsigned int boundary = binsearch(t, 0, limit);
  1099. /* can this boundary represent the real size of the array? */
  1100. if (ispow2realasize(t) && boundary > luaH_realasize(t) / 2) {
  1101. t->alimit = boundary; /* use it as the new limit */
  1102. setnorealasize(t);
  1103. }
  1104. return boundary;
  1105. }
  1106. }
  1107. /* 'limit' is zero or present in table */
  1108. if (!limitequalsasize(t)) { /* (2)? */
  1109. /* 'limit' > 0 and array has more elements after 'limit' */
  1110. if (arraykeyisempty(t, limit + 1)) /* 'limit + 1' is empty? */
  1111. return limit; /* this is the boundary */
  1112. /* else, try last element in the array */
  1113. limit = luaH_realasize(t);
  1114. if (arraykeyisempty(t, limit)) { /* empty? */
  1115. /* there must be a boundary in the array after old limit,
  1116. and it must be a valid new limit */
  1117. unsigned int boundary = binsearch(t, t->alimit, limit);
  1118. t->alimit = boundary;
  1119. return boundary;
  1120. }
  1121. /* else, new limit is present in the table; check the hash part */
  1122. }
  1123. /* (3) 'limit' is the last element and either is zero or present in table */
  1124. lua_assert(limit == luaH_realasize(t) &&
  1125. (limit == 0 || !arraykeyisempty(t, limit)));
  1126. if (isdummy(t) || hashkeyisempty(t, limit + 1))
  1127. return limit; /* 'limit + 1' is absent */
  1128. else /* 'limit + 1' is also present */
  1129. return hash_search(t, limit);
  1130. }
  1131. #if defined(LUA_DEBUG)
  1132. /* export these functions for the test library */
  1133. Node *luaH_mainposition (const Table *t, const TValue *key) {
  1134. return mainpositionTV(t, key);
  1135. }
  1136. #endif