ltable.c 24 KB

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