ltable.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. /*
  2. ** $Id: ltable.c,v 2.122 2017/05/19 12:57:10 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. ** returns the index for 'k' if 'k' is an appropriate key to live in
  150. ** the array part of a table, 0 otherwise.
  151. */
  152. static unsigned int arrayindex (lua_Integer k) {
  153. if (0 < k && l_castS2U(k) <= MAXASIZE)
  154. return cast(unsigned int, k); /* 'key' is an appropriate array index */
  155. else
  156. return 0;
  157. }
  158. /*
  159. ** returns the index of a 'key' for table traversals. First goes all
  160. ** elements in the array part, then elements in the hash part. The
  161. ** beginning of a traversal is signaled by 0.
  162. */
  163. static unsigned int findindex (lua_State *L, Table *t, StkId key) {
  164. unsigned int i;
  165. if (ttisnil(key)) return 0; /* first iteration */
  166. i = ttisinteger(key) ? arrayindex(ivalue(key)) : 0;
  167. if (i != 0 && i <= t->sizearray) /* is 'key' inside array part? */
  168. return i; /* yes; that's the index */
  169. else {
  170. int nx;
  171. Node *n = mainpositionTV(t, key);
  172. for (;;) { /* check whether 'key' is somewhere in the chain */
  173. /* key may be dead already, but it is ok to use it in 'next' */
  174. if (equalkey(key, n) ||
  175. (keyisdead(n) && iscollectable(key) &&
  176. deadkey(n) == gcvalue(key))) {
  177. i = cast_int(n - gnode(t, 0)); /* key index in hash table */
  178. /* hash elements are numbered after array ones */
  179. return (i + 1) + t->sizearray;
  180. }
  181. nx = gnext(n);
  182. if (nx == 0)
  183. luaG_runerror(L, "invalid key to 'next'"); /* key not found */
  184. else n += nx;
  185. }
  186. }
  187. }
  188. int luaH_next (lua_State *L, Table *t, StkId key) {
  189. unsigned int i = findindex(L, t, key); /* find original element */
  190. for (; i < t->sizearray; i++) { /* try first array part */
  191. if (!ttisnil(&t->array[i])) { /* a non-nil value? */
  192. setivalue(key, i + 1);
  193. setobj2s(L, key+1, &t->array[i]);
  194. return 1;
  195. }
  196. }
  197. for (i -= t->sizearray; cast_int(i) < sizenode(t); i++) { /* hash part */
  198. if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */
  199. Node *n = gnode(t, i);
  200. getnodekey(L, key, n);
  201. setobj2s(L, key + 1, gval(n));
  202. return 1;
  203. }
  204. }
  205. return 0; /* no more elements */
  206. }
  207. /*
  208. ** {=============================================================
  209. ** Rehash
  210. ** ==============================================================
  211. */
  212. /*
  213. ** Compute the optimal size for the array part of table 't'. 'nums' is a
  214. ** "count array" where 'nums[i]' is the number of integers in the table
  215. ** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of
  216. ** integer keys in the table and leaves with the number of keys that
  217. ** will go to the array part; return the optimal size. (The condition
  218. ** 'twotoi > 0' in the for loop stops the loop if 'twotoi' overflows.)
  219. */
  220. static unsigned int computesizes (unsigned int nums[], unsigned int *pna) {
  221. int i;
  222. unsigned int twotoi; /* 2^i (candidate for optimal size) */
  223. unsigned int a = 0; /* number of elements smaller than 2^i */
  224. unsigned int na = 0; /* number of elements to go to array part */
  225. unsigned int optimal = 0; /* optimal size for array part */
  226. /* loop while keys can fill more than half of total size */
  227. for (i = 0, twotoi = 1;
  228. twotoi > 0 && *pna > twotoi / 2;
  229. i++, twotoi *= 2) {
  230. a += nums[i];
  231. if (a > twotoi/2) { /* more than half elements present? */
  232. optimal = twotoi; /* optimal size (till now) */
  233. na = a; /* all elements up to 'optimal' will go to array part */
  234. }
  235. }
  236. lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal);
  237. *pna = na;
  238. return optimal;
  239. }
  240. static int countint (lua_Integer key, unsigned int *nums) {
  241. unsigned int k = arrayindex(key);
  242. if (k != 0) { /* is 'key' an appropriate array index? */
  243. nums[luaO_ceillog2(k)]++; /* count as such */
  244. return 1;
  245. }
  246. else
  247. return 0;
  248. }
  249. /*
  250. ** Count keys in array part of table 't': Fill 'nums[i]' with
  251. ** number of keys that will go into corresponding slice and return
  252. ** total number of non-nil keys.
  253. */
  254. static unsigned int numusearray (const Table *t, unsigned int *nums) {
  255. int lg;
  256. unsigned int ttlg; /* 2^lg */
  257. unsigned int ause = 0; /* summation of 'nums' */
  258. unsigned int i = 1; /* count to traverse all array keys */
  259. /* traverse each slice */
  260. for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
  261. unsigned int lc = 0; /* counter */
  262. unsigned int lim = ttlg;
  263. if (lim > t->sizearray) {
  264. lim = t->sizearray; /* adjust upper limit */
  265. if (i > lim)
  266. break; /* no more elements to count */
  267. }
  268. /* count elements in range (2^(lg - 1), 2^lg] */
  269. for (; i <= lim; i++) {
  270. if (!ttisnil(&t->array[i-1]))
  271. lc++;
  272. }
  273. nums[lg] += lc;
  274. ause += lc;
  275. }
  276. return ause;
  277. }
  278. static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) {
  279. int totaluse = 0; /* total number of elements */
  280. int ause = 0; /* elements added to 'nums' (can go to array part) */
  281. int i = sizenode(t);
  282. while (i--) {
  283. Node *n = &t->node[i];
  284. if (!ttisnil(gval(n))) {
  285. if (keyisinteger(n))
  286. ause += countint(keyival(n), nums);
  287. totaluse++;
  288. }
  289. }
  290. *pna += ause;
  291. return totaluse;
  292. }
  293. static void setarrayvector (lua_State *L, Table *t, unsigned int size) {
  294. unsigned int i;
  295. luaM_reallocvector(L, t->array, t->sizearray, size, TValue);
  296. for (i=t->sizearray; i<size; i++)
  297. setnilvalue(&t->array[i]);
  298. t->sizearray = size;
  299. }
  300. static void setnodevector (lua_State *L, Table *t, unsigned int size) {
  301. if (size == 0) { /* no elements to hash part? */
  302. t->node = cast(Node *, dummynode); /* use common 'dummynode' */
  303. t->lsizenode = 0;
  304. t->lastfree = NULL; /* signal that it is using dummy node */
  305. }
  306. else {
  307. int i;
  308. int lsize = luaO_ceillog2(size);
  309. if (lsize > MAXHBITS)
  310. luaG_runerror(L, "table overflow");
  311. size = twoto(lsize);
  312. t->node = luaM_newvector(L, size, Node);
  313. for (i = 0; i < (int)size; i++) {
  314. Node *n = gnode(t, i);
  315. gnext(n) = 0;
  316. setnilkey(n);
  317. setnilvalue(gval(n));
  318. }
  319. t->lsizenode = cast_byte(lsize);
  320. t->lastfree = gnode(t, size); /* all positions are free */
  321. }
  322. }
  323. void luaH_resize (lua_State *L, Table *t, unsigned int nasize,
  324. unsigned int nhsize) {
  325. unsigned int i;
  326. int j;
  327. unsigned int oldasize = t->sizearray;
  328. int oldhsize = allocsizenode(t);
  329. Node *nold = t->node; /* save old hash ... */
  330. if (nasize > oldasize) /* array part must grow? */
  331. setarrayvector(L, t, nasize);
  332. /* create new hash part with appropriate size */
  333. setnodevector(L, t, nhsize);
  334. if (nasize < oldasize) { /* array part must shrink? */
  335. t->sizearray = nasize;
  336. /* re-insert elements from vanishing slice */
  337. for (i=nasize; i<oldasize; i++) {
  338. if (!ttisnil(&t->array[i]))
  339. luaH_setint(L, t, i + 1, &t->array[i]);
  340. }
  341. /* shrink array */
  342. luaM_reallocvector(L, t->array, oldasize, nasize, TValue);
  343. }
  344. /* re-insert elements from hash part */
  345. for (j = oldhsize - 1; j >= 0; j--) {
  346. Node *old = nold + j;
  347. if (!ttisnil(gval(old))) {
  348. /* doesn't need barrier/invalidate cache, as entry was
  349. already present in the table */
  350. TValue k; getnodekey(L, &k, old);
  351. setobjt2t(L, luaH_set(L, t, &k), gval(old));
  352. }
  353. }
  354. if (oldhsize > 0) /* not the dummy node? */
  355. luaM_freearray(L, nold, cast(size_t, oldhsize)); /* free old hash */
  356. }
  357. void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
  358. int nsize = allocsizenode(t);
  359. luaH_resize(L, t, nasize, nsize);
  360. }
  361. /*
  362. ** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
  363. */
  364. static void rehash (lua_State *L, Table *t, const TValue *ek) {
  365. unsigned int asize; /* optimal size for array part */
  366. unsigned int na; /* number of keys in the array part */
  367. unsigned int nums[MAXABITS + 1];
  368. int i;
  369. int totaluse;
  370. for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */
  371. na = numusearray(t, nums); /* count keys in array part */
  372. totaluse = na; /* all those keys are integer keys */
  373. totaluse += numusehash(t, nums, &na); /* count keys in hash part */
  374. /* count extra key */
  375. if (ttisinteger(ek))
  376. na += countint(ivalue(ek), nums);
  377. totaluse++;
  378. /* compute new size for array part */
  379. asize = computesizes(nums, &na);
  380. /* resize the table to new computed sizes */
  381. luaH_resize(L, t, asize, totaluse - na);
  382. }
  383. /*
  384. ** }=============================================================
  385. */
  386. Table *luaH_new (lua_State *L) {
  387. GCObject *o = luaC_newobj(L, LUA_TTABLE, sizeof(Table));
  388. Table *t = gco2t(o);
  389. t->metatable = NULL;
  390. t->flags = cast_byte(~0);
  391. t->array = NULL;
  392. t->sizearray = 0;
  393. setnodevector(L, t, 0);
  394. return t;
  395. }
  396. void luaH_free (lua_State *L, Table *t) {
  397. if (!isdummy(t))
  398. luaM_freearray(L, t->node, cast(size_t, sizenode(t)));
  399. luaM_freearray(L, t->array, t->sizearray);
  400. luaM_free(L, t);
  401. }
  402. static Node *getfreepos (Table *t) {
  403. if (!isdummy(t)) {
  404. while (t->lastfree > t->node) {
  405. t->lastfree--;
  406. if (keyisnil(t->lastfree))
  407. return t->lastfree;
  408. }
  409. }
  410. return NULL; /* could not find a free place */
  411. }
  412. /*
  413. ** inserts a new key into a hash table; first, check whether key's main
  414. ** position is free. If not, check whether colliding node is in its main
  415. ** position or not: if it is not, move colliding node to an empty place and
  416. ** put new key in its main position; otherwise (colliding node is in its main
  417. ** position), new key goes to an empty position.
  418. */
  419. TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
  420. Node *mp;
  421. TValue aux;
  422. if (ttisnil(key)) luaG_runerror(L, "table index is nil");
  423. else if (ttisfloat(key)) {
  424. lua_Integer k;
  425. if (luaV_tointeger(key, &k, 0)) { /* does index fit in an integer? */
  426. setivalue(&aux, k);
  427. key = &aux; /* insert it as an integer */
  428. }
  429. else if (luai_numisnan(fltvalue(key)))
  430. luaG_runerror(L, "table index is NaN");
  431. }
  432. mp = mainpositionTV(t, key);
  433. if (!ttisnil(gval(mp)) || isdummy(t)) { /* main position is taken? */
  434. Node *othern;
  435. Node *f = getfreepos(t); /* get a free place */
  436. if (f == NULL) { /* cannot find a free place? */
  437. rehash(L, t, key); /* grow table */
  438. /* whatever called 'newkey' takes care of TM cache */
  439. return luaH_set(L, t, key); /* insert key into grown table */
  440. }
  441. lua_assert(!isdummy(t));
  442. othern = mainposition(t, keytt(mp), &keyval(mp));
  443. if (othern != mp) { /* is colliding node out of its main position? */
  444. /* yes; move colliding node into free position */
  445. while (othern + gnext(othern) != mp) /* find previous */
  446. othern += gnext(othern);
  447. gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */
  448. *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  449. if (gnext(mp) != 0) {
  450. gnext(f) += cast_int(mp - f); /* correct 'next' */
  451. gnext(mp) = 0; /* now 'mp' is free */
  452. }
  453. setnilvalue(gval(mp));
  454. }
  455. else { /* colliding node is in its own main position */
  456. /* new node will go into free position */
  457. if (gnext(mp) != 0)
  458. gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */
  459. else lua_assert(gnext(f) == 0);
  460. gnext(mp) = cast_int(f - mp);
  461. mp = f;
  462. }
  463. }
  464. setnodekey(L, mp, key);
  465. luaC_barrierback(L, t, key);
  466. lua_assert(ttisnil(gval(mp)));
  467. return gval(mp);
  468. }
  469. /*
  470. ** search function for integers
  471. */
  472. const TValue *luaH_getint (Table *t, lua_Integer key) {
  473. /* (1 <= key && key <= t->sizearray) */
  474. if (l_castS2U(key) - 1u < t->sizearray)
  475. return &t->array[key - 1];
  476. else {
  477. Node *n = hashint(t, key);
  478. for (;;) { /* check whether 'key' is somewhere in the chain */
  479. if (keyisinteger(n) && keyival(n) == key)
  480. return gval(n); /* that's it */
  481. else {
  482. int nx = gnext(n);
  483. if (nx == 0) break;
  484. n += nx;
  485. }
  486. }
  487. return luaO_nilobject;
  488. }
  489. }
  490. /*
  491. ** search function for short strings
  492. */
  493. const TValue *luaH_getshortstr (Table *t, TString *key) {
  494. Node *n = hashstr(t, key);
  495. lua_assert(key->tt == LUA_TSHRSTR);
  496. for (;;) { /* check whether 'key' is somewhere in the chain */
  497. if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
  498. return gval(n); /* that's it */
  499. else {
  500. int nx = gnext(n);
  501. if (nx == 0)
  502. return luaO_nilobject; /* not found */
  503. n += nx;
  504. }
  505. }
  506. }
  507. /*
  508. ** "Generic" get version. (Not that generic: not valid for integers,
  509. ** which may be in array part, nor for floats with integral values.)
  510. */
  511. static const TValue *getgeneric (Table *t, const TValue *key) {
  512. Node *n = mainpositionTV(t, key);
  513. for (;;) { /* check whether 'key' is somewhere in the chain */
  514. if (equalkey(key, n))
  515. return gval(n); /* that's it */
  516. else {
  517. int nx = gnext(n);
  518. if (nx == 0)
  519. return luaO_nilobject; /* not found */
  520. n += nx;
  521. }
  522. }
  523. }
  524. const TValue *luaH_getstr (Table *t, TString *key) {
  525. if (key->tt == LUA_TSHRSTR)
  526. return luaH_getshortstr(t, key);
  527. else { /* for long strings, use generic case */
  528. TValue ko;
  529. setsvalue(cast(lua_State *, NULL), &ko, key);
  530. return getgeneric(t, &ko);
  531. }
  532. }
  533. /*
  534. ** main search function
  535. */
  536. const TValue *luaH_get (Table *t, const TValue *key) {
  537. switch (ttype(key)) {
  538. case LUA_TSHRSTR: return luaH_getshortstr(t, tsvalue(key));
  539. case LUA_TNUMINT: return luaH_getint(t, ivalue(key));
  540. case LUA_TNIL: return luaO_nilobject;
  541. case LUA_TNUMFLT: {
  542. lua_Integer k;
  543. if (luaV_tointeger(key, &k, 0)) /* index is int? */
  544. return luaH_getint(t, k); /* use specialized version */
  545. /* else... */
  546. } /* FALLTHROUGH */
  547. default:
  548. return getgeneric(t, key);
  549. }
  550. }
  551. /*
  552. ** beware: when using this function you probably need to check a GC
  553. ** barrier and invalidate the TM cache.
  554. */
  555. TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
  556. const TValue *p = luaH_get(t, key);
  557. if (p != luaO_nilobject)
  558. return cast(TValue *, p);
  559. else return luaH_newkey(L, t, key);
  560. }
  561. void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
  562. const TValue *p = luaH_getint(t, key);
  563. TValue *cell;
  564. if (p != luaO_nilobject)
  565. cell = cast(TValue *, p);
  566. else {
  567. TValue k;
  568. setivalue(&k, key);
  569. cell = luaH_newkey(L, t, &k);
  570. }
  571. setobj2t(L, cell, value);
  572. }
  573. /*
  574. ** Try to find a boundary in the hash part of table 't'. From the
  575. ** caller, we know that 'j' is zero or present and that 'j + 1' is
  576. ** present. We want to find a larger key that is absent from the
  577. ** table, so that we can do a binary search between the two keys to
  578. ** find a boundary. We keep doubling 'j' until we get an absent index.
  579. ** If the doubling would overflow, we try LUA_MAXINTEGER. If it is
  580. ** absent, we are ready for the binary search. ('j', being max integer,
  581. ** is larger or equal to 'i', but it cannot be equal because it is
  582. ** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a
  583. ** boundary. ('j + 1' cannot be a present integer key because it is
  584. ** not a valid integer in Lua.)
  585. */
  586. static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
  587. lua_Unsigned i;
  588. if (j == 0) j++; /* the caller ensures 'j + 1' is present */
  589. do {
  590. i = j; /* 'i' is a present index */
  591. if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
  592. j *= 2;
  593. else {
  594. j = LUA_MAXINTEGER;
  595. if (ttisnil(luaH_getint(t, j))) /* t[j] == nil? */
  596. break; /* 'j' now is an absent index */
  597. else /* weird case */
  598. return j; /* well, max integer is a boundary... */
  599. }
  600. } while (!ttisnil(luaH_getint(t, j))); /* repeat until t[j] == nil */
  601. /* i < j && t[i] !≃ nil && t[j] == nil */
  602. while (j - i > 1u) { /* do a binary search between them */
  603. lua_Unsigned m = (i + j) / 2;
  604. if (ttisnil(luaH_getint(t, m))) j = m;
  605. else i = m;
  606. }
  607. return i;
  608. }
  609. /*
  610. ** Try to find a boundary in table 't'. (A 'boundary' is an integer index
  611. ** such that t[i] is non-nil and t[i+1] is nil, plus 0 if t[1] is nil
  612. ** and 'maxinteger' if t[maxinteger] is not nil.)
  613. ** First, try the array part: if there is an array part and its last
  614. ** element is nil, there must be a boundary there; a binary search
  615. ** finds that boundary. Otherwise, if the hash part is empty or does not
  616. ** contain 'j + 1', 'j' is a boundary. Othersize, call 'hash_search'
  617. ** to find a boundary in the hash part.
  618. */
  619. lua_Unsigned luaH_getn (Table *t) {
  620. unsigned int j = t->sizearray;
  621. if (j > 0 && ttisnil(&t->array[j - 1])) {
  622. unsigned int i = 0;
  623. while (j - i > 1u) { /* binary search */
  624. unsigned int m = (i + j) / 2;
  625. if (ttisnil(&t->array[m - 1])) j = m;
  626. else i = m;
  627. }
  628. return i;
  629. }
  630. else { /* 'j' is zero or present in table */
  631. if (isdummy(t) || ttisnil(luaH_getint(t, l_castU2S(j + 1))))
  632. return j; /* 'j + 1' is absent... */
  633. else /* 'j + 1' is also present */
  634. return hash_search(t, j);
  635. }
  636. }
  637. #if defined(LUA_DEBUG)
  638. Node *luaH_mainposition (const Table *t, const TValue *key) {
  639. return mainpositionTV(t, key);
  640. }
  641. int luaH_isdummy (const Table *t) { return isdummy(t); }
  642. #endif