ltable.c 21 KB

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