ltable.c 42 KB

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