ltable.c 40 KB

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