ltable.c 21 KB

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