ltable.c 22 KB

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