ltable.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. /*
  2. ** $Id: ltable.c,v 2.137 2018/05/30 14:25:52 roberto Exp roberto $
  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 such that, measured in bytes,
  41. ** it 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_TEMPTY, /* value's value and type */
  68. LUA_TNIL, 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_TNUMINT:
  108. return hashint(t, ivalueraw(*kvl));
  109. case LUA_TNUMFLT:
  110. return hashmod(t, l_hashfloat(fltvalueraw(*kvl)));
  111. case LUA_TSHRSTR:
  112. return hashstr(t, tsvalueraw(*kvl));
  113. case LUA_TLNGSTR:
  114. return hashpow2(t, luaS_hashlongstr(tsvalueraw(*kvl)));
  115. case LUA_TBOOLEAN:
  116. return hashboolean(t, bvalueraw(*kvl));
  117. case LUA_TLIGHTUSERDATA:
  118. return hashpointer(t, pvalueraw(*kvl));
  119. case LUA_TLCF:
  120. return hashpointer(t, fvalueraw(*kvl));
  121. default:
  122. return hashpointer(t, gcvalueraw(*kvl));
  123. }
  124. }
  125. static Node *mainpositionTV (const Table *t, const TValue *key) {
  126. return mainposition(t, rawtt(key), valraw(key));
  127. }
  128. /*
  129. ** Check whether key 'k1' is equal to the key in node 'n2'.
  130. ** This equality is raw, so there are no metamethods. Floats
  131. ** with integer values have been normalized, so integers cannot
  132. ** be equal to floats. It is assumed that 'eqshrstr' is simply
  133. ** pointer equality, so that short strings are handled in the
  134. ** default case.
  135. */
  136. static int equalkey (const TValue *k1, const Node *n2) {
  137. if (rawtt(k1) != keytt(n2)) /* not the same variants? */
  138. return 0; /* cannot be same key */
  139. switch (ttypetag(k1)) {
  140. case LUA_TNIL:
  141. return 1;
  142. case LUA_TNUMINT:
  143. return (ivalue(k1) == keyival(n2));
  144. case LUA_TNUMFLT:
  145. return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2)));
  146. case LUA_TBOOLEAN:
  147. return bvalue(k1) == bvalueraw(keyval(n2));
  148. case LUA_TLIGHTUSERDATA:
  149. return pvalue(k1) == pvalueraw(keyval(n2));
  150. case LUA_TLCF:
  151. return fvalue(k1) == fvalueraw(keyval(n2));
  152. case LUA_TLNGSTR:
  153. return luaS_eqlngstr(tsvalue(k1), keystrval(n2));
  154. default:
  155. return gcvalue(k1) == gcvalueraw(keyval(n2));
  156. }
  157. }
  158. /*
  159. ** "Generic" get version. (Not that generic: not valid for integers,
  160. ** which may be in array part, nor for floats with integral values.)
  161. */
  162. static const TValue *getgeneric (Table *t, const TValue *key) {
  163. Node *n = mainpositionTV(t, key);
  164. for (;;) { /* check whether 'key' is somewhere in the chain */
  165. if (equalkey(key, n))
  166. return gval(n); /* that's it */
  167. else {
  168. int nx = gnext(n);
  169. if (nx == 0)
  170. return &absentkey; /* not found */
  171. n += nx;
  172. }
  173. }
  174. }
  175. /*
  176. ** returns the index for 'k' if 'k' is an appropriate key to live in
  177. ** the array part of a table, 0 otherwise.
  178. */
  179. static unsigned int arrayindex (lua_Integer k) {
  180. if (0 < k && l_castS2U(k) <= MAXASIZE)
  181. return cast_uint(k); /* 'key' is an appropriate array index */
  182. else
  183. return 0;
  184. }
  185. /*
  186. ** returns the index of a 'key' for table traversals. First goes all
  187. ** elements in the array part, then elements in the hash part. The
  188. ** beginning of a traversal is signaled by 0.
  189. */
  190. static unsigned int findindex (lua_State *L, Table *t, TValue *key) {
  191. unsigned int i;
  192. if (ttisnil(key)) return 0; /* first iteration */
  193. i = ttisinteger(key) ? arrayindex(ivalue(key)) : 0;
  194. if (i != 0 && i <= t->sizearray) /* is 'key' inside array part? */
  195. return i; /* yes; that's the index */
  196. else {
  197. const TValue *n = getgeneric(t, key);
  198. if (unlikely(isabstkey(n)))
  199. luaG_runerror(L, "invalid key to 'next'"); /* key not found */
  200. i = cast_int(nodefromval(n) - gnode(t, 0)); /* key index in hash table */
  201. /* hash elements are numbered after array ones */
  202. return (i + 1) + t->sizearray;
  203. }
  204. }
  205. int luaH_next (lua_State *L, Table *t, StkId key) {
  206. unsigned int i = findindex(L, t, s2v(key)); /* find original element */
  207. for (; i < t->sizearray; i++) { /* try first array part */
  208. if (!isempty(&t->array[i])) { /* a non-empty entry? */
  209. setivalue(s2v(key), i + 1);
  210. setobj2s(L, key + 1, &t->array[i]);
  211. return 1;
  212. }
  213. }
  214. for (i -= t->sizearray; cast_int(i) < sizenode(t); i++) { /* hash part */
  215. if (!isempty(gval(gnode(t, i)))) { /* a non-empty entry? */
  216. Node *n = gnode(t, i);
  217. getnodekey(L, s2v(key), n);
  218. setobj2s(L, key + 1, gval(n));
  219. return 1;
  220. }
  221. }
  222. return 0; /* no more elements */
  223. }
  224. static void freehash (lua_State *L, Table *t) {
  225. if (!isdummy(t))
  226. luaM_freearray(L, t->node, cast_sizet(sizenode(t)));
  227. }
  228. /*
  229. ** {=============================================================
  230. ** Rehash
  231. ** ==============================================================
  232. */
  233. /*
  234. ** Compute the optimal size for the array part of table 't'. 'nums' is a
  235. ** "count array" where 'nums[i]' is the number of integers in the table
  236. ** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of
  237. ** integer keys in the table and leaves with the number of keys that
  238. ** will go to the array part; return the optimal size. (The condition
  239. ** 'twotoi > 0' in the for loop stops the loop if 'twotoi' overflows.)
  240. */
  241. static unsigned int computesizes (unsigned int nums[], unsigned int *pna) {
  242. int i;
  243. unsigned int twotoi; /* 2^i (candidate for optimal size) */
  244. unsigned int a = 0; /* number of elements smaller than 2^i */
  245. unsigned int na = 0; /* number of elements to go to array part */
  246. unsigned int optimal = 0; /* optimal size for array part */
  247. /* loop while keys can fill more than half of total size */
  248. for (i = 0, twotoi = 1;
  249. twotoi > 0 && *pna > twotoi / 2;
  250. i++, twotoi *= 2) {
  251. a += nums[i];
  252. if (a > twotoi/2) { /* more than half elements present? */
  253. optimal = twotoi; /* optimal size (till now) */
  254. na = a; /* all elements up to 'optimal' will go to array part */
  255. }
  256. }
  257. lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal);
  258. *pna = na;
  259. return optimal;
  260. }
  261. static int countint (lua_Integer key, unsigned int *nums) {
  262. unsigned int k = arrayindex(key);
  263. if (k != 0) { /* is 'key' an appropriate array index? */
  264. nums[luaO_ceillog2(k)]++; /* count as such */
  265. return 1;
  266. }
  267. else
  268. return 0;
  269. }
  270. /*
  271. ** Count keys in array part of table 't': Fill 'nums[i]' with
  272. ** number of keys that will go into corresponding slice and return
  273. ** total number of non-nil keys.
  274. */
  275. static unsigned int numusearray (const Table *t, unsigned int *nums) {
  276. int lg;
  277. unsigned int ttlg; /* 2^lg */
  278. unsigned int ause = 0; /* summation of 'nums' */
  279. unsigned int i = 1; /* count to traverse all array keys */
  280. /* traverse each slice */
  281. for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
  282. unsigned int lc = 0; /* counter */
  283. unsigned int lim = ttlg;
  284. if (lim > t->sizearray) {
  285. lim = t->sizearray; /* adjust upper limit */
  286. if (i > lim)
  287. break; /* no more elements to count */
  288. }
  289. /* count elements in range (2^(lg - 1), 2^lg] */
  290. for (; i <= lim; i++) {
  291. if (!isempty(&t->array[i-1]))
  292. lc++;
  293. }
  294. nums[lg] += lc;
  295. ause += lc;
  296. }
  297. return ause;
  298. }
  299. static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) {
  300. int totaluse = 0; /* total number of elements */
  301. int ause = 0; /* elements added to 'nums' (can go to array part) */
  302. int i = sizenode(t);
  303. while (i--) {
  304. Node *n = &t->node[i];
  305. if (!isempty(gval(n))) {
  306. if (keyisinteger(n))
  307. ause += countint(keyival(n), nums);
  308. totaluse++;
  309. }
  310. }
  311. *pna += ause;
  312. return totaluse;
  313. }
  314. /*
  315. ** Creates an array for the hash part of a table with the given
  316. ** size, or reuses the dummy node if size is zero.
  317. ** The computation for size overflow is in two steps: the first
  318. ** comparison ensures that the shift in the second one does not
  319. ** overflow.
  320. */
  321. static void setnodevector (lua_State *L, Table *t, unsigned int size) {
  322. if (size == 0) { /* no elements to hash part? */
  323. t->node = cast(Node *, dummynode); /* use common 'dummynode' */
  324. t->lsizenode = 0;
  325. t->lastfree = NULL; /* signal that it is using dummy node */
  326. }
  327. else {
  328. int i;
  329. int lsize = luaO_ceillog2(size);
  330. if (lsize > MAXHBITS || (1u << lsize) > MAXHSIZE)
  331. luaG_runerror(L, "table overflow");
  332. size = twoto(lsize);
  333. t->node = luaM_newvector(L, size, Node);
  334. for (i = 0; i < (int)size; i++) {
  335. Node *n = gnode(t, i);
  336. gnext(n) = 0;
  337. setnilkey(n);
  338. setempty(gval(n));
  339. }
  340. t->lsizenode = cast_byte(lsize);
  341. t->lastfree = gnode(t, size); /* all positions are free */
  342. }
  343. }
  344. /*
  345. ** (Re)insert all elements from the hash part of 'ot' into table 't'.
  346. */
  347. static void reinsert (lua_State *L, Table *ot, Table *t) {
  348. int j;
  349. int size = sizenode(ot);
  350. for (j = 0; j < size; j++) {
  351. Node *old = gnode(ot, j);
  352. if (!isempty(gval(old))) {
  353. /* doesn't need barrier/invalidate cache, as entry was
  354. already present in the table */
  355. TValue k;
  356. getnodekey(L, &k, old);
  357. setobjt2t(L, luaH_set(L, t, &k), gval(old));
  358. }
  359. }
  360. }
  361. /*
  362. ** Exchange the hash part of 't1' and 't2'.
  363. */
  364. static void exchangehashpart (Table *t1, Table *t2) {
  365. lu_byte lsizenode = t1->lsizenode;
  366. Node *node = t1->node;
  367. Node *lastfree = t1->lastfree;
  368. t1->lsizenode = t2->lsizenode;
  369. t1->node = t2->node;
  370. t1->lastfree = t2->lastfree;
  371. t2->lsizenode = lsizenode;
  372. t2->node = node;
  373. t2->lastfree = lastfree;
  374. }
  375. /*
  376. ** Resize table 't' for the new given sizes. Both allocations (for
  377. ** the hash part and for the array part) can fail, which creates some
  378. ** subtleties. If the first allocation, for the hash part, fails, an
  379. ** error is raised and that is it. Otherwise, it copies the elements from
  380. ** the shrinking part of the array (if it is shrinking) into the new
  381. ** hash. Then it reallocates the array part. If that fails, the table
  382. ** is in its original state; the function frees the new hash part and then
  383. ** raises the allocation error. Otherwise, it sets the new hash part
  384. ** into the table, initializes the new part of the array (if any) with
  385. ** nils and reinserts the elements of the old hash back into the new
  386. ** parts of the table.
  387. */
  388. void luaH_resize (lua_State *L, Table *t, unsigned int newasize,
  389. unsigned int nhsize) {
  390. unsigned int i;
  391. Table newt; /* to keep the new hash part */
  392. unsigned int oldasize = t->sizearray;
  393. TValue *newarray;
  394. /* create new hash part with appropriate size into 'newt' */
  395. setnodevector(L, &newt, nhsize);
  396. if (newasize < oldasize) { /* will array shrink? */
  397. t->sizearray = newasize; /* pretend array has new size... */
  398. exchangehashpart(t, &newt); /* and new hash */
  399. /* re-insert into the new hash the elements from vanishing slice */
  400. for (i = newasize; i < oldasize; i++) {
  401. if (!isempty(&t->array[i]))
  402. luaH_setint(L, t, i + 1, &t->array[i]);
  403. }
  404. t->sizearray = oldasize; /* restore current size... */
  405. exchangehashpart(t, &newt); /* and hash (in case of errors) */
  406. }
  407. /* allocate new array */
  408. newarray = luaM_reallocvector(L, t->array, oldasize, newasize, TValue);
  409. if (unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */
  410. freehash(L, &newt); /* release new hash part */
  411. luaM_error(L); /* raise error (with array unchanged) */
  412. }
  413. /* allocation ok; initialize new part of the array */
  414. exchangehashpart(t, &newt); /* 't' has the new hash ('newt' has the old) */
  415. t->array = newarray; /* set new array part */
  416. t->sizearray = newasize;
  417. for (i = oldasize; i < newasize; i++) /* clear new slice of the array */
  418. setempty(&t->array[i]);
  419. /* re-insert elements from old hash part into new parts */
  420. reinsert(L, &newt, t); /* 'newt' now has the old hash */
  421. freehash(L, &newt); /* free old hash part */
  422. }
  423. void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
  424. int nsize = allocsizenode(t);
  425. luaH_resize(L, t, nasize, nsize);
  426. }
  427. /*
  428. ** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
  429. */
  430. static void rehash (lua_State *L, Table *t, const TValue *ek) {
  431. unsigned int asize; /* optimal size for array part */
  432. unsigned int na; /* number of keys in the array part */
  433. unsigned int nums[MAXABITS + 1];
  434. int i;
  435. int totaluse;
  436. for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */
  437. na = numusearray(t, nums); /* count keys in array part */
  438. totaluse = na; /* all those keys are integer keys */
  439. totaluse += numusehash(t, nums, &na); /* count keys in hash part */
  440. /* count extra key */
  441. if (ttisinteger(ek))
  442. na += countint(ivalue(ek), nums);
  443. totaluse++;
  444. /* compute new size for array part */
  445. asize = computesizes(nums, &na);
  446. /* resize the table to new computed sizes */
  447. luaH_resize(L, t, asize, totaluse - na);
  448. }
  449. /*
  450. ** }=============================================================
  451. */
  452. Table *luaH_new (lua_State *L) {
  453. GCObject *o = luaC_newobj(L, LUA_TTABLE, sizeof(Table));
  454. Table *t = gco2t(o);
  455. t->metatable = NULL;
  456. t->flags = cast_byte(~0);
  457. t->array = NULL;
  458. t->sizearray = 0;
  459. setnodevector(L, t, 0);
  460. return t;
  461. }
  462. void luaH_free (lua_State *L, Table *t) {
  463. freehash(L, t);
  464. luaM_freearray(L, t->array, t->sizearray);
  465. luaM_free(L, t);
  466. }
  467. static Node *getfreepos (Table *t) {
  468. if (!isdummy(t)) {
  469. while (t->lastfree > t->node) {
  470. t->lastfree--;
  471. if (keyisnil(t->lastfree))
  472. return t->lastfree;
  473. }
  474. }
  475. return NULL; /* could not find a free place */
  476. }
  477. /*
  478. ** inserts a new key into a hash table; first, check whether key's main
  479. ** position is free. If not, check whether colliding node is in its main
  480. ** position or not: if it is not, move colliding node to an empty place and
  481. ** put new key in its main position; otherwise (colliding node is in its main
  482. ** position), new key goes to an empty position.
  483. */
  484. TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
  485. Node *mp;
  486. TValue aux;
  487. if (unlikely(ttisnil(key)))
  488. luaG_runerror(L, "table index is nil");
  489. else if (ttisfloat(key)) {
  490. lua_Number f = fltvalue(key);
  491. lua_Integer k;
  492. if (luaV_flttointeger(f, &k, 0)) { /* does key fit in an integer? */
  493. setivalue(&aux, k);
  494. key = &aux; /* insert it as an integer */
  495. }
  496. else if (unlikely(luai_numisnan(f)))
  497. luaG_runerror(L, "table index is NaN");
  498. }
  499. mp = mainpositionTV(t, key);
  500. if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */
  501. Node *othern;
  502. Node *f = getfreepos(t); /* get a free place */
  503. if (f == NULL) { /* cannot find a free place? */
  504. rehash(L, t, key); /* grow table */
  505. /* whatever called 'newkey' takes care of TM cache */
  506. return luaH_set(L, t, key); /* insert key into grown table */
  507. }
  508. lua_assert(!isdummy(t));
  509. othern = mainposition(t, keytt(mp), &keyval(mp));
  510. if (othern != mp) { /* is colliding node out of its main position? */
  511. /* yes; move colliding node into free position */
  512. while (othern + gnext(othern) != mp) /* find previous */
  513. othern += gnext(othern);
  514. gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */
  515. *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  516. if (gnext(mp) != 0) {
  517. gnext(f) += cast_int(mp - f); /* correct 'next' */
  518. gnext(mp) = 0; /* now 'mp' is free */
  519. }
  520. setempty(gval(mp));
  521. }
  522. else { /* colliding node is in its own main position */
  523. /* new node will go into free position */
  524. if (gnext(mp) != 0)
  525. gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */
  526. else lua_assert(gnext(f) == 0);
  527. gnext(mp) = cast_int(f - mp);
  528. mp = f;
  529. }
  530. }
  531. setnodekey(L, mp, key);
  532. luaC_barrierback(L, obj2gco(t), key);
  533. lua_assert(isempty(gval(mp)));
  534. return gval(mp);
  535. }
  536. /*
  537. ** search function for integers
  538. */
  539. const TValue *luaH_getint (Table *t, lua_Integer key) {
  540. /* (1 <= key && key <= t->sizearray) */
  541. if (l_castS2U(key) - 1u < t->sizearray)
  542. return &t->array[key - 1];
  543. else {
  544. Node *n = hashint(t, key);
  545. for (;;) { /* check whether 'key' is somewhere in the chain */
  546. if (keyisinteger(n) && keyival(n) == key)
  547. return gval(n); /* that's it */
  548. else {
  549. int nx = gnext(n);
  550. if (nx == 0) break;
  551. n += nx;
  552. }
  553. }
  554. return &absentkey;
  555. }
  556. }
  557. /*
  558. ** search function for short strings
  559. */
  560. const TValue *luaH_getshortstr (Table *t, TString *key) {
  561. Node *n = hashstr(t, key);
  562. lua_assert(key->tt == LUA_TSHRSTR);
  563. for (;;) { /* check whether 'key' is somewhere in the chain */
  564. if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
  565. return gval(n); /* that's it */
  566. else {
  567. int nx = gnext(n);
  568. if (nx == 0)
  569. return &absentkey; /* not found */
  570. n += nx;
  571. }
  572. }
  573. }
  574. const TValue *luaH_getstr (Table *t, TString *key) {
  575. if (key->tt == LUA_TSHRSTR)
  576. return luaH_getshortstr(t, key);
  577. else { /* for long strings, use generic case */
  578. TValue ko;
  579. setsvalue(cast(lua_State *, NULL), &ko, key);
  580. return getgeneric(t, &ko);
  581. }
  582. }
  583. /*
  584. ** main search function
  585. */
  586. const TValue *luaH_get (Table *t, const TValue *key) {
  587. switch (ttypetag(key)) {
  588. case LUA_TSHRSTR: return luaH_getshortstr(t, tsvalue(key));
  589. case LUA_TNUMINT: return luaH_getint(t, ivalue(key));
  590. case LUA_TNIL: return &absentkey;
  591. case LUA_TNUMFLT: {
  592. lua_Integer k;
  593. if (luaV_flttointeger(fltvalue(key), &k, 0)) /* index is an integral? */
  594. return luaH_getint(t, k); /* use specialized version */
  595. /* else... */
  596. } /* FALLTHROUGH */
  597. default:
  598. return getgeneric(t, key);
  599. }
  600. }
  601. /*
  602. ** beware: when using this function you probably need to check a GC
  603. ** barrier and invalidate the TM cache.
  604. */
  605. TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
  606. const TValue *p = luaH_get(t, key);
  607. if (!isabstkey(p))
  608. return cast(TValue *, p);
  609. else return luaH_newkey(L, t, key);
  610. }
  611. void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
  612. const TValue *p = luaH_getint(t, key);
  613. TValue *cell;
  614. if (!isabstkey(p))
  615. cell = cast(TValue *, p);
  616. else {
  617. TValue k;
  618. setivalue(&k, key);
  619. cell = luaH_newkey(L, t, &k);
  620. }
  621. setobj2t(L, cell, value);
  622. }
  623. /*
  624. ** Try to find a boundary in the hash part of table 't'. From the
  625. ** caller, we know that 'j' is zero or present and that 'j + 1' is
  626. ** present. We want to find a larger key that is absent from the
  627. ** table, so that we can do a binary search between the two keys to
  628. ** find a boundary. We keep doubling 'j' until we get an absent index.
  629. ** If the doubling would overflow, we try LUA_MAXINTEGER. If it is
  630. ** absent, we are ready for the binary search. ('j', being max integer,
  631. ** is larger or equal to 'i', but it cannot be equal because it is
  632. ** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a
  633. ** boundary. ('j + 1' cannot be a present integer key because it is
  634. ** not a valid integer in Lua.)
  635. */
  636. static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
  637. lua_Unsigned i;
  638. if (j == 0) j++; /* the caller ensures 'j + 1' is present */
  639. do {
  640. i = j; /* 'i' is a present index */
  641. if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
  642. j *= 2;
  643. else {
  644. j = LUA_MAXINTEGER;
  645. if (isempty(luaH_getint(t, j))) /* t[j] not present? */
  646. break; /* 'j' now is an absent index */
  647. else /* weird case */
  648. return j; /* well, max integer is a boundary... */
  649. }
  650. } while (!isempty(luaH_getint(t, j))); /* repeat until an absent t[j] */
  651. /* i < j && t[i] present && t[j] absent */
  652. while (j - i > 1u) { /* do a binary search between them */
  653. lua_Unsigned m = (i + j) / 2;
  654. if (isempty(luaH_getint(t, m))) j = m;
  655. else i = m;
  656. }
  657. return i;
  658. }
  659. /*
  660. ** Try to find a boundary in table 't'. (A 'boundary' is an integer index
  661. ** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent
  662. ** and 'maxinteger' if t[maxinteger] is present.)
  663. ** First, try the array part: if there is an array part and its last
  664. ** element is absent, there must be a boundary there; a binary search
  665. ** finds that boundary. Otherwise, if the hash part is empty or does not
  666. ** contain 'j + 1', 'j' is a boundary. Otherwize, call 'hash_search'
  667. ** to find a boundary in the hash part.
  668. */
  669. lua_Unsigned luaH_getn (Table *t) {
  670. unsigned int j = t->sizearray;
  671. if (j > 0 && isempty(&t->array[j - 1])) {
  672. unsigned int i = 0;
  673. while (j - i > 1u) { /* binary search */
  674. unsigned int m = (i + j) / 2;
  675. if (isempty(&t->array[m - 1])) j = m;
  676. else i = m;
  677. }
  678. return i;
  679. }
  680. else { /* 'j' is zero or present in table */
  681. if (isdummy(t) || isempty(luaH_getint(t, cast(lua_Integer, j + 1))))
  682. return j; /* 'j + 1' is absent... */
  683. else /* 'j + 1' is also present */
  684. return hash_search(t, j);
  685. }
  686. }
  687. #if defined(LUA_DEBUG)
  688. Node *luaH_mainposition (const Table *t, const TValue *key) {
  689. return mainpositionTV(t, key);
  690. }
  691. int luaH_isdummy (const Table *t) { return isdummy(t); }
  692. #endif