ltable.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. /*
  2. ** $Id: ltable.c,v 2.128 2017/12/07 18:59: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_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(unsigned int, i) + cast(unsigned int, ni);
  94. return cast_int(u <= cast(unsigned int, 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(unsigned int, 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. /*
  224. ** {=============================================================
  225. ** Rehash
  226. ** ==============================================================
  227. */
  228. /*
  229. ** Compute the optimal size for the array part of table 't'. 'nums' is a
  230. ** "count array" where 'nums[i]' is the number of integers in the table
  231. ** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of
  232. ** integer keys in the table and leaves with the number of keys that
  233. ** will go to the array part; return the optimal size. (The condition
  234. ** 'twotoi > 0' in the for loop stops the loop if 'twotoi' overflows.)
  235. */
  236. static unsigned int computesizes (unsigned int nums[], unsigned int *pna) {
  237. int i;
  238. unsigned int twotoi; /* 2^i (candidate for optimal size) */
  239. unsigned int a = 0; /* number of elements smaller than 2^i */
  240. unsigned int na = 0; /* number of elements to go to array part */
  241. unsigned int optimal = 0; /* optimal size for array part */
  242. /* loop while keys can fill more than half of total size */
  243. for (i = 0, twotoi = 1;
  244. twotoi > 0 && *pna > twotoi / 2;
  245. i++, twotoi *= 2) {
  246. a += nums[i];
  247. if (a > twotoi/2) { /* more than half elements present? */
  248. optimal = twotoi; /* optimal size (till now) */
  249. na = a; /* all elements up to 'optimal' will go to array part */
  250. }
  251. }
  252. lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal);
  253. *pna = na;
  254. return optimal;
  255. }
  256. static int countint (lua_Integer key, unsigned int *nums) {
  257. unsigned int k = arrayindex(key);
  258. if (k != 0) { /* is 'key' an appropriate array index? */
  259. nums[luaO_ceillog2(k)]++; /* count as such */
  260. return 1;
  261. }
  262. else
  263. return 0;
  264. }
  265. /*
  266. ** Count keys in array part of table 't': Fill 'nums[i]' with
  267. ** number of keys that will go into corresponding slice and return
  268. ** total number of non-nil keys.
  269. */
  270. static unsigned int numusearray (const Table *t, unsigned int *nums) {
  271. int lg;
  272. unsigned int ttlg; /* 2^lg */
  273. unsigned int ause = 0; /* summation of 'nums' */
  274. unsigned int i = 1; /* count to traverse all array keys */
  275. /* traverse each slice */
  276. for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
  277. unsigned int lc = 0; /* counter */
  278. unsigned int lim = ttlg;
  279. if (lim > t->sizearray) {
  280. lim = t->sizearray; /* adjust upper limit */
  281. if (i > lim)
  282. break; /* no more elements to count */
  283. }
  284. /* count elements in range (2^(lg - 1), 2^lg] */
  285. for (; i <= lim; i++) {
  286. if (!ttisnil(&t->array[i-1]))
  287. lc++;
  288. }
  289. nums[lg] += lc;
  290. ause += lc;
  291. }
  292. return ause;
  293. }
  294. static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) {
  295. int totaluse = 0; /* total number of elements */
  296. int ause = 0; /* elements added to 'nums' (can go to array part) */
  297. int i = sizenode(t);
  298. while (i--) {
  299. Node *n = &t->node[i];
  300. if (!ttisnil(gval(n))) {
  301. if (keyisinteger(n))
  302. ause += countint(keyival(n), nums);
  303. totaluse++;
  304. }
  305. }
  306. *pna += ause;
  307. return totaluse;
  308. }
  309. /*
  310. ** Creates an array for the hash part of a table with the given
  311. ** size, or reuses the dummy node if size is zero.
  312. ** The computation for size overflow is in two steps: the first
  313. ** comparison ensures that the shift in the second one does not
  314. ** overflow.
  315. */
  316. static void setnodevector (lua_State *L, Table *t, unsigned int size) {
  317. if (size == 0) { /* no elements to hash part? */
  318. t->node = cast(Node *, dummynode); /* use common 'dummynode' */
  319. t->lsizenode = 0;
  320. t->lastfree = NULL; /* signal that it is using dummy node */
  321. }
  322. else {
  323. int i;
  324. int lsize = luaO_ceillog2(size);
  325. if (lsize > MAXHBITS || (1u << lsize) > MAXHSIZE)
  326. luaG_runerror(L, "table overflow");
  327. size = twoto(lsize);
  328. t->node = luaM_newvector(L, size, Node);
  329. for (i = 0; i < (int)size; i++) {
  330. Node *n = gnode(t, i);
  331. gnext(n) = 0;
  332. setnilkey(n);
  333. setnilvalue(gval(n));
  334. }
  335. t->lsizenode = cast_byte(lsize);
  336. t->lastfree = gnode(t, size); /* all positions are free */
  337. }
  338. }
  339. /*
  340. ** (Re)insert all elements from list 'nodes' into table 't'.
  341. */
  342. static void reinsert(lua_State *L, Node *nodes, int nsize, Table *t) {
  343. int j;
  344. for (j = nsize - 1; j >= 0; j--) {
  345. Node *old = nodes + j;
  346. if (!ttisnil(gval(old))) {
  347. /* doesn't need barrier/invalidate cache, as entry was
  348. already present in the table */
  349. TValue k;
  350. getnodekey(L, &k, old);
  351. setobjt2t(L, luaH_set(L, t, &k), gval(old));
  352. }
  353. }
  354. }
  355. /*
  356. ** Resize table 't' for the new given sizes. Both allocations
  357. ** (for the hash part and for the array part) can fail, which
  358. ** creates some subtleties. If the first allocation, for the hash
  359. ** part, fails, an error is raised and that is it. Otherwise,
  360. ** copy the elements in the shrinking part of the array (if it
  361. ** is shrinking) into the new hash. Then it reallocates the array part.
  362. ** If that fails, it frees the new hash part and restores the old hash
  363. ** part (to restore the original state of the table), and then raises
  364. ** the allocation error. Otherwise, initialize the new part of the
  365. ** array (if any) with nils and reinsert the elements in the old
  366. ** hash back into the new parts of the table.
  367. */
  368. void luaH_resize (lua_State *L, Table *t, unsigned int newasize,
  369. unsigned int nhsize) {
  370. unsigned int i;
  371. Node *oldnode = t->node; /* save old hash ... */
  372. Node *oldlastfree = t->lastfree;
  373. int oldlsizenode = t->lsizenode;
  374. int oldhsize = allocsizenode(t);
  375. unsigned int oldasize = t->sizearray;
  376. TValue *newarray;
  377. /* create new hash part with appropriate size */
  378. setnodevector(L, t, nhsize);
  379. if (newasize < oldasize) { /* will array shrink? */
  380. /* re-insert into the hash the elements from vanishing slice */
  381. t->sizearray = newasize; /* pretend array has new size */
  382. for (i = newasize; i < oldasize; i++) {
  383. if (!ttisnil(&t->array[i]))
  384. luaH_setint(L, t, i + 1, &t->array[i]);
  385. }
  386. t->sizearray = oldasize; /* restore current size */
  387. }
  388. /* allocate new array */
  389. newarray = luaM_reallocvector(L, t->array, oldasize, newasize, TValue);
  390. if (newarray == NULL && newasize > 0) { /* allocation failed? */
  391. if (nhsize > 0) /* not the dummy node? */
  392. luaM_freearray(L, t->node, allocsizenode(t)); /* release new hash part */
  393. t->node = oldnode; /* restore original hash part */
  394. t->lastfree = oldlastfree;
  395. t->lsizenode = oldlsizenode;
  396. lua_assert(!isdummy(t) == (t->node != dummynode));
  397. luaM_error(L); /* error with array unchanged */
  398. }
  399. /* allocation ok; initialize new part of the array */
  400. t->array = newarray;
  401. t->sizearray = newasize;
  402. for (i = oldasize; i < newasize; i++)
  403. setnilvalue(&t->array[i]);
  404. /* re-insert elements from old hash part into new parts */
  405. reinsert(L, oldnode, oldhsize, t);
  406. /* free old hash */
  407. if (oldhsize > 0) /* not the dummy node? */
  408. luaM_freearray(L, oldnode, cast(size_t, oldhsize));
  409. lua_assert(!isdummy(t) == (t->node != dummynode));
  410. }
  411. void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
  412. int nsize = allocsizenode(t);
  413. luaH_resize(L, t, nasize, nsize);
  414. }
  415. /*
  416. ** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
  417. */
  418. static void rehash (lua_State *L, Table *t, const TValue *ek) {
  419. unsigned int asize; /* optimal size for array part */
  420. unsigned int na; /* number of keys in the array part */
  421. unsigned int nums[MAXABITS + 1];
  422. int i;
  423. int totaluse;
  424. for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */
  425. na = numusearray(t, nums); /* count keys in array part */
  426. totaluse = na; /* all those keys are integer keys */
  427. totaluse += numusehash(t, nums, &na); /* count keys in hash part */
  428. /* count extra key */
  429. if (ttisinteger(ek))
  430. na += countint(ivalue(ek), nums);
  431. totaluse++;
  432. /* compute new size for array part */
  433. asize = computesizes(nums, &na);
  434. /* resize the table to new computed sizes */
  435. luaH_resize(L, t, asize, totaluse - na);
  436. }
  437. /*
  438. ** }=============================================================
  439. */
  440. Table *luaH_new (lua_State *L) {
  441. GCObject *o = luaC_newobj(L, LUA_TTABLE, sizeof(Table));
  442. Table *t = gco2t(o);
  443. t->metatable = NULL;
  444. t->flags = cast_byte(~0);
  445. t->array = NULL;
  446. t->sizearray = 0;
  447. setnodevector(L, t, 0);
  448. return t;
  449. }
  450. void luaH_free (lua_State *L, Table *t) {
  451. if (!isdummy(t))
  452. luaM_freearray(L, t->node, cast(size_t, sizenode(t)));
  453. luaM_freearray(L, t->array, t->sizearray);
  454. luaM_free(L, t);
  455. }
  456. static Node *getfreepos (Table *t) {
  457. if (!isdummy(t)) {
  458. while (t->lastfree > t->node) {
  459. t->lastfree--;
  460. if (keyisnil(t->lastfree))
  461. return t->lastfree;
  462. }
  463. }
  464. return NULL; /* could not find a free place */
  465. }
  466. /*
  467. ** inserts a new key into a hash table; first, check whether key's main
  468. ** position is free. If not, check whether colliding node is in its main
  469. ** position or not: if it is not, move colliding node to an empty place and
  470. ** put new key in its main position; otherwise (colliding node is in its main
  471. ** position), new key goes to an empty position.
  472. */
  473. TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
  474. Node *mp;
  475. TValue aux;
  476. if (ttisnil(key)) luaG_runerror(L, "table index is nil");
  477. else if (ttisfloat(key)) {
  478. lua_Integer k;
  479. if (luaV_flttointeger(key, &k, 0)) { /* does index fit in an integer? */
  480. setivalue(&aux, k);
  481. key = &aux; /* insert it as an integer */
  482. }
  483. else if (luai_numisnan(fltvalue(key)))
  484. luaG_runerror(L, "table index is NaN");
  485. }
  486. mp = mainpositionTV(t, key);
  487. if (!ttisnil(gval(mp)) || isdummy(t)) { /* main position is taken? */
  488. Node *othern;
  489. Node *f = getfreepos(t); /* get a free place */
  490. if (f == NULL) { /* cannot find a free place? */
  491. rehash(L, t, key); /* grow table */
  492. /* whatever called 'newkey' takes care of TM cache */
  493. return luaH_set(L, t, key); /* insert key into grown table */
  494. }
  495. lua_assert(!isdummy(t));
  496. othern = mainposition(t, keytt(mp), &keyval(mp));
  497. if (othern != mp) { /* is colliding node out of its main position? */
  498. /* yes; move colliding node into free position */
  499. while (othern + gnext(othern) != mp) /* find previous */
  500. othern += gnext(othern);
  501. gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */
  502. *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  503. if (gnext(mp) != 0) {
  504. gnext(f) += cast_int(mp - f); /* correct 'next' */
  505. gnext(mp) = 0; /* now 'mp' is free */
  506. }
  507. setnilvalue(gval(mp));
  508. }
  509. else { /* colliding node is in its own main position */
  510. /* new node will go into free position */
  511. if (gnext(mp) != 0)
  512. gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */
  513. else lua_assert(gnext(f) == 0);
  514. gnext(mp) = cast_int(f - mp);
  515. mp = f;
  516. }
  517. }
  518. setnodekey(L, mp, key);
  519. luaC_barrierback(L, t, key);
  520. lua_assert(ttisnil(gval(mp)));
  521. return gval(mp);
  522. }
  523. /*
  524. ** search function for integers
  525. */
  526. const TValue *luaH_getint (Table *t, lua_Integer key) {
  527. /* (1 <= key && key <= t->sizearray) */
  528. if (l_castS2U(key) - 1u < t->sizearray)
  529. return &t->array[key - 1];
  530. else {
  531. Node *n = hashint(t, key);
  532. for (;;) { /* check whether 'key' is somewhere in the chain */
  533. if (keyisinteger(n) && keyival(n) == key)
  534. return gval(n); /* that's it */
  535. else {
  536. int nx = gnext(n);
  537. if (nx == 0) break;
  538. n += nx;
  539. }
  540. }
  541. return luaO_nilobject;
  542. }
  543. }
  544. /*
  545. ** search function for short strings
  546. */
  547. const TValue *luaH_getshortstr (Table *t, TString *key) {
  548. Node *n = hashstr(t, key);
  549. lua_assert(key->tt == LUA_TSHRSTR);
  550. for (;;) { /* check whether 'key' is somewhere in the chain */
  551. if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
  552. return gval(n); /* that's it */
  553. else {
  554. int nx = gnext(n);
  555. if (nx == 0)
  556. return luaO_nilobject; /* not found */
  557. n += nx;
  558. }
  559. }
  560. }
  561. const TValue *luaH_getstr (Table *t, TString *key) {
  562. if (key->tt == LUA_TSHRSTR)
  563. return luaH_getshortstr(t, key);
  564. else { /* for long strings, use generic case */
  565. TValue ko;
  566. setsvalue(cast(lua_State *, NULL), &ko, key);
  567. return getgeneric(t, &ko);
  568. }
  569. }
  570. /*
  571. ** main search function
  572. */
  573. const TValue *luaH_get (Table *t, const TValue *key) {
  574. switch (ttype(key)) {
  575. case LUA_TSHRSTR: return luaH_getshortstr(t, tsvalue(key));
  576. case LUA_TNUMINT: return luaH_getint(t, ivalue(key));
  577. case LUA_TNIL: return luaO_nilobject;
  578. case LUA_TNUMFLT: {
  579. lua_Integer k;
  580. if (luaV_flttointeger(key, &k, 0)) /* index is an integral? */
  581. return luaH_getint(t, k); /* use specialized version */
  582. /* else... */
  583. } /* FALLTHROUGH */
  584. default:
  585. return getgeneric(t, key);
  586. }
  587. }
  588. /*
  589. ** beware: when using this function you probably need to check a GC
  590. ** barrier and invalidate the TM cache.
  591. */
  592. TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
  593. const TValue *p = luaH_get(t, key);
  594. if (p != luaO_nilobject)
  595. return cast(TValue *, p);
  596. else return luaH_newkey(L, t, key);
  597. }
  598. void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
  599. const TValue *p = luaH_getint(t, key);
  600. TValue *cell;
  601. if (p != luaO_nilobject)
  602. cell = cast(TValue *, p);
  603. else {
  604. TValue k;
  605. setivalue(&k, key);
  606. cell = luaH_newkey(L, t, &k);
  607. }
  608. setobj2t(L, cell, value);
  609. }
  610. /*
  611. ** Try to find a boundary in the hash part of table 't'. From the
  612. ** caller, we know that 'j' is zero or present and that 'j + 1' is
  613. ** present. We want to find a larger key that is absent from the
  614. ** table, so that we can do a binary search between the two keys to
  615. ** find a boundary. We keep doubling 'j' until we get an absent index.
  616. ** If the doubling would overflow, we try LUA_MAXINTEGER. If it is
  617. ** absent, we are ready for the binary search. ('j', being max integer,
  618. ** is larger or equal to 'i', but it cannot be equal because it is
  619. ** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a
  620. ** boundary. ('j + 1' cannot be a present integer key because it is
  621. ** not a valid integer in Lua.)
  622. */
  623. static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
  624. lua_Unsigned i;
  625. if (j == 0) j++; /* the caller ensures 'j + 1' is present */
  626. do {
  627. i = j; /* 'i' is a present index */
  628. if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
  629. j *= 2;
  630. else {
  631. j = LUA_MAXINTEGER;
  632. if (ttisnil(luaH_getint(t, j))) /* t[j] == nil? */
  633. break; /* 'j' now is an absent index */
  634. else /* weird case */
  635. return j; /* well, max integer is a boundary... */
  636. }
  637. } while (!ttisnil(luaH_getint(t, j))); /* repeat until t[j] == nil */
  638. /* i < j && t[i] !≃ nil && t[j] == nil */
  639. while (j - i > 1u) { /* do a binary search between them */
  640. lua_Unsigned m = (i + j) / 2;
  641. if (ttisnil(luaH_getint(t, m))) j = m;
  642. else i = m;
  643. }
  644. return i;
  645. }
  646. /*
  647. ** Try to find a boundary in table 't'. (A 'boundary' is an integer index
  648. ** such that t[i] is non-nil and t[i+1] is nil, plus 0 if t[1] is nil
  649. ** and 'maxinteger' if t[maxinteger] is not nil.)
  650. ** First, try the array part: if there is an array part and its last
  651. ** element is nil, there must be a boundary there; a binary search
  652. ** finds that boundary. Otherwise, if the hash part is empty or does not
  653. ** contain 'j + 1', 'j' is a boundary. Otherwize, call 'hash_search'
  654. ** to find a boundary in the hash part.
  655. */
  656. lua_Unsigned luaH_getn (Table *t) {
  657. unsigned int j = t->sizearray;
  658. if (j > 0 && ttisnil(&t->array[j - 1])) {
  659. unsigned int i = 0;
  660. while (j - i > 1u) { /* binary search */
  661. unsigned int m = (i + j) / 2;
  662. if (ttisnil(&t->array[m - 1])) j = m;
  663. else i = m;
  664. }
  665. return i;
  666. }
  667. else { /* 'j' is zero or present in table */
  668. if (isdummy(t) || ttisnil(luaH_getint(t, l_castU2S(j + 1))))
  669. return j; /* 'j + 1' is absent... */
  670. else /* 'j + 1' is also present */
  671. return hash_search(t, j);
  672. }
  673. }
  674. #if defined(LUA_DEBUG)
  675. Node *luaH_mainposition (const Table *t, const TValue *key) {
  676. return mainpositionTV(t, key);
  677. }
  678. int luaH_isdummy (const Table *t) { return isdummy(t); }
  679. #endif