9
3

ltable.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  1. /*
  2. ** $Id: ltable.c $
  3. ** Lua tables (hash)
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define ltable_c
  7. #define LUA_CORE
  8. #include "lprefix.h"
  9. /*
  10. ** Implementation of tables (aka arrays, objects, or hash tables).
  11. ** Tables keep its elements in two parts: an array part and a hash part.
  12. ** Non-negative integer keys are all candidates to be kept in the array
  13. ** part. The actual size of the array is the largest 'n' such that
  14. ** more than half the slots between 1 and n are in use.
  15. ** Hash uses a mix of chained scatter table with Brent's variation.
  16. ** A main invariant of these tables is that, if an element is not
  17. ** in its main position (i.e. the 'original' position that its hash gives
  18. ** to it), then the colliding element is in its own main position.
  19. ** Hence even when the load factor reaches 100%, performance remains good.
  20. */
  21. #include <math.h>
  22. #include <limits.h>
  23. #include "lua.h"
  24. #include "ldebug.h"
  25. #include "ldo.h"
  26. #include "lgc.h"
  27. #include "lmem.h"
  28. #include "lobject.h"
  29. #include "lstate.h"
  30. #include "lstring.h"
  31. #include "ltable.h"
  32. #include "lvm.h"
  33. /*
  34. ** MAXABITS is the largest integer such that MAXASIZE fits in an
  35. ** unsigned int.
  36. */
  37. #define MAXABITS cast_int(sizeof(int) * CHAR_BIT - 1)
  38. /*
  39. ** MAXASIZE is the maximum size of the array part. It is the minimum
  40. ** between 2^MAXABITS and the maximum size that, measured in bytes,
  41. ** fits in a 'size_t'.
  42. */
  43. #define MAXASIZE luaM_limitN(1u << MAXABITS, TValue)
  44. /*
  45. ** MAXHBITS is the largest integer such that 2^MAXHBITS fits in a
  46. ** signed int.
  47. */
  48. #define MAXHBITS (MAXABITS - 1)
  49. /*
  50. ** MAXHSIZE is the maximum size of the hash part. It is the minimum
  51. ** between 2^MAXHBITS and the maximum size such that, measured in bytes,
  52. ** it fits in a 'size_t'.
  53. */
  54. #define MAXHSIZE luaM_limitN(1u << MAXHBITS, Node)
  55. #define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))
  56. #define hashstr(t,str) hashpow2(t, (str)->hash)
  57. #define hashboolean(t,p) hashpow2(t, p)
  58. #define hashint(t,i) hashpow2(t, i)
  59. /*
  60. ** for some types, it is better to avoid modulus by power of 2, as
  61. ** they tend to have many 2 factors.
  62. */
  63. #define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))
  64. #define hashpointer(t,p) hashmod(t, point2uint(p))
  65. #define dummynode (&dummynode_)
  66. static const Node dummynode_ = {
  67. {{NULL}, LUA_VEMPTY, /* value's value and type */
  68. LUA_VNIL, 0, {NULL}} /* key type, next, and key value */
  69. };
  70. static const TValue absentkey = {ABSTKEYCONSTANT};
  71. /*
  72. ** Hash for floating-point numbers.
  73. ** The main computation should be just
  74. ** n = frexp(n, &i); return (n * INT_MAX) + i
  75. ** but there are some numerical subtleties.
  76. ** In a two-complement representation, INT_MAX does not has an exact
  77. ** representation as a float, but INT_MIN does; because the absolute
  78. ** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the
  79. ** absolute value of the product 'frexp * -INT_MIN' is smaller or equal
  80. ** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when
  81. ** adding 'i'; the use of '~u' (instead of '-u') avoids problems with
  82. ** INT_MIN.
  83. */
  84. #if !defined(l_hashfloat)
  85. static int l_hashfloat (lua_Number n) {
  86. int i;
  87. lua_Integer ni;
  88. n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN);
  89. if (!lua_numbertointeger(n, &ni)) { /* is 'n' inf/-inf/NaN? */
  90. lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL));
  91. return 0;
  92. }
  93. else { /* normal case */
  94. unsigned int u = cast_uint(i) + cast_uint(ni);
  95. return cast_int(u <= cast_uint(INT_MAX) ? u : ~u);
  96. }
  97. }
  98. #endif
  99. /*
  100. ** returns the 'main' position of an element in a table (that is,
  101. ** the index of its hash value). The key comes broken (tag in 'ktt'
  102. ** and value in 'vkl') so that we can call it on keys inserted into
  103. ** nodes.
  104. */
  105. static Node *mainposition (const Table *t, int ktt, const Value *kvl) {
  106. switch (withvariant(ktt)) {
  107. case LUA_VNUMINT:
  108. return hashint(t, ivalueraw(*kvl));
  109. case LUA_VNUMFLT:
  110. return hashmod(t, l_hashfloat(fltvalueraw(*kvl)));
  111. case LUA_VSHRSTR:
  112. return hashstr(t, tsvalueraw(*kvl));
  113. case LUA_VLNGSTR:
  114. return hashpow2(t, luaS_hashlongstr(tsvalueraw(*kvl)));
  115. case LUA_VFALSE:
  116. return hashboolean(t, 0);
  117. case LUA_VTRUE:
  118. return hashboolean(t, 1);
  119. case LUA_VLIGHTUSERDATA:
  120. return hashpointer(t, pvalueraw(*kvl));
  121. case LUA_VLCF:
  122. return hashpointer(t, fvalueraw(*kvl));
  123. default:
  124. return hashpointer(t, gcvalueraw(*kvl));
  125. }
  126. }
  127. /*
  128. ** Returns the main position of an element given as a 'TValue'
  129. */
  130. static Node *mainpositionTV (const Table *t, const TValue *key) {
  131. return mainposition(t, rawtt(key), valraw(key));
  132. }
  133. /*
  134. ** Check whether key 'k1' is equal to the key in node 'n2'. This
  135. ** equality is raw, so there are no metamethods. Floats with integer
  136. ** values have been normalized, so integers cannot be equal to
  137. ** floats. It is assumed that 'eqshrstr' is simply pointer equality, so
  138. ** that short strings are handled in the default case.
  139. ** A true 'deadok' means to accept dead keys as equal to their original
  140. ** values. All dead keys are compared in the default case, by pointer
  141. ** identity. (Only collectable objects can produce dead keys.) Note that
  142. ** dead long strings are also compared by identity.
  143. ** Once a key is dead, its corresponding value may be collected, and
  144. ** then another value can be created with the same address. If this
  145. ** other value is given to 'next', 'equalkey' will signal a false
  146. ** positive. In a regular traversal, this situation should never happen,
  147. ** as all keys given to 'next' came from the table itself, and therefore
  148. ** could not have been collected. Outside a regular traversal, we
  149. ** have garbage in, garbage out. What is relevant is that this false
  150. ** positive does not break anything. (In particular, 'next' will return
  151. ** some other valid item on the table or nil.)
  152. */
  153. static int equalkey (const TValue *k1, const Node *n2, int deadok) {
  154. if ((rawtt(k1) != keytt(n2)) && /* not the same variants? */
  155. !(deadok && keyisdead(n2) && iscollectable(k1)))
  156. return 0; /* cannot be same key */
  157. switch (keytt(n2)) {
  158. case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE:
  159. return 1;
  160. case LUA_VNUMINT:
  161. return (ivalue(k1) == keyival(n2));
  162. case LUA_VNUMFLT:
  163. return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2)));
  164. case LUA_VLIGHTUSERDATA:
  165. return pvalue(k1) == pvalueraw(keyval(n2));
  166. case LUA_VLCF:
  167. return fvalue(k1) == fvalueraw(keyval(n2));
  168. case ctb(LUA_VLNGSTR):
  169. return luaS_eqlngstr(tsvalue(k1), keystrval(n2));
  170. default:
  171. return gcvalue(k1) == gcvalueraw(keyval(n2));
  172. }
  173. }
  174. /*
  175. ** True if value of 'alimit' is equal to the real size of the array
  176. ** part of table 't'. (Otherwise, the array part must be larger than
  177. ** 'alimit'.)
  178. */
  179. #define limitequalsasize(t) (isrealasize(t) || ispow2((t)->alimit))
  180. /*
  181. ** Returns the real size of the 'array' array
  182. */
  183. LUAI_FUNC unsigned int luaH_realasize (const Table *t) {
  184. if (limitequalsasize(t))
  185. return t->alimit; /* this is the size */
  186. else {
  187. unsigned int size = t->alimit;
  188. /* compute the smallest power of 2 not smaller than 'n' */
  189. size |= (size >> 1);
  190. size |= (size >> 2);
  191. size |= (size >> 4);
  192. size |= (size >> 8);
  193. size |= (size >> 16);
  194. #if (UINT_MAX >> 30) > 3
  195. size |= (size >> 32); /* unsigned int has more than 32 bits */
  196. #endif
  197. size++;
  198. lua_assert(ispow2(size) && size/2 < t->alimit && t->alimit < size);
  199. return size;
  200. }
  201. }
  202. /*
  203. ** Check whether real size of the array is a power of 2.
  204. ** (If it is not, 'alimit' cannot be changed to any other value
  205. ** without changing the real size.)
  206. */
  207. static int ispow2realasize (const Table *t) {
  208. return (!isrealasize(t) || ispow2(t->alimit));
  209. }
  210. static unsigned int setlimittosize (Table *t) {
  211. t->alimit = luaH_realasize(t);
  212. setrealasize(t);
  213. return t->alimit;
  214. }
  215. #define limitasasize(t) check_exp(isrealasize(t), t->alimit)
  216. /*
  217. ** "Generic" get version. (Not that generic: not valid for integers,
  218. ** which may be in array part, nor for floats with integral values.)
  219. ** See explanation about 'deadok' in function 'equalkey'.
  220. */
  221. static const TValue *getgeneric (Table *t, const TValue *key, int deadok) {
  222. Node *n = mainpositionTV(t, key);
  223. for (;;) { /* check whether 'key' is somewhere in the chain */
  224. if (equalkey(key, n, deadok))
  225. return gval(n); /* that's it */
  226. else {
  227. int nx = gnext(n);
  228. if (nx == 0)
  229. return &absentkey; /* not found */
  230. n += nx;
  231. }
  232. }
  233. }
  234. /*
  235. ** returns the index for 'k' if 'k' is an appropriate key to live in
  236. ** the array part of a table, 0 otherwise.
  237. */
  238. static unsigned int arrayindex (lua_Integer k) {
  239. if (l_castS2U(k) - 1u < MAXASIZE) /* 'k' in [1, MAXASIZE]? */
  240. return cast_uint(k); /* 'key' is an appropriate array index */
  241. else
  242. return 0;
  243. }
  244. /*
  245. ** returns the index of a 'key' for table traversals. First goes all
  246. ** elements in the array part, then elements in the hash part. The
  247. ** beginning of a traversal is signaled by 0.
  248. */
  249. static unsigned int findindex (lua_State *L, Table *t, TValue *key,
  250. unsigned int asize) {
  251. unsigned int i;
  252. if (ttisnil(key)) return 0; /* first iteration */
  253. i = ttisinteger(key) ? arrayindex(ivalue(key)) : 0;
  254. if (i - 1u < asize) /* is 'key' inside array part? */
  255. return i; /* yes; that's the index */
  256. else {
  257. const TValue *n = getgeneric(t, key, 1);
  258. if (unlikely(isabstkey(n)))
  259. luaG_runerror(L, "invalid key to 'next'"); /* key not found */
  260. i = cast_int(nodefromval(n) - gnode(t, 0)); /* key index in hash table */
  261. /* hash elements are numbered after array ones */
  262. return (i + 1) + asize;
  263. }
  264. }
  265. int luaH_next (lua_State *L, Table *t, StkId key) {
  266. unsigned int asize = luaH_realasize(t);
  267. unsigned int i = findindex(L, t, s2v(key), asize); /* find original key */
  268. for (; i < asize; i++) { /* try first array part */
  269. if (!isempty(&t->array[i])) { /* a non-empty entry? */
  270. setivalue(s2v(key), i + 1);
  271. setobj2s(L, key + 1, &t->array[i]);
  272. return 1;
  273. }
  274. }
  275. for (i -= asize; cast_int(i) < sizenode(t); i++) { /* hash part */
  276. if (!isempty(gval(gnode(t, i)))) { /* a non-empty entry? */
  277. Node *n = gnode(t, i);
  278. getnodekey(L, s2v(key), n);
  279. setobj2s(L, key + 1, gval(n));
  280. return 1;
  281. }
  282. }
  283. return 0; /* no more elements */
  284. }
  285. static void freehash (lua_State *L, Table *t) {
  286. if (!isdummy(t))
  287. luaM_freearray(L, t->node, cast_sizet(sizenode(t)));
  288. }
  289. /*
  290. ** {=============================================================
  291. ** Rehash
  292. ** ==============================================================
  293. */
  294. /*
  295. ** Compute the optimal size for the array part of table 't'. 'nums' is a
  296. ** "count array" where 'nums[i]' is the number of integers in the table
  297. ** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of
  298. ** integer keys in the table and leaves with the number of keys that
  299. ** will go to the array part; return the optimal size. (The condition
  300. ** 'twotoi > 0' in the for loop stops the loop if 'twotoi' overflows.)
  301. */
  302. static unsigned int computesizes (unsigned int nums[], unsigned int *pna) {
  303. int i;
  304. unsigned int twotoi; /* 2^i (candidate for optimal size) */
  305. unsigned int a = 0; /* number of elements smaller than 2^i */
  306. unsigned int na = 0; /* number of elements to go to array part */
  307. unsigned int optimal = 0; /* optimal size for array part */
  308. /* loop while keys can fill more than half of total size */
  309. for (i = 0, twotoi = 1;
  310. twotoi > 0 && *pna > twotoi / 2;
  311. i++, twotoi *= 2) {
  312. a += nums[i];
  313. if (a > twotoi/2) { /* more than half elements present? */
  314. optimal = twotoi; /* optimal size (till now) */
  315. na = a; /* all elements up to 'optimal' will go to array part */
  316. }
  317. }
  318. lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal);
  319. *pna = na;
  320. return optimal;
  321. }
  322. static int countint (lua_Integer key, unsigned int *nums) {
  323. unsigned int k = arrayindex(key);
  324. if (k != 0) { /* is 'key' an appropriate array index? */
  325. nums[luaO_ceillog2(k)]++; /* count as such */
  326. return 1;
  327. }
  328. else
  329. return 0;
  330. }
  331. /*
  332. ** Count keys in array part of table 't': Fill 'nums[i]' with
  333. ** number of keys that will go into corresponding slice and return
  334. ** total number of non-nil keys.
  335. */
  336. static unsigned int numusearray (const Table *t, unsigned int *nums) {
  337. int lg;
  338. unsigned int ttlg; /* 2^lg */
  339. unsigned int ause = 0; /* summation of 'nums' */
  340. unsigned int i = 1; /* count to traverse all array keys */
  341. unsigned int asize = limitasasize(t); /* real array size */
  342. /* traverse each slice */
  343. for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
  344. unsigned int lc = 0; /* counter */
  345. unsigned int lim = ttlg;
  346. if (lim > asize) {
  347. lim = asize; /* adjust upper limit */
  348. if (i > lim)
  349. break; /* no more elements to count */
  350. }
  351. /* count elements in range (2^(lg - 1), 2^lg] */
  352. for (; i <= lim; i++) {
  353. if (!isempty(&t->array[i-1]))
  354. lc++;
  355. }
  356. nums[lg] += lc;
  357. ause += lc;
  358. }
  359. return ause;
  360. }
  361. static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) {
  362. int totaluse = 0; /* total number of elements */
  363. int ause = 0; /* elements added to 'nums' (can go to array part) */
  364. int i = sizenode(t);
  365. while (i--) {
  366. Node *n = &t->node[i];
  367. if (!isempty(gval(n))) {
  368. if (keyisinteger(n))
  369. ause += countint(keyival(n), nums);
  370. totaluse++;
  371. }
  372. }
  373. *pna += ause;
  374. return totaluse;
  375. }
  376. /*
  377. ** Creates an array for the hash part of a table with the given
  378. ** size, or reuses the dummy node if size is zero.
  379. ** The computation for size overflow is in two steps: the first
  380. ** comparison ensures that the shift in the second one does not
  381. ** overflow.
  382. */
  383. static void setnodevector (lua_State *L, Table *t, unsigned int size) {
  384. if (size == 0) { /* no elements to hash part? */
  385. t->node = cast(Node *, dummynode); /* use common 'dummynode' */
  386. t->lsizenode = 0;
  387. t->lastfree = NULL; /* signal that it is using dummy node */
  388. }
  389. else {
  390. int i;
  391. int lsize = luaO_ceillog2(size);
  392. if (lsize > MAXHBITS || (1u << lsize) > MAXHSIZE)
  393. luaG_runerror(L, "table overflow");
  394. size = twoto(lsize);
  395. t->node = luaM_newvector(L, size, Node);
  396. for (i = 0; i < (int)size; i++) {
  397. Node *n = gnode(t, i);
  398. gnext(n) = 0;
  399. setnilkey(n);
  400. setempty(gval(n));
  401. }
  402. t->lsizenode = cast_byte(lsize);
  403. t->lastfree = gnode(t, size); /* all positions are free */
  404. }
  405. }
  406. /*
  407. ** (Re)insert all elements from the hash part of 'ot' into table 't'.
  408. */
  409. static void reinsert (lua_State *L, Table *ot, Table *t) {
  410. int j;
  411. int size = sizenode(ot);
  412. for (j = 0; j < size; j++) {
  413. Node *old = gnode(ot, j);
  414. if (!isempty(gval(old))) {
  415. /* doesn't need barrier/invalidate cache, as entry was
  416. already present in the table */
  417. TValue k;
  418. getnodekey(L, &k, old);
  419. setobjt2t(L, luaH_set(L, t, &k), gval(old));
  420. }
  421. }
  422. }
  423. /*
  424. ** Exchange the hash part of 't1' and 't2'.
  425. */
  426. static void exchangehashpart (Table *t1, Table *t2) {
  427. lu_byte lsizenode = t1->lsizenode;
  428. Node *node = t1->node;
  429. Node *lastfree = t1->lastfree;
  430. t1->lsizenode = t2->lsizenode;
  431. t1->node = t2->node;
  432. t1->lastfree = t2->lastfree;
  433. t2->lsizenode = lsizenode;
  434. t2->node = node;
  435. t2->lastfree = lastfree;
  436. }
  437. /*
  438. ** Resize table 't' for the new given sizes. Both allocations (for
  439. ** the hash part and for the array part) can fail, which creates some
  440. ** subtleties. If the first allocation, for the hash part, fails, an
  441. ** error is raised and that is it. Otherwise, it copies the elements from
  442. ** the shrinking part of the array (if it is shrinking) into the new
  443. ** hash. Then it reallocates the array part. If that fails, the table
  444. ** is in its original state; the function frees the new hash part and then
  445. ** raises the allocation error. Otherwise, it sets the new hash part
  446. ** into the table, initializes the new part of the array (if any) with
  447. ** nils and reinserts the elements of the old hash back into the new
  448. ** parts of the table.
  449. */
  450. void luaH_resize (lua_State *L, Table *t, unsigned int newasize,
  451. unsigned int nhsize) {
  452. unsigned int i;
  453. Table newt; /* to keep the new hash part */
  454. unsigned int oldasize = setlimittosize(t);
  455. TValue *newarray;
  456. /* create new hash part with appropriate size into 'newt' */
  457. setnodevector(L, &newt, nhsize);
  458. if (newasize < oldasize) { /* will array shrink? */
  459. t->alimit = newasize; /* pretend array has new size... */
  460. exchangehashpart(t, &newt); /* and new hash */
  461. /* re-insert into the new hash the elements from vanishing slice */
  462. for (i = newasize; i < oldasize; i++) {
  463. if (!isempty(&t->array[i]))
  464. luaH_setint(L, t, i + 1, &t->array[i]);
  465. }
  466. t->alimit = oldasize; /* restore current size... */
  467. exchangehashpart(t, &newt); /* and hash (in case of errors) */
  468. }
  469. /* allocate new array */
  470. newarray = luaM_reallocvector(L, t->array, oldasize, newasize, TValue);
  471. if (unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */
  472. freehash(L, &newt); /* release new hash part */
  473. luaM_error(L); /* raise error (with array unchanged) */
  474. }
  475. /* allocation ok; initialize new part of the array */
  476. exchangehashpart(t, &newt); /* 't' has the new hash ('newt' has the old) */
  477. t->array = newarray; /* set new array part */
  478. t->alimit = newasize;
  479. for (i = oldasize; i < newasize; i++) /* clear new slice of the array */
  480. setempty(&t->array[i]);
  481. /* re-insert elements from old hash part into new parts */
  482. reinsert(L, &newt, t); /* 'newt' now has the old hash */
  483. freehash(L, &newt); /* free old hash part */
  484. }
  485. void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
  486. int nsize = allocsizenode(t);
  487. luaH_resize(L, t, nasize, nsize);
  488. }
  489. /*
  490. ** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
  491. */
  492. static void rehash (lua_State *L, Table *t, const TValue *ek) {
  493. unsigned int asize; /* optimal size for array part */
  494. unsigned int na; /* number of keys in the array part */
  495. unsigned int nums[MAXABITS + 1];
  496. int i;
  497. int totaluse;
  498. for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */
  499. setlimittosize(t);
  500. na = numusearray(t, nums); /* count keys in array part */
  501. totaluse = na; /* all those keys are integer keys */
  502. totaluse += numusehash(t, nums, &na); /* count keys in hash part */
  503. /* count extra key */
  504. if (ttisinteger(ek))
  505. na += countint(ivalue(ek), nums);
  506. totaluse++;
  507. /* compute new size for array part */
  508. asize = computesizes(nums, &na);
  509. /* resize the table to new computed sizes */
  510. luaH_resize(L, t, asize, totaluse - na);
  511. }
  512. /*
  513. ** }=============================================================
  514. */
  515. Table *luaH_new (lua_State *L) {
  516. GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
  517. Table *t = gco2t(o);
  518. t->metatable = NULL;
  519. t->flags = cast_byte(maskflags); /* table has no metamethod fields */
  520. t->array = NULL;
  521. t->alimit = 0;
  522. setnodevector(L, t, 0);
  523. return t;
  524. }
  525. void luaH_free (lua_State *L, Table *t) {
  526. freehash(L, t);
  527. luaM_freearray(L, t->array, luaH_realasize(t));
  528. luaM_free(L, t);
  529. }
  530. static Node *getfreepos (Table *t) {
  531. if (!isdummy(t)) {
  532. while (t->lastfree > t->node) {
  533. t->lastfree--;
  534. if (keyisnil(t->lastfree))
  535. return t->lastfree;
  536. }
  537. }
  538. return NULL; /* could not find a free place */
  539. }
  540. /*
  541. ** inserts a new key into a hash table; first, check whether key's main
  542. ** position is free. If not, check whether colliding node is in its main
  543. ** position or not: if it is not, move colliding node to an empty place and
  544. ** put new key in its main position; otherwise (colliding node is in its main
  545. ** position), new key goes to an empty position.
  546. */
  547. TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
  548. Node *mp;
  549. TValue aux;
  550. if (unlikely(ttisnil(key)))
  551. luaG_runerror(L, "table index is nil");
  552. else if (ttisfloat(key)) {
  553. lua_Number f = fltvalue(key);
  554. lua_Integer k;
  555. if (luaV_flttointeger(f, &k, F2Ieq)) { /* does key fit in an integer? */
  556. setivalue(&aux, k);
  557. key = &aux; /* insert it as an integer */
  558. }
  559. else if (unlikely(luai_numisnan(f)))
  560. luaG_runerror(L, "table index is NaN");
  561. }
  562. mp = mainpositionTV(t, key);
  563. if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */
  564. Node *othern;
  565. Node *f = getfreepos(t); /* get a free place */
  566. if (f == NULL) { /* cannot find a free place? */
  567. rehash(L, t, key); /* grow table */
  568. /* whatever called 'newkey' takes care of TM cache */
  569. return luaH_set(L, t, key); /* insert key into grown table */
  570. }
  571. lua_assert(!isdummy(t));
  572. othern = mainposition(t, keytt(mp), &keyval(mp));
  573. if (othern != mp) { /* is colliding node out of its main position? */
  574. /* yes; move colliding node into free position */
  575. while (othern + gnext(othern) != mp) /* find previous */
  576. othern += gnext(othern);
  577. gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */
  578. *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  579. if (gnext(mp) != 0) {
  580. gnext(f) += cast_int(mp - f); /* correct 'next' */
  581. gnext(mp) = 0; /* now 'mp' is free */
  582. }
  583. setempty(gval(mp));
  584. }
  585. else { /* colliding node is in its own main position */
  586. /* new node will go into free position */
  587. if (gnext(mp) != 0)
  588. gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */
  589. else lua_assert(gnext(f) == 0);
  590. gnext(mp) = cast_int(f - mp);
  591. mp = f;
  592. }
  593. }
  594. setnodekey(L, mp, key);
  595. luaC_barrierback(L, obj2gco(t), key);
  596. lua_assert(isempty(gval(mp)));
  597. return gval(mp);
  598. }
  599. /*
  600. ** Search function for integers. If integer is inside 'alimit', get it
  601. ** directly from the array part. Otherwise, if 'alimit' is not equal to
  602. ** the real size of the array, key still can be in the array part. In
  603. ** this case, try to avoid a call to 'luaH_realasize' when key is just
  604. ** one more than the limit (so that it can be incremented without
  605. ** changing the real size of the array).
  606. */
  607. const TValue *luaH_getint (Table *t, lua_Integer key) {
  608. if (l_castS2U(key) - 1u < t->alimit) /* 'key' in [1, t->alimit]? */
  609. return &t->array[key - 1];
  610. else if (!limitequalsasize(t) && /* key still may be in the array part? */
  611. (l_castS2U(key) == t->alimit + 1 ||
  612. l_castS2U(key) - 1u < luaH_realasize(t))) {
  613. t->alimit = cast_uint(key); /* probably '#t' is here now */
  614. return &t->array[key - 1];
  615. }
  616. else {
  617. Node *n = hashint(t, key);
  618. for (;;) { /* check whether 'key' is somewhere in the chain */
  619. if (keyisinteger(n) && keyival(n) == key)
  620. return gval(n); /* that's it */
  621. else {
  622. int nx = gnext(n);
  623. if (nx == 0) break;
  624. n += nx;
  625. }
  626. }
  627. return &absentkey;
  628. }
  629. }
  630. /*
  631. ** search function for short strings
  632. */
  633. const TValue *luaH_getshortstr (Table *t, TString *key) {
  634. Node *n = hashstr(t, key);
  635. lua_assert(key->tt == LUA_VSHRSTR);
  636. for (;;) { /* check whether 'key' is somewhere in the chain */
  637. if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
  638. return gval(n); /* that's it */
  639. else {
  640. int nx = gnext(n);
  641. if (nx == 0)
  642. return &absentkey; /* not found */
  643. n += nx;
  644. }
  645. }
  646. }
  647. const TValue *luaH_getstr (Table *t, TString *key) {
  648. if (key->tt == LUA_VSHRSTR)
  649. return luaH_getshortstr(t, key);
  650. else { /* for long strings, use generic case */
  651. TValue ko;
  652. setsvalue(cast(lua_State *, NULL), &ko, key);
  653. return getgeneric(t, &ko, 0);
  654. }
  655. }
  656. /*
  657. ** main search function
  658. */
  659. const TValue *luaH_get (Table *t, const TValue *key) {
  660. switch (ttypetag(key)) {
  661. case LUA_VSHRSTR: return luaH_getshortstr(t, tsvalue(key));
  662. case LUA_VNUMINT: return luaH_getint(t, ivalue(key));
  663. case LUA_VNIL: return &absentkey;
  664. case LUA_VNUMFLT: {
  665. lua_Integer k;
  666. if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
  667. return luaH_getint(t, k); /* use specialized version */
  668. /* else... */
  669. } /* FALLTHROUGH */
  670. default:
  671. return getgeneric(t, key, 0);
  672. }
  673. }
  674. /*
  675. ** beware: when using this function you probably need to check a GC
  676. ** barrier and invalidate the TM cache.
  677. */
  678. TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
  679. const TValue *p = luaH_get(t, key);
  680. if (!isabstkey(p))
  681. return cast(TValue *, p);
  682. else return luaH_newkey(L, t, key);
  683. }
  684. void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
  685. const TValue *p = luaH_getint(t, key);
  686. TValue *cell;
  687. if (!isabstkey(p))
  688. cell = cast(TValue *, p);
  689. else {
  690. TValue k;
  691. setivalue(&k, key);
  692. cell = luaH_newkey(L, t, &k);
  693. }
  694. setobj2t(L, cell, value);
  695. }
  696. /*
  697. ** Try to find a boundary in the hash part of table 't'. From the
  698. ** caller, we know that 'j' is zero or present and that 'j + 1' is
  699. ** present. We want to find a larger key that is absent from the
  700. ** table, so that we can do a binary search between the two keys to
  701. ** find a boundary. We keep doubling 'j' until we get an absent index.
  702. ** If the doubling would overflow, we try LUA_MAXINTEGER. If it is
  703. ** absent, we are ready for the binary search. ('j', being max integer,
  704. ** is larger or equal to 'i', but it cannot be equal because it is
  705. ** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a
  706. ** boundary. ('j + 1' cannot be a present integer key because it is
  707. ** not a valid integer in Lua.)
  708. */
  709. static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
  710. lua_Unsigned i;
  711. if (j == 0) j++; /* the caller ensures 'j + 1' is present */
  712. do {
  713. i = j; /* 'i' is a present index */
  714. if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
  715. j *= 2;
  716. else {
  717. j = LUA_MAXINTEGER;
  718. if (isempty(luaH_getint(t, j))) /* t[j] not present? */
  719. break; /* 'j' now is an absent index */
  720. else /* weird case */
  721. return j; /* well, max integer is a boundary... */
  722. }
  723. } while (!isempty(luaH_getint(t, j))); /* repeat until an absent t[j] */
  724. /* i < j && t[i] present && t[j] absent */
  725. while (j - i > 1u) { /* do a binary search between them */
  726. lua_Unsigned m = (i + j) / 2;
  727. if (isempty(luaH_getint(t, m))) j = m;
  728. else i = m;
  729. }
  730. return i;
  731. }
  732. static unsigned int binsearch (const TValue *array, unsigned int i,
  733. unsigned int j) {
  734. while (j - i > 1u) { /* binary search */
  735. unsigned int m = (i + j) / 2;
  736. if (isempty(&array[m - 1])) j = m;
  737. else i = m;
  738. }
  739. return i;
  740. }
  741. /*
  742. ** Try to find a boundary in table 't'. (A 'boundary' is an integer index
  743. ** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent
  744. ** and 'maxinteger' if t[maxinteger] is present.)
  745. ** (In the next explanation, we use Lua indices, that is, with base 1.
  746. ** The code itself uses base 0 when indexing the array part of the table.)
  747. ** The code starts with 'limit = t->alimit', a position in the array
  748. ** part that may be a boundary.
  749. **
  750. ** (1) If 't[limit]' is empty, there must be a boundary before it.
  751. ** As a common case (e.g., after 't[#t]=nil'), check whether 'limit-1'
  752. ** is present. If so, it is a boundary. Otherwise, do a binary search
  753. ** between 0 and limit to find a boundary. In both cases, try to
  754. ** use this boundary as the new 'alimit', as a hint for the next call.
  755. **
  756. ** (2) If 't[limit]' is not empty and the array has more elements
  757. ** after 'limit', try to find a boundary there. Again, try first
  758. ** the special case (which should be quite frequent) where 'limit+1'
  759. ** is empty, so that 'limit' is a boundary. Otherwise, check the
  760. ** last element of the array part. If it is empty, there must be a
  761. ** boundary between the old limit (present) and the last element
  762. ** (absent), which is found with a binary search. (This boundary always
  763. ** can be a new limit.)
  764. **
  765. ** (3) The last case is when there are no elements in the array part
  766. ** (limit == 0) or its last element (the new limit) is present.
  767. ** In this case, must check the hash part. If there is no hash part
  768. ** or 'limit+1' is absent, 'limit' is a boundary. Otherwise, call
  769. ** 'hash_search' to find a boundary in the hash part of the table.
  770. ** (In those cases, the boundary is not inside the array part, and
  771. ** therefore cannot be used as a new limit.)
  772. */
  773. lua_Unsigned luaH_getn (Table *t) {
  774. unsigned int limit = t->alimit;
  775. if (limit > 0 && isempty(&t->array[limit - 1])) { /* (1)? */
  776. /* there must be a boundary before 'limit' */
  777. if (limit >= 2 && !isempty(&t->array[limit - 2])) {
  778. /* 'limit - 1' is a boundary; can it be a new limit? */
  779. if (ispow2realasize(t) && !ispow2(limit - 1)) {
  780. t->alimit = limit - 1;
  781. setnorealasize(t); /* now 'alimit' is not the real size */
  782. }
  783. return limit - 1;
  784. }
  785. else { /* must search for a boundary in [0, limit] */
  786. unsigned int boundary = binsearch(t->array, 0, limit);
  787. /* can this boundary represent the real size of the array? */
  788. if (ispow2realasize(t) && boundary > luaH_realasize(t) / 2) {
  789. t->alimit = boundary; /* use it as the new limit */
  790. setnorealasize(t);
  791. }
  792. return boundary;
  793. }
  794. }
  795. /* 'limit' is zero or present in table */
  796. if (!limitequalsasize(t)) { /* (2)? */
  797. /* 'limit' > 0 and array has more elements after 'limit' */
  798. if (isempty(&t->array[limit])) /* 'limit + 1' is empty? */
  799. return limit; /* this is the boundary */
  800. /* else, try last element in the array */
  801. limit = luaH_realasize(t);
  802. if (isempty(&t->array[limit - 1])) { /* empty? */
  803. /* there must be a boundary in the array after old limit,
  804. and it must be a valid new limit */
  805. unsigned int boundary = binsearch(t->array, t->alimit, limit);
  806. t->alimit = boundary;
  807. return boundary;
  808. }
  809. /* else, new limit is present in the table; check the hash part */
  810. }
  811. /* (3) 'limit' is the last element and either is zero or present in table */
  812. lua_assert(limit == luaH_realasize(t) &&
  813. (limit == 0 || !isempty(&t->array[limit - 1])));
  814. if (isdummy(t) || isempty(luaH_getint(t, cast(lua_Integer, limit + 1))))
  815. return limit; /* 'limit + 1' is absent */
  816. else /* 'limit + 1' is also present */
  817. return hash_search(t, limit);
  818. }
  819. #if defined(LUA_DEBUG)
  820. /* export these functions for the test library */
  821. Node *luaH_mainposition (const Table *t, const TValue *key) {
  822. return mainpositionTV(t, key);
  823. }
  824. int luaH_isdummy (const Table *t) { return isdummy(t); }
  825. #endif