ltable.c 34 KB

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