ltable.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. /*
  2. ** $Id: ltable.c,v 2.32.1.2 2007/12/28 15:32:23 roberto Exp $
  3. ** Lua tables (hash)
  4. ** See Copyright Notice in lua.h
  5. */
  6. /*
  7. ** Implementation of tables (aka arrays, objects, or hash tables).
  8. ** Tables keep its elements in two parts: an array part and a hash part.
  9. ** Non-negative integer keys are all candidates to be kept in the array
  10. ** part. The actual size of the array is the largest `n' such that at
  11. ** least half the slots between 0 and n are in use.
  12. ** Hash uses a mix of chained scatter table with Brent's variation.
  13. ** A main invariant of these tables is that, if an element is not
  14. ** in its main position (i.e. the `original' position that its hash gives
  15. ** to it), then the colliding element is in its own main position.
  16. ** Hence even when the load factor reaches 100%, performance remains good.
  17. */
  18. #include <math.h>
  19. #include <string.h>
  20. #define ltable_c
  21. #define LUA_CORE
  22. #include "lua.h"
  23. #include "ldebug.h"
  24. #include "ldo.h"
  25. #include "lgc.h"
  26. #include "lmem.h"
  27. #include "lobject.h"
  28. #include "lstate.h"
  29. #include "ltable.h"
  30. #include "lrotable.h"
  31. /*
  32. ** max size of array part is 2^MAXBITS
  33. */
  34. #if LUAI_BITSINT > 26
  35. #define MAXBITS 26
  36. #else
  37. #define MAXBITS (LUAI_BITSINT-2)
  38. #endif
  39. #define MAXASIZE (1 << MAXBITS)
  40. #define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))
  41. #define hashstr(t,str) hashpow2(t, (str)->tsv.hash)
  42. #define hashboolean(t,p) hashpow2(t, p)
  43. /*
  44. ** for some types, it is better to avoid modulus by power of 2, as
  45. ** they tend to have many 2 factors.
  46. */
  47. #define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))
  48. #define hashpointer(t,p) hashmod(t, IntPoint(p))
  49. /*
  50. ** number of ints inside a lua_Number
  51. */
  52. #define numints cast_int(sizeof(lua_Number)/sizeof(int))
  53. #define dummynode (&dummynode_)
  54. static const Node dummynode_ = {
  55. {LUA_TVALUE_NIL}, /* value */
  56. {LUA_TKEY_NIL} /* key */
  57. };
  58. /*
  59. ** hash for lua_Numbers
  60. */
  61. static Node *hashnum (const Table *t, lua_Number n) {
  62. unsigned int a[numints];
  63. int i;
  64. if (luai_numeq(n, 0)) /* avoid problems with -0 */
  65. return gnode(t, 0);
  66. memcpy(a, &n, sizeof(a));
  67. for (i = 1; i < numints; i++) a[0] += a[i];
  68. return hashmod(t, a[0]);
  69. }
  70. /*
  71. ** returns the `main' position of an element in a table (that is, the index
  72. ** of its hash value)
  73. */
  74. static Node *mainposition (const Table *t, const TValue *key) {
  75. switch (ttype(key)) {
  76. case LUA_TNUMBER:
  77. return hashnum(t, nvalue(key));
  78. case LUA_TSTRING:
  79. return hashstr(t, rawtsvalue(key));
  80. case LUA_TBOOLEAN:
  81. return hashboolean(t, bvalue(key));
  82. case LUA_TLIGHTUSERDATA:
  83. case LUA_TROTABLE:
  84. case LUA_TLIGHTFUNCTION:
  85. return hashpointer(t, pvalue(key));
  86. default:
  87. return hashpointer(t, gcvalue(key));
  88. }
  89. }
  90. /*
  91. ** returns the index for `key' if `key' is an appropriate key to live in
  92. ** the array part of the table, -1 otherwise.
  93. */
  94. static int arrayindex (const TValue *key) {
  95. if (ttisnumber(key)) {
  96. lua_Number n = nvalue(key);
  97. int k;
  98. lua_number2int(k, n);
  99. if (luai_numeq(cast_num(k), n))
  100. return k;
  101. }
  102. return -1; /* `key' did not match some condition */
  103. }
  104. /*
  105. ** returns the index of a `key' for table traversals. First goes all
  106. ** elements in the array part, then elements in the hash part. The
  107. ** beginning of a traversal is signalled by -1.
  108. */
  109. static int findindex (lua_State *L, Table *t, StkId key) {
  110. int i;
  111. if (ttisnil(key)) return -1; /* first iteration */
  112. i = arrayindex(key);
  113. if (0 < i && i <= t->sizearray) /* is `key' inside array part? */
  114. return i-1; /* yes; that's the index (corrected to C) */
  115. else {
  116. Node *n = mainposition(t, key);
  117. do { /* check whether `key' is somewhere in the chain */
  118. /* key may be dead already, but it is ok to use it in `next' */
  119. if (luaO_rawequalObj(key2tval(n), key) ||
  120. (ttype(gkey(n)) == LUA_TDEADKEY && iscollectable(key) &&
  121. gcvalue(gkey(n)) == gcvalue(key))) {
  122. i = cast_int(n - gnode(t, 0)); /* key index in hash table */
  123. /* hash elements are numbered after array ones */
  124. return i + t->sizearray;
  125. }
  126. else n = gnext(n);
  127. } while (n);
  128. luaG_runerror(L, "invalid key to " LUA_QL("next")); /* key not found */
  129. return 0; /* to avoid warnings */
  130. }
  131. }
  132. int luaH_next (lua_State *L, Table *t, StkId key) {
  133. int i = findindex(L, t, key); /* find original element */
  134. for (i++; i < t->sizearray; i++) { /* try first array part */
  135. if (!ttisnil(&t->array[i])) { /* a non-nil value? */
  136. setnvalue(key, cast_num(i+1));
  137. setobj2s(L, key+1, &t->array[i]);
  138. return 1;
  139. }
  140. }
  141. for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */
  142. if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */
  143. setobj2s(L, key, key2tval(gnode(t, i)));
  144. setobj2s(L, key+1, gval(gnode(t, i)));
  145. return 1;
  146. }
  147. }
  148. return 0; /* no more elements */
  149. }
  150. int luaH_next_ro (lua_State *L, void *t, StkId key) {
  151. luaR_next(L, t, key, key+1);
  152. return ttisnil(key) ? 0 : 1;
  153. }
  154. /*
  155. ** {=============================================================
  156. ** Rehash
  157. ** ==============================================================
  158. */
  159. static int computesizes (int nums[], int *narray) {
  160. int i;
  161. int twotoi; /* 2^i */
  162. int a = 0; /* number of elements smaller than 2^i */
  163. int na = 0; /* number of elements to go to array part */
  164. int n = 0; /* optimal size for array part */
  165. for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) {
  166. if (nums[i] > 0) {
  167. a += nums[i];
  168. if (a > twotoi/2) { /* more than half elements present? */
  169. n = twotoi; /* optimal size (till now) */
  170. na = a; /* all elements smaller than n will go to array part */
  171. }
  172. }
  173. if (a == *narray) break; /* all elements already counted */
  174. }
  175. *narray = n;
  176. lua_assert(*narray/2 <= na && na <= *narray);
  177. return na;
  178. }
  179. static int countint (const TValue *key, int *nums) {
  180. int k = arrayindex(key);
  181. if (0 < k && k <= MAXASIZE) { /* is `key' an appropriate array index? */
  182. nums[ceillog2(k)]++; /* count as such */
  183. return 1;
  184. }
  185. else
  186. return 0;
  187. }
  188. static int numusearray (const Table *t, int *nums) {
  189. int lg;
  190. int ttlg; /* 2^lg */
  191. int ause = 0; /* summation of `nums' */
  192. int i = 1; /* count to traverse all array keys */
  193. for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) { /* for each slice */
  194. int lc = 0; /* counter */
  195. int lim = ttlg;
  196. if (lim > t->sizearray) {
  197. lim = t->sizearray; /* adjust upper limit */
  198. if (i > lim)
  199. break; /* no more elements to count */
  200. }
  201. /* count elements in range (2^(lg-1), 2^lg] */
  202. for (; i <= lim; i++) {
  203. if (!ttisnil(&t->array[i-1]))
  204. lc++;
  205. }
  206. nums[lg] += lc;
  207. ause += lc;
  208. }
  209. return ause;
  210. }
  211. static int numusehash (const Table *t, int *nums, int *pnasize) {
  212. int totaluse = 0; /* total number of elements */
  213. int ause = 0; /* summation of `nums' */
  214. int i = sizenode(t);
  215. while (i--) {
  216. Node *n = &t->node[i];
  217. if (!ttisnil(gval(n))) {
  218. ause += countint(key2tval(n), nums);
  219. totaluse++;
  220. }
  221. }
  222. *pnasize += ause;
  223. return totaluse;
  224. }
  225. static void setarrayvector (lua_State *L, Table *t, int size) {
  226. int i;
  227. luaM_reallocvector(L, t->array, t->sizearray, size, TValue);
  228. for (i=t->sizearray; i<size; i++)
  229. setnilvalue(&t->array[i]);
  230. t->sizearray = size;
  231. }
  232. static Node *getfreepos (Table *t) {
  233. while (t->lastfree-- > t->node) {
  234. if (ttisnil(gkey(t->lastfree)))
  235. return t->lastfree;
  236. }
  237. return NULL; /* could not find a free place */
  238. }
  239. static void resizenodevector (lua_State *L, Table *t, int oldsize, int newsize) {
  240. int lsize;
  241. if (newsize == 0) { /* no elements to hash part? */
  242. t->node = cast(Node *, dummynode); /* use common `dummynode' */
  243. lsize = 0;
  244. }
  245. else {
  246. Node *node = t->node;
  247. int i;
  248. lsize = ceillog2(newsize);
  249. if (lsize > MAXBITS)
  250. luaG_runerror(L, "table overflow");
  251. newsize = twoto(lsize);
  252. if (node == dummynode) {
  253. oldsize = 0;
  254. node = NULL; /* don't try to realloc `dummynode' pointer. */
  255. }
  256. luaM_reallocvector(L, node, oldsize, newsize, Node);
  257. t->node = node;
  258. for (i=oldsize; i<newsize; i++) {
  259. Node *n = gnode(t, i);
  260. gnext(n) = NULL;
  261. setnilvalue(gkey(n));
  262. setnilvalue(gval(n));
  263. }
  264. }
  265. t->lsizenode = cast_byte(lsize);
  266. t->lastfree = gnode(t, newsize); /* reset lastfree to end of table. */
  267. }
  268. static Node *find_prev_node(Node *mp, Node *next) {
  269. Node *prev = mp;
  270. while (prev != NULL && gnext(prev) != next) prev = gnext(prev);
  271. return prev;
  272. }
  273. /*
  274. ** move a node from it's old position to it's new position during a rehash;
  275. ** first, check whether the moving node's main position is free. If not, check whether
  276. ** colliding node is in its main position or not: if it is not, move colliding
  277. ** node to an empty place and put moving node in its main position; otherwise
  278. ** (colliding node is in its main position), moving node goes to an empty position.
  279. */
  280. static int move_node (lua_State *L, Table *t, Node *node) {
  281. Node *mp = mainposition(t, key2tval(node));
  282. /* if node is in it's main position, don't need to move node. */
  283. if (mp == node) return 1;
  284. /* if node is in it's main position's chain, don't need to move node. */
  285. if (find_prev_node(mp, node) != NULL) return 1;
  286. /* is main position is free? */
  287. if (!ttisnil(gval(mp)) || mp == dummynode) {
  288. /* no; move main position node if it is out of its main position */
  289. Node *othermp;
  290. othermp = mainposition(t, key2tval(mp));
  291. if (othermp != mp) { /* is colliding node out of its main position? */
  292. /* yes; swap colliding node with the node that is being moved. */
  293. Node *prev;
  294. Node tmp;
  295. tmp = *node;
  296. prev = find_prev_node(othermp, mp); /* find previous */
  297. if (prev != NULL) gnext(prev) = node; /* redo the chain with `n' in place of `mp' */
  298. *node = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  299. *mp = tmp;
  300. return (prev != NULL) ? 1 : 0; /* is colliding node part of its main position chain? */
  301. }
  302. else { /* colliding node is in its own main position */
  303. /* add node to main position's chain. */
  304. gnext(node) = gnext(mp); /* chain new position */
  305. gnext(mp) = node;
  306. }
  307. }
  308. else { /* main position is free, move node */
  309. *mp = *node;
  310. gnext(node) = NULL;
  311. setnilvalue(gkey(node));
  312. setnilvalue(gval(node));
  313. }
  314. return 1;
  315. }
  316. static int move_number (lua_State *L, Table *t, Node *node) {
  317. int key;
  318. lua_Number n = nvalue(key2tval(node));
  319. lua_number2int(key, n);
  320. if (luai_numeq(cast_num(key), nvalue(key2tval(node)))) {/* index is int? */
  321. /* (1 <= key && key <= t->sizearray) */
  322. if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray)) {
  323. setobjt2t(L, &t->array[key-1], gval(node));
  324. setnilvalue(gkey(node));
  325. setnilvalue(gval(node));
  326. return 1;
  327. }
  328. }
  329. return 0;
  330. }
  331. static void resize_hashpart (lua_State *L, Table *t, int nhsize) {
  332. int i;
  333. int lsize=0;
  334. int oldhsize = (t->node != dummynode) ? twoto(t->lsizenode) : 0;
  335. if (nhsize > 0) { /* round new hashpart size up to next power of two. */
  336. lsize=ceillog2(nhsize);
  337. if (lsize > MAXBITS)
  338. luaG_runerror(L, "table overflow");
  339. }
  340. nhsize = twoto(lsize);
  341. /* grow hash part to new size. */
  342. if (oldhsize < nhsize)
  343. resizenodevector(L, t, oldhsize, nhsize);
  344. else { /* hash part might be shrinking */
  345. if (nhsize > 0) {
  346. t->lsizenode = cast_byte(lsize);
  347. t->lastfree = gnode(t, nhsize); /* reset lastfree back to end of table. */
  348. }
  349. else { /* new hashpart size is zero. */
  350. resizenodevector(L, t, oldhsize, nhsize);
  351. return;
  352. }
  353. }
  354. /* break old chains, try moving int keys to array part and compact keys into new hashpart */
  355. for (i = 0; i < oldhsize; i++) {
  356. Node *old = gnode(t, i);
  357. gnext(old) = NULL;
  358. if (ttisnil(gval(old))) { /* clear nodes with nil values. */
  359. setnilvalue(gkey(old));
  360. continue;
  361. }
  362. if (ttisnumber(key2tval(old))) { /* try moving the int keys into array part. */
  363. if(move_number(L, t, old))
  364. continue;
  365. }
  366. if (i >= nhsize) { /* move all valid keys to indices < nhsize. */
  367. Node *n = getfreepos(t); /* get a free place */
  368. lua_assert(n != dummynode && n != NULL);
  369. *n = *old;
  370. }
  371. }
  372. /* shrink hash part */
  373. if (oldhsize > nhsize)
  374. resizenodevector(L, t, oldhsize, nhsize);
  375. /* move nodes to their new mainposition and re-create node chains */
  376. for (i = 0; i < nhsize; i++) {
  377. Node *curr = gnode(t, i);
  378. if (!ttisnil(gval(curr)))
  379. while (move_node(L, t, curr) == 0);
  380. }
  381. }
  382. static void resize (lua_State *L, Table *t, int nasize, int nhsize) {
  383. int i;
  384. int oldasize = t->sizearray;
  385. if (nasize > oldasize) /* array part must grow? */
  386. setarrayvector(L, t, nasize);
  387. resize_hashpart(L, t, nhsize);
  388. if (nasize < oldasize) { /* array part must shrink? */
  389. t->sizearray = nasize;
  390. /* re-insert elements from vanishing slice */
  391. for (i=nasize; i<oldasize; i++) {
  392. if (!ttisnil(&t->array[i]))
  393. setobjt2t(L, luaH_setnum(L, t, i+1), &t->array[i]);
  394. }
  395. /* shrink array */
  396. luaM_reallocvector(L, t->array, oldasize, nasize, TValue);
  397. }
  398. }
  399. void luaH_resizearray (lua_State *L, Table *t, int nasize) {
  400. int nsize = (t->node == dummynode) ? 0 : sizenode(t);
  401. resize(L, t, nasize, nsize);
  402. }
  403. static void rehash (lua_State *L, Table *t, const TValue *ek) {
  404. int nasize, na;
  405. int nums[MAXBITS+1]; /* nums[i] = number of keys between 2^(i-1) and 2^i */
  406. int i;
  407. int totaluse;
  408. for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */
  409. nasize = numusearray(t, nums); /* count keys in array part */
  410. totaluse = nasize; /* all those keys are integer keys */
  411. totaluse += numusehash(t, nums, &nasize); /* count keys in hash part */
  412. /* count extra key */
  413. nasize += countint(ek, nums);
  414. totaluse++;
  415. /* compute new size for array part */
  416. na = computesizes(nums, &nasize);
  417. /* resize the table to new computed sizes */
  418. resize(L, t, nasize, totaluse - na);
  419. }
  420. /*
  421. ** }=============================================================
  422. */
  423. Table *luaH_new (lua_State *L, int narray, int nhash) {
  424. Table *t = luaM_new(L, Table);
  425. luaC_link(L, obj2gco(t), LUA_TTABLE);
  426. sethvalue2s(L, L->top, t); /* put table on stack */
  427. incr_top(L);
  428. t->metatable = NULL;
  429. t->flags = cast_byte(~0);
  430. /* temporary values (kept only if some malloc fails) */
  431. t->array = NULL;
  432. t->sizearray = 0;
  433. t->lsizenode = 0;
  434. t->node = cast(Node *, dummynode);
  435. setarrayvector(L, t, narray);
  436. resizenodevector(L, t, 0, nhash);
  437. L->top--; /* remove table from stack */
  438. return t;
  439. }
  440. void luaH_free (lua_State *L, Table *t) {
  441. if (t->node != dummynode)
  442. luaM_freearray(L, t->node, sizenode(t), Node);
  443. luaM_freearray(L, t->array, t->sizearray, TValue);
  444. luaM_free(L, t);
  445. }
  446. /*
  447. ** inserts a new key into a hash table; first, check whether key's main
  448. ** position is free. If not, check whether colliding node is in its main
  449. ** position or not: if it is not, move colliding node to an empty place and
  450. ** put new key in its main position; otherwise (colliding node is in its main
  451. ** position), new key goes to an empty position.
  452. */
  453. static TValue *newkey (lua_State *L, Table *t, const TValue *key) {
  454. Node *mp = mainposition(t, key);
  455. if (!ttisnil(gval(mp)) || mp == dummynode) {
  456. Node *othern;
  457. Node *n = getfreepos(t); /* get a free place */
  458. if (n == NULL) { /* cannot find a free place? */
  459. rehash(L, t, key); /* grow table */
  460. return luaH_set(L, t, key); /* re-insert key into grown table */
  461. }
  462. lua_assert(n != dummynode);
  463. othern = mainposition(t, key2tval(mp));
  464. if (othern != mp) { /* is colliding node out of its main position? */
  465. /* yes; move colliding node into free position */
  466. while (gnext(othern) != mp) othern = gnext(othern); /* find previous */
  467. gnext(othern) = n; /* redo the chain with `n' in place of `mp' */
  468. *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  469. gnext(mp) = NULL; /* now `mp' is free */
  470. setnilvalue(gval(mp));
  471. }
  472. else { /* colliding node is in its own main position */
  473. /* new node will go into free position */
  474. gnext(n) = gnext(mp); /* chain new position */
  475. gnext(mp) = n;
  476. mp = n;
  477. }
  478. }
  479. setobj2t(L, gkey(mp), key);
  480. luaC_barriert(L, t, key);
  481. lua_assert(ttisnil(gval(mp)));
  482. return gval(mp);
  483. }
  484. /*
  485. ** search function for integers
  486. */
  487. const TValue *luaH_getnum (Table *t, int key) {
  488. /* (1 <= key && key <= t->sizearray) */
  489. if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray))
  490. return &t->array[key-1];
  491. else {
  492. lua_Number nk = cast_num(key);
  493. Node *n = hashnum(t, nk);
  494. do { /* check whether `key' is somewhere in the chain */
  495. if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk))
  496. return gval(n); /* that's it */
  497. else n = gnext(n);
  498. } while (n);
  499. return luaO_nilobject;
  500. }
  501. }
  502. /* same thing for rotables */
  503. const TValue *luaH_getnum_ro (void *t, int key) {
  504. const TValue *res = luaR_findentry(t, NULL, key, NULL);
  505. return res ? res : luaO_nilobject;
  506. }
  507. /*
  508. ** search function for strings
  509. */
  510. const TValue *luaH_getstr (Table *t, TString *key) {
  511. Node *n = hashstr(t, key);
  512. do { /* check whether `key' is somewhere in the chain */
  513. if (ttisstring(gkey(n)) && rawtsvalue(gkey(n)) == key)
  514. return gval(n); /* that's it */
  515. else n = gnext(n);
  516. } while (n);
  517. return luaO_nilobject;
  518. }
  519. /* same thing for rotables */
  520. const TValue *luaH_getstr_ro (void *t, TString *key) {
  521. char keyname[LUA_MAX_ROTABLE_NAME + 1];
  522. const TValue *res;
  523. if (!t)
  524. return luaO_nilobject;
  525. luaR_getcstr(keyname, key, LUA_MAX_ROTABLE_NAME);
  526. res = luaR_findentry(t, keyname, 0, NULL);
  527. return res ? res : luaO_nilobject;
  528. }
  529. /*
  530. ** main search function
  531. */
  532. const TValue *luaH_get (Table *t, const TValue *key) {
  533. switch (ttype(key)) {
  534. case LUA_TNIL: return luaO_nilobject;
  535. case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key));
  536. case LUA_TNUMBER: {
  537. int k;
  538. lua_Number n = nvalue(key);
  539. lua_number2int(k, n);
  540. if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */
  541. return luaH_getnum(t, k); /* use specialized version */
  542. /* else go through */
  543. }
  544. default: {
  545. Node *n = mainposition(t, key);
  546. do { /* check whether `key' is somewhere in the chain */
  547. if (luaO_rawequalObj(key2tval(n), key))
  548. return gval(n); /* that's it */
  549. else n = gnext(n);
  550. } while (n);
  551. return luaO_nilobject;
  552. }
  553. }
  554. }
  555. /* same thing for rotables */
  556. const TValue *luaH_get_ro (void *t, const TValue *key) {
  557. switch (ttype(key)) {
  558. case LUA_TNIL: return luaO_nilobject;
  559. case LUA_TSTRING: return luaH_getstr_ro(t, rawtsvalue(key));
  560. case LUA_TNUMBER: {
  561. int k;
  562. lua_Number n = nvalue(key);
  563. lua_number2int(k, n);
  564. if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */
  565. return luaH_getnum_ro(t, k); /* use specialized version */
  566. /* else go through */
  567. }
  568. default: {
  569. return luaO_nilobject;
  570. }
  571. }
  572. }
  573. TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
  574. const TValue *p = luaH_get(t, key);
  575. t->flags = 0;
  576. if (p != luaO_nilobject)
  577. return cast(TValue *, p);
  578. else {
  579. if (ttisnil(key)) luaG_runerror(L, "table index is nil");
  580. else if (ttisnumber(key) && luai_numisnan(nvalue(key)))
  581. luaG_runerror(L, "table index is NaN");
  582. return newkey(L, t, key);
  583. }
  584. }
  585. TValue *luaH_setnum (lua_State *L, Table *t, int key) {
  586. const TValue *p = luaH_getnum(t, key);
  587. if (p != luaO_nilobject)
  588. return cast(TValue *, p);
  589. else {
  590. TValue k;
  591. setnvalue(&k, cast_num(key));
  592. return newkey(L, t, &k);
  593. }
  594. }
  595. TValue *luaH_setstr (lua_State *L, Table *t, TString *key) {
  596. const TValue *p = luaH_getstr(t, key);
  597. if (p != luaO_nilobject)
  598. return cast(TValue *, p);
  599. else {
  600. TValue k;
  601. setsvalue(L, &k, key);
  602. return newkey(L, t, &k);
  603. }
  604. }
  605. static int unbound_search (Table *t, unsigned int j) {
  606. unsigned int i = j; /* i is zero or a present index */
  607. j++;
  608. /* find `i' and `j' such that i is present and j is not */
  609. while (!ttisnil(luaH_getnum(t, j))) {
  610. i = j;
  611. j *= 2;
  612. if (j > cast(unsigned int, MAX_INT)) { /* overflow? */
  613. /* table was built with bad purposes: resort to linear search */
  614. i = 1;
  615. while (!ttisnil(luaH_getnum(t, i))) i++;
  616. return i - 1;
  617. }
  618. }
  619. /* now do a binary search between them */
  620. while (j - i > 1) {
  621. unsigned int m = (i+j)/2;
  622. if (ttisnil(luaH_getnum(t, m))) j = m;
  623. else i = m;
  624. }
  625. return i;
  626. }
  627. /*
  628. ** Try to find a boundary in table `t'. A `boundary' is an integer index
  629. ** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
  630. */
  631. int luaH_getn (Table *t) {
  632. unsigned int j = t->sizearray;
  633. if (j > 0 && ttisnil(&t->array[j - 1])) {
  634. /* there is a boundary in the array part: (binary) search for it */
  635. unsigned int i = 0;
  636. while (j - i > 1) {
  637. unsigned int m = (i+j)/2;
  638. if (ttisnil(&t->array[m - 1])) j = m;
  639. else i = m;
  640. }
  641. return i;
  642. }
  643. /* else must find a boundary in hash part */
  644. else if (t->node == dummynode) /* hash part is empty? */
  645. return j; /* that is easy... */
  646. else return unbound_search(t, j);
  647. }
  648. /* same thing for rotables */
  649. int luaH_getn_ro (void *t) {
  650. int i = 1, len=0;
  651. while(luaR_findentry(t, NULL, i ++, NULL))
  652. len ++;
  653. return len;
  654. }
  655. #if defined(LUA_DEBUG)
  656. Node *luaH_mainposition (const Table *t, const TValue *key) {
  657. return mainposition(t, key);
  658. }
  659. int luaH_isdummy (Node *n) { return n == dummynode; }
  660. #endif