ltable.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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. case ctb(LUA_VSHRSTR):
  198. return eqshrstr(tsvalue(k1), keystrval(n2));
  199. default:
  200. return gcvalue(k1) == gcvalueraw(keyval(n2));
  201. }
  202. }
  203. /*
  204. ** True if value of 'alimit' is equal to the real size of the array
  205. ** part of table 't'. (Otherwise, the array part must be larger than
  206. ** 'alimit'.)
  207. */
  208. #define limitequalsasize(t) (isrealasize(t) || ispow2((t)->alimit))
  209. /*
  210. ** Returns the real size of the 'array' array
  211. */
  212. LUAI_FUNC unsigned int luaH_realasize (const Table *t) {
  213. if (limitequalsasize(t))
  214. return t->alimit; /* this is the size */
  215. else {
  216. unsigned int size = t->alimit;
  217. /* compute the smallest power of 2 not smaller than 'n' */
  218. size |= (size >> 1);
  219. size |= (size >> 2);
  220. size |= (size >> 4);
  221. size |= (size >> 8);
  222. #if (UINT_MAX >> 14) > 3 /* unsigned int has more than 16 bits */
  223. size |= (size >> 16);
  224. #if (UINT_MAX >> 30) > 3
  225. size |= (size >> 32); /* unsigned int has more than 32 bits */
  226. #endif
  227. #endif
  228. size++;
  229. lua_assert(ispow2(size) && size/2 < t->alimit && t->alimit < size);
  230. return size;
  231. }
  232. }
  233. /*
  234. ** Check whether real size of the array is a power of 2.
  235. ** (If it is not, 'alimit' cannot be changed to any other value
  236. ** without changing the real size.)
  237. */
  238. static int ispow2realasize (const Table *t) {
  239. return (!isrealasize(t) || ispow2(t->alimit));
  240. }
  241. static unsigned int setlimittosize (Table *t) {
  242. t->alimit = luaH_realasize(t);
  243. setrealasize(t);
  244. return t->alimit;
  245. }
  246. #define limitasasize(t) check_exp(isrealasize(t), t->alimit)
  247. /*
  248. ** "Generic" get version. (Not that generic: not valid for integers,
  249. ** which may be in array part, nor for floats with integral values.)
  250. ** See explanation about 'deadok' in function 'equalkey'.
  251. */
  252. static const TValue *getgeneric (Table *t, const TValue *key, int deadok) {
  253. Node *n = mainpositionTV(t, key);
  254. for (;;) { /* check whether 'key' is somewhere in the chain */
  255. if (equalkey(key, n, deadok))
  256. return gval(n); /* that's it */
  257. else {
  258. int nx = gnext(n);
  259. if (nx == 0)
  260. return &absentkey; /* not found */
  261. n += nx;
  262. }
  263. }
  264. }
  265. /*
  266. ** returns the index for 'k' if 'k' is an appropriate key to live in
  267. ** the array part of a table, 0 otherwise.
  268. */
  269. static unsigned int arrayindex (lua_Integer k) {
  270. if (l_castS2U(k) - 1u < MAXASIZE) /* 'k' in [1, MAXASIZE]? */
  271. return cast_uint(k); /* 'key' is an appropriate array index */
  272. else
  273. return 0;
  274. }
  275. /*
  276. ** returns the index of a 'key' for table traversals. First goes all
  277. ** elements in the array part, then elements in the hash part. The
  278. ** beginning of a traversal is signaled by 0.
  279. */
  280. static unsigned int findindex (lua_State *L, Table *t, TValue *key,
  281. unsigned int asize) {
  282. unsigned int i;
  283. if (ttisnil(key)) return 0; /* first iteration */
  284. i = ttisinteger(key) ? arrayindex(ivalue(key)) : 0;
  285. if (i - 1u < asize) /* is 'key' inside array part? */
  286. return i; /* yes; that's the index */
  287. else {
  288. const TValue *n = getgeneric(t, key, 1);
  289. if (l_unlikely(isabstkey(n)))
  290. luaG_runerror(L, "invalid key to 'next'"); /* key not found */
  291. i = cast_int(nodefromval(n) - gnode(t, 0)); /* key index in hash table */
  292. /* hash elements are numbered after array ones */
  293. return (i + 1) + asize;
  294. }
  295. }
  296. int luaH_next (lua_State *L, Table *t, StkId key) {
  297. unsigned int asize = luaH_realasize(t);
  298. unsigned int i = findindex(L, t, s2v(key), asize); /* find original key */
  299. for (; i < asize; i++) { /* try first array part */
  300. if (!isempty(&t->array[i])) { /* a non-empty entry? */
  301. setivalue(s2v(key), i + 1);
  302. setobj2s(L, key + 1, &t->array[i]);
  303. return 1;
  304. }
  305. }
  306. for (i -= asize; cast_int(i) < sizenode(t); i++) { /* hash part */
  307. if (!isempty(gval(gnode(t, i)))) { /* a non-empty entry? */
  308. Node *n = gnode(t, i);
  309. getnodekey(L, s2v(key), n);
  310. setobj2s(L, key + 1, gval(n));
  311. return 1;
  312. }
  313. }
  314. return 0; /* no more elements */
  315. }
  316. static void freehash (lua_State *L, Table *t) {
  317. if (!isdummy(t))
  318. luaM_freearray(L, t->node, cast_sizet(sizenode(t)));
  319. }
  320. /*
  321. ** {=============================================================
  322. ** Rehash
  323. ** ==============================================================
  324. */
  325. /*
  326. ** Compute the optimal size for the array part of table 't'. 'nums' is a
  327. ** "count array" where 'nums[i]' is the number of integers in the table
  328. ** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of
  329. ** integer keys in the table and leaves with the number of keys that
  330. ** will go to the array part; return the optimal size. (The condition
  331. ** 'twotoi > 0' in the for loop stops the loop if 'twotoi' overflows.)
  332. */
  333. static unsigned int computesizes (unsigned int nums[], unsigned int *pna) {
  334. int i;
  335. unsigned int twotoi; /* 2^i (candidate for optimal size) */
  336. unsigned int a = 0; /* number of elements smaller than 2^i */
  337. unsigned int na = 0; /* number of elements to go to array part */
  338. unsigned int optimal = 0; /* optimal size for array part */
  339. /* loop while keys can fill more than half of total size */
  340. for (i = 0, twotoi = 1;
  341. twotoi > 0 && *pna > twotoi / 2;
  342. i++, twotoi *= 2) {
  343. a += nums[i];
  344. if (a > twotoi/2) { /* more than half elements present? */
  345. optimal = twotoi; /* optimal size (till now) */
  346. na = a; /* all elements up to 'optimal' will go to array part */
  347. }
  348. }
  349. lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal);
  350. *pna = na;
  351. return optimal;
  352. }
  353. static int countint (lua_Integer key, unsigned int *nums) {
  354. unsigned int k = arrayindex(key);
  355. if (k != 0) { /* is 'key' an appropriate array index? */
  356. nums[luaO_ceillog2(k)]++; /* count as such */
  357. return 1;
  358. }
  359. else
  360. return 0;
  361. }
  362. /*
  363. ** Count keys in array part of table 't': Fill 'nums[i]' with
  364. ** number of keys that will go into corresponding slice and return
  365. ** total number of non-nil keys.
  366. */
  367. static unsigned int numusearray (const Table *t, unsigned int *nums) {
  368. int lg;
  369. unsigned int ttlg; /* 2^lg */
  370. unsigned int ause = 0; /* summation of 'nums' */
  371. unsigned int i = 1; /* count to traverse all array keys */
  372. unsigned int asize = limitasasize(t); /* real array size */
  373. /* traverse each slice */
  374. for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
  375. unsigned int lc = 0; /* counter */
  376. unsigned int lim = ttlg;
  377. if (lim > asize) {
  378. lim = asize; /* adjust upper limit */
  379. if (i > lim)
  380. break; /* no more elements to count */
  381. }
  382. /* count elements in range (2^(lg - 1), 2^lg] */
  383. for (; i <= lim; i++) {
  384. if (!isempty(&t->array[i-1]))
  385. lc++;
  386. }
  387. nums[lg] += lc;
  388. ause += lc;
  389. }
  390. return ause;
  391. }
  392. static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) {
  393. int totaluse = 0; /* total number of elements */
  394. int ause = 0; /* elements added to 'nums' (can go to array part) */
  395. int i = sizenode(t);
  396. while (i--) {
  397. Node *n = &t->node[i];
  398. if (!isempty(gval(n))) {
  399. if (keyisinteger(n))
  400. ause += countint(keyival(n), nums);
  401. totaluse++;
  402. }
  403. }
  404. *pna += ause;
  405. return totaluse;
  406. }
  407. /*
  408. ** Creates an array for the hash part of a table with the given
  409. ** size, or reuses the dummy node if size is zero.
  410. ** The computation for size overflow is in two steps: the first
  411. ** comparison ensures that the shift in the second one does not
  412. ** overflow.
  413. */
  414. static void setnodevector (lua_State *L, Table *t, unsigned int size) {
  415. if (size == 0) { /* no elements to hash part? */
  416. t->node = cast(Node *, dummynode); /* use common 'dummynode' */
  417. t->lsizenode = 0;
  418. t->lastfree = NULL; /* signal that it is using dummy node */
  419. }
  420. else {
  421. int i;
  422. int lsize = luaO_ceillog2(size);
  423. if (lsize > MAXHBITS || (1u << lsize) > MAXHSIZE)
  424. luaG_runerror(L, "table overflow");
  425. size = twoto(lsize);
  426. t->node = luaM_newvector(L, size, Node);
  427. for (i = 0; i < cast_int(size); i++) {
  428. Node *n = gnode(t, i);
  429. gnext(n) = 0;
  430. setnilkey(n);
  431. setempty(gval(n));
  432. }
  433. t->lsizenode = cast_byte(lsize);
  434. t->lastfree = gnode(t, size); /* all positions are free */
  435. }
  436. }
  437. /*
  438. ** (Re)insert all elements from the hash part of 'ot' into table 't'.
  439. */
  440. static void reinsert (lua_State *L, Table *ot, Table *t) {
  441. int j;
  442. int size = sizenode(ot);
  443. for (j = 0; j < size; j++) {
  444. Node *old = gnode(ot, j);
  445. if (!isempty(gval(old))) {
  446. /* doesn't need barrier/invalidate cache, as entry was
  447. already present in the table */
  448. TValue k;
  449. getnodekey(L, &k, old);
  450. luaH_set(L, t, &k, gval(old));
  451. }
  452. }
  453. }
  454. /*
  455. ** Exchange the hash part of 't1' and 't2'.
  456. */
  457. static void exchangehashpart (Table *t1, Table *t2) {
  458. lu_byte lsizenode = t1->lsizenode;
  459. Node *node = t1->node;
  460. Node *lastfree = t1->lastfree;
  461. t1->lsizenode = t2->lsizenode;
  462. t1->node = t2->node;
  463. t1->lastfree = t2->lastfree;
  464. t2->lsizenode = lsizenode;
  465. t2->node = node;
  466. t2->lastfree = lastfree;
  467. }
  468. /*
  469. ** Resize table 't' for the new given sizes. Both allocations (for
  470. ** the hash part and for the array part) can fail, which creates some
  471. ** subtleties. If the first allocation, for the hash part, fails, an
  472. ** error is raised and that is it. Otherwise, it copies the elements from
  473. ** the shrinking part of the array (if it is shrinking) into the new
  474. ** hash. Then it reallocates the array part. If that fails, the table
  475. ** is in its original state; the function frees the new hash part and then
  476. ** raises the allocation error. Otherwise, it sets the new hash part
  477. ** into the table, initializes the new part of the array (if any) with
  478. ** nils and reinserts the elements of the old hash back into the new
  479. ** parts of the table.
  480. */
  481. void luaH_resize (lua_State *L, Table *t, unsigned int newasize,
  482. unsigned int nhsize) {
  483. unsigned int i;
  484. Table newt; /* to keep the new hash part */
  485. unsigned int oldasize = setlimittosize(t);
  486. TValue *newarray;
  487. /* create new hash part with appropriate size into 'newt' */
  488. setnodevector(L, &newt, nhsize);
  489. if (newasize < oldasize) { /* will array shrink? */
  490. t->alimit = newasize; /* pretend array has new size... */
  491. exchangehashpart(t, &newt); /* and new hash */
  492. /* re-insert into the new hash the elements from vanishing slice */
  493. for (i = newasize; i < oldasize; i++) {
  494. if (!isempty(&t->array[i]))
  495. luaH_setint(L, t, i + 1, &t->array[i]);
  496. }
  497. t->alimit = oldasize; /* restore current size... */
  498. exchangehashpart(t, &newt); /* and hash (in case of errors) */
  499. }
  500. /* allocate new array */
  501. newarray = luaM_reallocvector(L, t->array, oldasize, newasize, TValue);
  502. if (l_unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */
  503. freehash(L, &newt); /* release new hash part */
  504. luaM_error(L); /* raise error (with array unchanged) */
  505. }
  506. /* allocation ok; initialize new part of the array */
  507. exchangehashpart(t, &newt); /* 't' has the new hash ('newt' has the old) */
  508. t->array = newarray; /* set new array part */
  509. t->alimit = newasize;
  510. for (i = oldasize; i < newasize; i++) /* clear new slice of the array */
  511. setempty(&t->array[i]);
  512. /* re-insert elements from old hash part into new parts */
  513. reinsert(L, &newt, t); /* 'newt' now has the old hash */
  514. freehash(L, &newt); /* free old hash part */
  515. }
  516. void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
  517. int nsize = allocsizenode(t);
  518. luaH_resize(L, t, nasize, nsize);
  519. }
  520. /*
  521. ** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
  522. */
  523. static void rehash (lua_State *L, Table *t, const TValue *ek) {
  524. unsigned int asize; /* optimal size for array part */
  525. unsigned int na; /* number of keys in the array part */
  526. unsigned int nums[MAXABITS + 1];
  527. int i;
  528. int totaluse;
  529. for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */
  530. setlimittosize(t);
  531. na = numusearray(t, nums); /* count keys in array part */
  532. totaluse = na; /* all those keys are integer keys */
  533. totaluse += numusehash(t, nums, &na); /* count keys in hash part */
  534. /* count extra key */
  535. if (ttisinteger(ek))
  536. na += countint(ivalue(ek), nums);
  537. totaluse++;
  538. /* compute new size for array part */
  539. asize = computesizes(nums, &na);
  540. /* resize the table to new computed sizes */
  541. luaH_resize(L, t, asize, totaluse - na);
  542. }
  543. /*
  544. ** }=============================================================
  545. */
  546. Table *luaH_new (lua_State *L) {
  547. GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
  548. Table *t = gco2t(o);
  549. t->metatable = NULL;
  550. t->flags = cast_byte(maskflags); /* table has no metamethod fields */
  551. t->array = NULL;
  552. t->alimit = 0;
  553. setnodevector(L, t, 0);
  554. return t;
  555. }
  556. void luaH_free (lua_State *L, Table *t) {
  557. freehash(L, t);
  558. luaM_freearray(L, t->array, luaH_realasize(t));
  559. luaM_free(L, t);
  560. }
  561. static Node *getfreepos (Table *t) {
  562. if (!isdummy(t)) {
  563. while (t->lastfree > t->node) {
  564. t->lastfree--;
  565. if (keyisnil(t->lastfree))
  566. return t->lastfree;
  567. }
  568. }
  569. return NULL; /* could not find a free place */
  570. }
  571. /*
  572. ** inserts a new key into a hash table; first, check whether key's main
  573. ** position is free. If not, check whether colliding node is in its main
  574. ** position or not: if it is not, move colliding node to an empty place and
  575. ** put new key in its main position; otherwise (colliding node is in its main
  576. ** position), new key goes to an empty position.
  577. */
  578. void luaH_newkey (lua_State *L, Table *t, const TValue *key, TValue *value) {
  579. Node *mp;
  580. TValue aux;
  581. if (l_unlikely(isshared(t)))
  582. luaG_runerror(L, "attempt to change a shared table");
  583. if (l_unlikely(ttisnil(key)))
  584. luaG_runerror(L, "table index is nil");
  585. else if (ttisfloat(key)) {
  586. lua_Number f = fltvalue(key);
  587. lua_Integer k;
  588. if (luaV_flttointeger(f, &k, F2Ieq)) { /* does key fit in an integer? */
  589. setivalue(&aux, k);
  590. key = &aux; /* insert it as an integer */
  591. }
  592. else if (l_unlikely(luai_numisnan(f)))
  593. luaG_runerror(L, "table index is NaN");
  594. }
  595. if (ttisnil(value))
  596. return; /* do not insert nil values */
  597. mp = mainpositionTV(t, key);
  598. if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */
  599. Node *othern;
  600. Node *f = getfreepos(t); /* get a free place */
  601. if (f == NULL) { /* cannot find a free place? */
  602. rehash(L, t, key); /* grow table */
  603. /* whatever called 'newkey' takes care of TM cache */
  604. luaH_set(L, t, key, value); /* insert key into grown table */
  605. return;
  606. }
  607. lua_assert(!isdummy(t));
  608. othern = mainpositionfromnode(t, mp);
  609. if (othern != mp) { /* is colliding node out of its main position? */
  610. /* yes; move colliding node into free position */
  611. while (othern + gnext(othern) != mp) /* find previous */
  612. othern += gnext(othern);
  613. gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */
  614. *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  615. if (gnext(mp) != 0) {
  616. gnext(f) += cast_int(mp - f); /* correct 'next' */
  617. gnext(mp) = 0; /* now 'mp' is free */
  618. }
  619. setempty(gval(mp));
  620. }
  621. else { /* colliding node is in its own main position */
  622. /* new node will go into free position */
  623. if (gnext(mp) != 0)
  624. gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */
  625. else lua_assert(gnext(f) == 0);
  626. gnext(mp) = cast_int(f - mp);
  627. mp = f;
  628. }
  629. }
  630. setnodekey(L, mp, key);
  631. luaC_barrierback(L, obj2gco(t), key);
  632. lua_assert(isempty(gval(mp)));
  633. setobj2t(L, gval(mp), value);
  634. }
  635. /*
  636. ** Search function for integers. If integer is inside 'alimit', get it
  637. ** directly from the array part. Otherwise, if 'alimit' is not equal to
  638. ** the real size of the array, key still can be in the array part. In
  639. ** this case, try to avoid a call to 'luaH_realasize' when key is just
  640. ** one more than the limit (so that it can be incremented without
  641. ** changing the real size of the array).
  642. */
  643. const TValue *luaH_getint (Table *t, lua_Integer key) {
  644. if (l_castS2U(key) - 1u < t->alimit) /* 'key' in [1, t->alimit]? */
  645. return &t->array[key - 1];
  646. else if (!limitequalsasize(t) && /* key still may be in the array part? */
  647. (l_castS2U(key) == t->alimit + 1 ||
  648. l_castS2U(key) - 1u < luaH_realasize(t))) {
  649. t->alimit = cast_uint(key); /* probably '#t' is here now */
  650. return &t->array[key - 1];
  651. }
  652. else {
  653. Node *n = hashint(t, key);
  654. for (;;) { /* check whether 'key' is somewhere in the chain */
  655. if (keyisinteger(n) && keyival(n) == key)
  656. return gval(n); /* that's it */
  657. else {
  658. int nx = gnext(n);
  659. if (nx == 0) break;
  660. n += nx;
  661. }
  662. }
  663. return &absentkey;
  664. }
  665. }
  666. /*
  667. ** search function for short strings
  668. */
  669. const TValue *luaH_getshortstr (Table *t, TString *key) {
  670. Node *n = hashstr(t, key);
  671. lua_assert(key->tt == LUA_VSHRSTR);
  672. for (;;) { /* check whether 'key' is somewhere in the chain */
  673. if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
  674. return gval(n); /* that's it */
  675. else {
  676. int nx = gnext(n);
  677. if (nx == 0)
  678. return &absentkey; /* not found */
  679. n += nx;
  680. }
  681. }
  682. }
  683. const TValue *luaH_getstr (Table *t, TString *key) {
  684. if (key->tt == LUA_VSHRSTR)
  685. return luaH_getshortstr(t, key);
  686. else { /* for long strings, use generic case */
  687. TValue ko;
  688. setsvalue(cast(lua_State *, NULL), &ko, key);
  689. return getgeneric(t, &ko, 0);
  690. }
  691. }
  692. /*
  693. ** main search function
  694. */
  695. const TValue *luaH_get (Table *t, const TValue *key) {
  696. switch (ttypetag(key)) {
  697. case LUA_VSHRSTR: return luaH_getshortstr(t, tsvalue(key));
  698. case LUA_VNUMINT: return luaH_getint(t, ivalue(key));
  699. case LUA_VNIL: return &absentkey;
  700. case LUA_VNUMFLT: {
  701. lua_Integer k;
  702. if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
  703. return luaH_getint(t, k); /* use specialized version */
  704. /* else... */
  705. } /* FALLTHROUGH */
  706. default:
  707. return getgeneric(t, key, 0);
  708. }
  709. }
  710. /*
  711. ** Finish a raw "set table" operation, where 'slot' is where the value
  712. ** should have been (the result of a previous "get table").
  713. ** Beware: when using this function you probably need to check a GC
  714. ** barrier and invalidate the TM cache.
  715. */
  716. void luaH_finishset (lua_State *L, Table *t, const TValue *key,
  717. const TValue *slot, TValue *value) {
  718. if (isabstkey(slot))
  719. luaH_newkey(L, t, key, value);
  720. else {
  721. if (l_unlikely(isshared(t)))
  722. luaG_runerror(L, "attempt to change a shared table");
  723. setobj2t(L, cast(TValue *, slot), value);
  724. }
  725. }
  726. /*
  727. ** beware: when using this function you probably need to check a GC
  728. ** barrier and invalidate the TM cache.
  729. */
  730. void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) {
  731. const TValue *slot = luaH_get(t, key);
  732. luaH_finishset(L, t, key, slot, value);
  733. }
  734. void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
  735. const TValue *p = luaH_getint(t, key);
  736. if (isabstkey(p)) {
  737. TValue k;
  738. setivalue(&k, key);
  739. luaH_newkey(L, t, &k, value);
  740. }
  741. else {
  742. if (l_unlikely(isshared(t)))
  743. luaG_runerror(L, "attempt to change a shared table");
  744. setobj2t(L, cast(TValue *, p), value);
  745. }
  746. }
  747. /*
  748. ** Try to find a boundary in the hash part of table 't'. From the
  749. ** caller, we know that 'j' is zero or present and that 'j + 1' is
  750. ** present. We want to find a larger key that is absent from the
  751. ** table, so that we can do a binary search between the two keys to
  752. ** find a boundary. We keep doubling 'j' until we get an absent index.
  753. ** If the doubling would overflow, we try LUA_MAXINTEGER. If it is
  754. ** absent, we are ready for the binary search. ('j', being max integer,
  755. ** is larger or equal to 'i', but it cannot be equal because it is
  756. ** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a
  757. ** boundary. ('j + 1' cannot be a present integer key because it is
  758. ** not a valid integer in Lua.)
  759. */
  760. static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
  761. lua_Unsigned i;
  762. if (j == 0) j++; /* the caller ensures 'j + 1' is present */
  763. do {
  764. i = j; /* 'i' is a present index */
  765. if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
  766. j *= 2;
  767. else {
  768. j = LUA_MAXINTEGER;
  769. if (isempty(luaH_getint(t, j))) /* t[j] not present? */
  770. break; /* 'j' now is an absent index */
  771. else /* weird case */
  772. return j; /* well, max integer is a boundary... */
  773. }
  774. } while (!isempty(luaH_getint(t, j))); /* repeat until an absent t[j] */
  775. /* i < j && t[i] present && t[j] absent */
  776. while (j - i > 1u) { /* do a binary search between them */
  777. lua_Unsigned m = (i + j) / 2;
  778. if (isempty(luaH_getint(t, m))) j = m;
  779. else i = m;
  780. }
  781. return i;
  782. }
  783. static unsigned int binsearch (const TValue *array, unsigned int i,
  784. unsigned int j) {
  785. while (j - i > 1u) { /* binary search */
  786. unsigned int m = (i + j) / 2;
  787. if (isempty(&array[m - 1])) j = m;
  788. else i = m;
  789. }
  790. return i;
  791. }
  792. /*
  793. ** Try to find a boundary in table 't'. (A 'boundary' is an integer index
  794. ** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent
  795. ** and 'maxinteger' if t[maxinteger] is present.)
  796. ** (In the next explanation, we use Lua indices, that is, with base 1.
  797. ** The code itself uses base 0 when indexing the array part of the table.)
  798. ** The code starts with 'limit = t->alimit', a position in the array
  799. ** part that may be a boundary.
  800. **
  801. ** (1) If 't[limit]' is empty, there must be a boundary before it.
  802. ** As a common case (e.g., after 't[#t]=nil'), check whether 'limit-1'
  803. ** is present. If so, it is a boundary. Otherwise, do a binary search
  804. ** between 0 and limit to find a boundary. In both cases, try to
  805. ** use this boundary as the new 'alimit', as a hint for the next call.
  806. **
  807. ** (2) If 't[limit]' is not empty and the array has more elements
  808. ** after 'limit', try to find a boundary there. Again, try first
  809. ** the special case (which should be quite frequent) where 'limit+1'
  810. ** is empty, so that 'limit' is a boundary. Otherwise, check the
  811. ** last element of the array part. If it is empty, there must be a
  812. ** boundary between the old limit (present) and the last element
  813. ** (absent), which is found with a binary search. (This boundary always
  814. ** can be a new limit.)
  815. **
  816. ** (3) The last case is when there are no elements in the array part
  817. ** (limit == 0) or its last element (the new limit) is present.
  818. ** In this case, must check the hash part. If there is no hash part
  819. ** or 'limit+1' is absent, 'limit' is a boundary. Otherwise, call
  820. ** 'hash_search' to find a boundary in the hash part of the table.
  821. ** (In those cases, the boundary is not inside the array part, and
  822. ** therefore cannot be used as a new limit.)
  823. */
  824. lua_Unsigned luaH_getn (Table *t) {
  825. unsigned int limit = t->alimit;
  826. if (limit > 0 && isempty(&t->array[limit - 1])) { /* (1)? */
  827. /* there must be a boundary before 'limit' */
  828. if (limit >= 2 && !isempty(&t->array[limit - 2])) {
  829. /* 'limit - 1' is a boundary; can it be a new limit? */
  830. if (ispow2realasize(t) && !ispow2(limit - 1)) {
  831. t->alimit = limit - 1;
  832. setnorealasize(t); /* now 'alimit' is not the real size */
  833. }
  834. return limit - 1;
  835. }
  836. else { /* must search for a boundary in [0, limit] */
  837. unsigned int boundary = binsearch(t->array, 0, limit);
  838. /* can this boundary represent the real size of the array? */
  839. if (ispow2realasize(t) && boundary > luaH_realasize(t) / 2) {
  840. t->alimit = boundary; /* use it as the new limit */
  841. setnorealasize(t);
  842. }
  843. return boundary;
  844. }
  845. }
  846. /* 'limit' is zero or present in table */
  847. if (!limitequalsasize(t)) { /* (2)? */
  848. /* 'limit' > 0 and array has more elements after 'limit' */
  849. if (isempty(&t->array[limit])) /* 'limit + 1' is empty? */
  850. return limit; /* this is the boundary */
  851. /* else, try last element in the array */
  852. limit = luaH_realasize(t);
  853. if (isempty(&t->array[limit - 1])) { /* empty? */
  854. /* there must be a boundary in the array after old limit,
  855. and it must be a valid new limit */
  856. unsigned int boundary = binsearch(t->array, t->alimit, limit);
  857. t->alimit = boundary;
  858. return boundary;
  859. }
  860. /* else, new limit is present in the table; check the hash part */
  861. }
  862. /* (3) 'limit' is the last element and either is zero or present in table */
  863. lua_assert(limit == luaH_realasize(t) &&
  864. (limit == 0 || !isempty(&t->array[limit - 1])));
  865. if (isdummy(t) || isempty(luaH_getint(t, cast(lua_Integer, limit + 1))))
  866. return limit; /* 'limit + 1' is absent */
  867. else /* 'limit + 1' is also present */
  868. return hash_search(t, limit);
  869. }
  870. #if defined(LUA_DEBUG)
  871. /* export these functions for the test library */
  872. Node *luaH_mainposition (const Table *t, const TValue *key) {
  873. return mainpositionTV(t, key);
  874. }
  875. #endif