ltable.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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)-1)|1))))
  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 hashmod(t, cast_int(ui));
  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 int 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 cast_int(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. LUAI_FUNC 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_int(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. int tag = *getArrTag(t, i);
  323. if (!tagisempty(tag)) { /* a non-empty entry? */
  324. setivalue(s2v(key), i + 1);
  325. farr2val(t, i, tag, s2v(key + 1));
  326. return 1;
  327. }
  328. }
  329. for (i -= asize; cast_int(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 int 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_Integer 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 int numusehash (const Table *t, unsigned *nums, unsigned *pna) {
  461. int totaluse = 0; /* total number of elements */
  462. int ause = 0; /* elements added to 'nums' (can go to array part) */
  463. int 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. int j;
  565. int 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 = (t1->flags & NOTBITDUMMY) | (t2->flags & BITDUMMY);
  590. t2->lsizenode = lsizenode;
  591. t2->node = node;
  592. t2->flags = (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. int 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. luaH_setint(L, t, i + 1, &aux); /* re-insert it into the table */
  608. }
  609. }
  610. t->alimit = oldasize; /* restore current size... */
  611. }
  612. /*
  613. ** Clear new slice of the array.
  614. */
  615. static void clearNewSlice (Table *t, unsigned oldasize, unsigned newasize) {
  616. for (; oldasize < newasize; oldasize++)
  617. *getArrTag(t, oldasize) = LUA_VEMPTY;
  618. }
  619. /*
  620. ** Resize table 't' for the new given sizes. Both allocations (for
  621. ** the hash part and for the array part) can fail, which creates some
  622. ** subtleties. If the first allocation, for the hash part, fails, an
  623. ** error is raised and that is it. Otherwise, it copies the elements from
  624. ** the shrinking part of the array (if it is shrinking) into the new
  625. ** hash. Then it reallocates the array part. If that fails, the table
  626. ** is in its original state; the function frees the new hash part and then
  627. ** raises the allocation error. Otherwise, it sets the new hash part
  628. ** into the table, initializes the new part of the array (if any) with
  629. ** nils and reinserts the elements of the old hash back into the new
  630. ** parts of the table.
  631. */
  632. void luaH_resize (lua_State *L, Table *t, unsigned newasize,
  633. unsigned nhsize) {
  634. Table newt; /* to keep the new hash part */
  635. unsigned int oldasize = setlimittosize(t);
  636. Value *newarray;
  637. if (newasize > MAXASIZE)
  638. luaG_runerror(L, "table overflow");
  639. /* create new hash part with appropriate size into 'newt' */
  640. newt.flags = 0;
  641. setnodevector(L, &newt, nhsize);
  642. if (newasize < oldasize) { /* will array shrink? */
  643. /* re-insert into the new hash the elements from vanishing slice */
  644. exchangehashpart(t, &newt); /* pretend table has new hash */
  645. reinsertOldSlice(L, t, oldasize, newasize);
  646. exchangehashpart(t, &newt); /* restore old hash (in case of errors) */
  647. }
  648. /* allocate new array */
  649. newarray = resizearray(L, t, oldasize, newasize);
  650. if (l_unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */
  651. freehash(L, &newt); /* release new hash part */
  652. luaM_error(L); /* raise error (with array unchanged) */
  653. }
  654. /* allocation ok; initialize new part of the array */
  655. exchangehashpart(t, &newt); /* 't' has the new hash ('newt' has the old) */
  656. t->array = newarray; /* set new array part */
  657. t->alimit = newasize;
  658. clearNewSlice(t, oldasize, newasize);
  659. /* re-insert elements from old hash part into new parts */
  660. reinsert(L, &newt, t); /* 'newt' now has the old hash */
  661. freehash(L, &newt); /* free old hash part */
  662. }
  663. void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
  664. int nsize = allocsizenode(t);
  665. luaH_resize(L, t, nasize, nsize);
  666. }
  667. /*
  668. ** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
  669. */
  670. static void rehash (lua_State *L, Table *t, const TValue *ek) {
  671. unsigned int asize; /* optimal size for array part */
  672. unsigned int na; /* number of keys in the array part */
  673. unsigned int nums[MAXABITS + 1];
  674. int i;
  675. int totaluse;
  676. for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */
  677. setlimittosize(t);
  678. na = numusearray(t, nums); /* count keys in array part */
  679. totaluse = na; /* all those keys are integer keys */
  680. totaluse += numusehash(t, nums, &na); /* count keys in hash part */
  681. /* count extra key */
  682. if (ttisinteger(ek))
  683. na += countint(ivalue(ek), nums);
  684. totaluse++;
  685. /* compute new size for array part */
  686. asize = computesizes(nums, &na);
  687. /* resize the table to new computed sizes */
  688. luaH_resize(L, t, asize, totaluse - na);
  689. }
  690. /*
  691. ** }=============================================================
  692. */
  693. Table *luaH_new (lua_State *L) {
  694. GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
  695. Table *t = gco2t(o);
  696. t->metatable = NULL;
  697. t->flags = cast_byte(maskflags); /* table has no metamethod fields */
  698. t->array = NULL;
  699. t->alimit = 0;
  700. setnodevector(L, t, 0);
  701. return t;
  702. }
  703. /*
  704. ** Frees a table.
  705. */
  706. void luaH_free (lua_State *L, Table *t) {
  707. unsigned int realsize = luaH_realasize(t);
  708. freehash(L, t);
  709. resizearray(L, t, realsize, 0);
  710. luaM_free(L, t);
  711. }
  712. static Node *getfreepos (Table *t) {
  713. if (haslastfree(t)) { /* does it have 'lastfree' information? */
  714. /* look for a spot before 'lastfree', updating 'lastfree' */
  715. while (getlastfree(t) > t->node) {
  716. Node *free = --getlastfree(t);
  717. if (keyisnil(free))
  718. return free;
  719. }
  720. }
  721. else { /* no 'lastfree' information */
  722. if (!isdummy(t)) {
  723. int i = sizenode(t);
  724. while (i--) { /* do a linear search */
  725. Node *free = gnode(t, i);
  726. if (keyisnil(free))
  727. return free;
  728. }
  729. }
  730. }
  731. return NULL; /* could not find a free place */
  732. }
  733. /*
  734. ** Inserts a new key into a hash table; first, check whether key's main
  735. ** position is free. If not, check whether colliding node is in its main
  736. ** position or not: if it is not, move colliding node to an empty place
  737. ** and put new key in its main position; otherwise (colliding node is in
  738. ** its main position), new key goes to an empty position.
  739. */
  740. static void luaH_newkey (lua_State *L, Table *t, const TValue *key,
  741. TValue *value) {
  742. Node *mp;
  743. TValue aux;
  744. if (l_unlikely(ttisnil(key)))
  745. luaG_runerror(L, "table index is nil");
  746. else if (ttisfloat(key)) {
  747. lua_Number f = fltvalue(key);
  748. lua_Integer k;
  749. if (luaV_flttointeger(f, &k, F2Ieq)) { /* does key fit in an integer? */
  750. setivalue(&aux, k);
  751. key = &aux; /* insert it as an integer */
  752. }
  753. else if (l_unlikely(luai_numisnan(f)))
  754. luaG_runerror(L, "table index is NaN");
  755. }
  756. if (ttisnil(value))
  757. return; /* do not insert nil values */
  758. mp = mainpositionTV(t, key);
  759. if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */
  760. Node *othern;
  761. Node *f = getfreepos(t); /* get a free place */
  762. if (f == NULL) { /* cannot find a free place? */
  763. rehash(L, t, key); /* grow table */
  764. /* whatever called 'newkey' takes care of TM cache */
  765. luaH_set(L, t, key, value); /* insert key into grown table */
  766. return;
  767. }
  768. lua_assert(!isdummy(t));
  769. othern = mainpositionfromnode(t, mp);
  770. if (othern != mp) { /* is colliding node out of its main position? */
  771. /* yes; move colliding node into free position */
  772. while (othern + gnext(othern) != mp) /* find previous */
  773. othern += gnext(othern);
  774. gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */
  775. *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  776. if (gnext(mp) != 0) {
  777. gnext(f) += cast_int(mp - f); /* correct 'next' */
  778. gnext(mp) = 0; /* now 'mp' is free */
  779. }
  780. setempty(gval(mp));
  781. }
  782. else { /* colliding node is in its own main position */
  783. /* new node will go into free position */
  784. if (gnext(mp) != 0)
  785. gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */
  786. else lua_assert(gnext(f) == 0);
  787. gnext(mp) = cast_int(f - mp);
  788. mp = f;
  789. }
  790. }
  791. setnodekey(L, mp, key);
  792. luaC_barrierback(L, obj2gco(t), key);
  793. lua_assert(isempty(gval(mp)));
  794. setobj2t(L, gval(mp), value);
  795. }
  796. static const TValue *getintfromhash (Table *t, lua_Integer key) {
  797. Node *n = hashint(t, key);
  798. lua_assert(l_castS2U(key) - 1u >= luaH_realasize(t));
  799. for (;;) { /* check whether 'key' is somewhere in the chain */
  800. if (keyisinteger(n) && keyival(n) == key)
  801. return gval(n); /* that's it */
  802. else {
  803. int nx = gnext(n);
  804. if (nx == 0) break;
  805. n += nx;
  806. }
  807. }
  808. return &absentkey;
  809. }
  810. static int hashkeyisempty (Table *t, lua_Integer key) {
  811. const TValue *val = getintfromhash(t, key);
  812. return isempty(val);
  813. }
  814. static int finishnodeget (const TValue *val, TValue *res) {
  815. if (!ttisnil(val)) {
  816. setobj(((lua_State*)NULL), res, val);
  817. }
  818. return ttypetag(val);
  819. }
  820. int luaH_getint (Table *t, lua_Integer key, TValue *res) {
  821. if (keyinarray(t, key)) {
  822. int tag = *getArrTag(t, key - 1);
  823. if (!tagisempty(tag))
  824. farr2val(t, key - 1, tag, res);
  825. return tag;
  826. }
  827. else
  828. return finishnodeget(getintfromhash(t, key), res);
  829. }
  830. /*
  831. ** search function for short strings
  832. */
  833. const TValue *luaH_Hgetshortstr (Table *t, TString *key) {
  834. Node *n = hashstr(t, key);
  835. lua_assert(key->tt == LUA_VSHRSTR);
  836. for (;;) { /* check whether 'key' is somewhere in the chain */
  837. if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
  838. return gval(n); /* that's it */
  839. else {
  840. int nx = gnext(n);
  841. if (nx == 0)
  842. return &absentkey; /* not found */
  843. n += nx;
  844. }
  845. }
  846. }
  847. int luaH_getshortstr (Table *t, TString *key, TValue *res) {
  848. return finishnodeget(luaH_Hgetshortstr(t, key), res);
  849. }
  850. static const TValue *Hgetstr (Table *t, TString *key) {
  851. if (key->tt == LUA_VSHRSTR)
  852. return luaH_Hgetshortstr(t, key);
  853. else { /* for long strings, use generic case */
  854. TValue ko;
  855. setsvalue(cast(lua_State *, NULL), &ko, key);
  856. return getgeneric(t, &ko, 0);
  857. }
  858. }
  859. int luaH_getstr (Table *t, TString *key, TValue *res) {
  860. return finishnodeget(Hgetstr(t, key), res);
  861. }
  862. TString *luaH_getstrkey (Table *t, TString *key) {
  863. const TValue *o = Hgetstr(t, key);
  864. if (!isabstkey(o)) /* string already present? */
  865. return keystrval(nodefromval(o)); /* get saved copy */
  866. else
  867. return NULL;
  868. }
  869. /*
  870. ** main search function
  871. */
  872. int luaH_get (Table *t, const TValue *key, TValue *res) {
  873. const TValue *slot;
  874. switch (ttypetag(key)) {
  875. case LUA_VSHRSTR:
  876. slot = luaH_Hgetshortstr(t, tsvalue(key));
  877. break;
  878. case LUA_VNUMINT:
  879. return luaH_getint(t, ivalue(key), res);
  880. case LUA_VNIL:
  881. slot = &absentkey;
  882. break;
  883. case LUA_VNUMFLT: {
  884. lua_Integer k;
  885. if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
  886. return luaH_getint(t, k, res); /* use specialized version */
  887. /* else... */
  888. } /* FALLTHROUGH */
  889. default:
  890. slot = getgeneric(t, key, 0);
  891. break;
  892. }
  893. return finishnodeget(slot, res);
  894. }
  895. static int finishnodeset (Table *t, const TValue *slot, TValue *val) {
  896. if (!ttisnil(slot)) {
  897. setobj(((lua_State*)NULL), cast(TValue*, slot), val);
  898. return HOK; /* success */
  899. }
  900. else if (isabstkey(slot))
  901. return HNOTFOUND; /* no slot with that key */
  902. else /* return node encoded */
  903. return cast_int((cast(Node*, slot) - t->node)) + HFIRSTNODE;
  904. }
  905. static int rawfinishnodeset (const TValue *slot, TValue *val) {
  906. if (isabstkey(slot))
  907. return 0; /* no slot with that key */
  908. else {
  909. setobj(((lua_State*)NULL), cast(TValue*, slot), val);
  910. return 1; /* success */
  911. }
  912. }
  913. int luaH_psetint (Table *t, lua_Integer key, TValue *val) {
  914. if (keyinarray(t, key)) {
  915. lu_byte *tag = getArrTag(t, key - 1);
  916. if (!tagisempty(*tag) || checknoTM(t->metatable, TM_NEWINDEX)) {
  917. fval2arr(t, key - 1, tag, val);
  918. return HOK; /* success */
  919. }
  920. else
  921. return ~cast_int(key - 1); /* empty slot in the array part */
  922. }
  923. else
  924. return finishnodeset(t, getintfromhash(t, key), val);
  925. }
  926. int luaH_psetshortstr (Table *t, TString *key, TValue *val) {
  927. return finishnodeset(t, luaH_Hgetshortstr(t, key), val);
  928. }
  929. int luaH_psetstr (Table *t, TString *key, TValue *val) {
  930. return finishnodeset(t, Hgetstr(t, key), val);
  931. }
  932. int luaH_pset (Table *t, const TValue *key, TValue *val) {
  933. switch (ttypetag(key)) {
  934. case LUA_VSHRSTR: return luaH_psetshortstr(t, tsvalue(key), val);
  935. case LUA_VNUMINT: return luaH_psetint(t, ivalue(key), val);
  936. case LUA_VNIL: return HNOTFOUND;
  937. case LUA_VNUMFLT: {
  938. lua_Integer k;
  939. if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
  940. return luaH_psetint(t, k, val); /* use specialized version */
  941. /* else... */
  942. } /* FALLTHROUGH */
  943. default:
  944. return finishnodeset(t, getgeneric(t, key, 0), val);
  945. }
  946. }
  947. /*
  948. ** Finish a raw "set table" operation, where 'slot' is where the value
  949. ** should have been (the result of a previous "get table").
  950. ** Beware: when using this function you probably need to check a GC
  951. ** barrier and invalidate the TM cache.
  952. */
  953. void luaH_finishset (lua_State *L, Table *t, const TValue *key,
  954. TValue *value, int hres) {
  955. lua_assert(hres != HOK);
  956. if (hres == HNOTFOUND) {
  957. luaH_newkey(L, t, key, value);
  958. }
  959. else if (hres > 0) { /* regular Node? */
  960. setobj2t(L, gval(gnode(t, hres - HFIRSTNODE)), value);
  961. }
  962. else { /* array entry */
  963. hres = ~hres; /* real index */
  964. obj2arr(t, hres, value);
  965. }
  966. }
  967. /*
  968. ** beware: when using this function you probably need to check a GC
  969. ** barrier and invalidate the TM cache.
  970. */
  971. void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) {
  972. int hres = luaH_pset(t, key, value);
  973. if (hres != HOK)
  974. luaH_finishset(L, t, key, value, hres);
  975. }
  976. /*
  977. ** Ditto for a GC barrier. (No need to invalidate the TM cache, as
  978. ** integers cannot be keys to metamethods.)
  979. */
  980. void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
  981. if (keyinarray(t, key))
  982. obj2arr(t, key - 1, value);
  983. else {
  984. int ok = rawfinishnodeset(getintfromhash(t, key), value);
  985. if (!ok) {
  986. TValue k;
  987. setivalue(&k, key);
  988. luaH_newkey(L, t, &k, value);
  989. }
  990. }
  991. }
  992. /*
  993. ** Try to find a boundary in the hash part of table 't'. From the
  994. ** caller, we know that 'j' is zero or present and that 'j + 1' is
  995. ** present. We want to find a larger key that is absent from the
  996. ** table, so that we can do a binary search between the two keys to
  997. ** find a boundary. We keep doubling 'j' until we get an absent index.
  998. ** If the doubling would overflow, we try LUA_MAXINTEGER. If it is
  999. ** absent, we are ready for the binary search. ('j', being max integer,
  1000. ** is larger or equal to 'i', but it cannot be equal because it is
  1001. ** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a
  1002. ** boundary. ('j + 1' cannot be a present integer key because it is
  1003. ** not a valid integer in Lua.)
  1004. */
  1005. static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
  1006. lua_Unsigned i;
  1007. if (j == 0) j++; /* the caller ensures 'j + 1' is present */
  1008. do {
  1009. i = j; /* 'i' is a present index */
  1010. if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
  1011. j *= 2;
  1012. else {
  1013. j = LUA_MAXINTEGER;
  1014. if (hashkeyisempty(t, j)) /* t[j] not present? */
  1015. break; /* 'j' now is an absent index */
  1016. else /* weird case */
  1017. return j; /* well, max integer is a boundary... */
  1018. }
  1019. } while (!hashkeyisempty(t, j)); /* repeat until an absent t[j] */
  1020. /* i < j && t[i] present && t[j] absent */
  1021. while (j - i > 1u) { /* do a binary search between them */
  1022. lua_Unsigned m = (i + j) / 2;
  1023. if (hashkeyisempty(t, m)) j = m;
  1024. else i = m;
  1025. }
  1026. return i;
  1027. }
  1028. static unsigned int binsearch (Table *array, unsigned int i, unsigned int j) {
  1029. while (j - i > 1u) { /* binary search */
  1030. unsigned int m = (i + j) / 2;
  1031. if (arraykeyisempty(array, m)) j = m;
  1032. else i = m;
  1033. }
  1034. return i;
  1035. }
  1036. /*
  1037. ** Try to find a boundary in table 't'. (A 'boundary' is an integer index
  1038. ** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent
  1039. ** and 'maxinteger' if t[maxinteger] is present.)
  1040. ** (In the next explanation, we use Lua indices, that is, with base 1.
  1041. ** The code itself uses base 0 when indexing the array part of the table.)
  1042. ** The code starts with 'limit = t->alimit', a position in the array
  1043. ** part that may be a boundary.
  1044. **
  1045. ** (1) If 't[limit]' is empty, there must be a boundary before it.
  1046. ** As a common case (e.g., after 't[#t]=nil'), check whether 'limit-1'
  1047. ** is present. If so, it is a boundary. Otherwise, do a binary search
  1048. ** between 0 and limit to find a boundary. In both cases, try to
  1049. ** use this boundary as the new 'alimit', as a hint for the next call.
  1050. **
  1051. ** (2) If 't[limit]' is not empty and the array has more elements
  1052. ** after 'limit', try to find a boundary there. Again, try first
  1053. ** the special case (which should be quite frequent) where 'limit+1'
  1054. ** is empty, so that 'limit' is a boundary. Otherwise, check the
  1055. ** last element of the array part. If it is empty, there must be a
  1056. ** boundary between the old limit (present) and the last element
  1057. ** (absent), which is found with a binary search. (This boundary always
  1058. ** can be a new limit.)
  1059. **
  1060. ** (3) The last case is when there are no elements in the array part
  1061. ** (limit == 0) or its last element (the new limit) is present.
  1062. ** In this case, must check the hash part. If there is no hash part
  1063. ** or 'limit+1' is absent, 'limit' is a boundary. Otherwise, call
  1064. ** 'hash_search' to find a boundary in the hash part of the table.
  1065. ** (In those cases, the boundary is not inside the array part, and
  1066. ** therefore cannot be used as a new limit.)
  1067. */
  1068. lua_Unsigned luaH_getn (Table *t) {
  1069. unsigned int limit = t->alimit;
  1070. if (limit > 0 && arraykeyisempty(t, limit)) { /* (1)? */
  1071. /* there must be a boundary before 'limit' */
  1072. if (limit >= 2 && !arraykeyisempty(t, limit - 1)) {
  1073. /* 'limit - 1' is a boundary; can it be a new limit? */
  1074. if (ispow2realasize(t) && !ispow2(limit - 1)) {
  1075. t->alimit = limit - 1;
  1076. setnorealasize(t); /* now 'alimit' is not the real size */
  1077. }
  1078. return limit - 1;
  1079. }
  1080. else { /* must search for a boundary in [0, limit] */
  1081. unsigned int boundary = binsearch(t, 0, limit);
  1082. /* can this boundary represent the real size of the array? */
  1083. if (ispow2realasize(t) && boundary > luaH_realasize(t) / 2) {
  1084. t->alimit = boundary; /* use it as the new limit */
  1085. setnorealasize(t);
  1086. }
  1087. return boundary;
  1088. }
  1089. }
  1090. /* 'limit' is zero or present in table */
  1091. if (!limitequalsasize(t)) { /* (2)? */
  1092. /* 'limit' > 0 and array has more elements after 'limit' */
  1093. if (arraykeyisempty(t, limit + 1)) /* 'limit + 1' is empty? */
  1094. return limit; /* this is the boundary */
  1095. /* else, try last element in the array */
  1096. limit = luaH_realasize(t);
  1097. if (arraykeyisempty(t, limit)) { /* empty? */
  1098. /* there must be a boundary in the array after old limit,
  1099. and it must be a valid new limit */
  1100. unsigned int boundary = binsearch(t, t->alimit, limit);
  1101. t->alimit = boundary;
  1102. return boundary;
  1103. }
  1104. /* else, new limit is present in the table; check the hash part */
  1105. }
  1106. /* (3) 'limit' is the last element and either is zero or present in table */
  1107. lua_assert(limit == luaH_realasize(t) &&
  1108. (limit == 0 || !arraykeyisempty(t, limit)));
  1109. if (isdummy(t) || hashkeyisempty(t, cast(lua_Integer, limit + 1)))
  1110. return limit; /* 'limit + 1' is absent */
  1111. else /* 'limit + 1' is also present */
  1112. return hash_search(t, limit);
  1113. }
  1114. #if defined(LUA_DEBUG)
  1115. /* export these functions for the test library */
  1116. Node *luaH_mainposition (const Table *t, const TValue *key) {
  1117. return mainpositionTV(t, key);
  1118. }
  1119. #endif