ltable.c 39 KB

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