ltable.c 23 KB

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