ltable.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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. #if 0
  19. #include <math.h>
  20. #include <string.h>
  21. #endif
  22. #define ltable_c
  23. #define LUA_CORE
  24. #include "lua.h"
  25. #include "ldebug.h"
  26. #include "ldo.h"
  27. #include "lgc.h"
  28. #include "lmem.h"
  29. #include "lobject.h"
  30. #include "lstate.h"
  31. #include "ltable.h"
  32. /*
  33. ** max size of array part is 2^MAXBITS
  34. */
  35. #if LUAI_BITSINT > 26
  36. #define MAXBITS 26
  37. #else
  38. #define MAXBITS (LUAI_BITSINT-2)
  39. #endif
  40. #define MAXASIZE (1 << MAXBITS)
  41. #define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))
  42. #define hashstr(t,str) hashpow2(t, (str)->tsv.hash)
  43. #define hashboolean(t,p) hashpow2(t, p)
  44. /*
  45. ** for some types, it is better to avoid modulus by power of 2, as
  46. ** they tend to have many 2 factors.
  47. */
  48. #define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))
  49. #define hashpointer(t,p) hashmod(t, IntPoint(p))
  50. /*
  51. ** number of ints inside a lua_Number
  52. */
  53. #define numints cast_int(sizeof(lua_Number)/sizeof(int))
  54. #define dummynode (&dummynode_)
  55. static const Node dummynode_ = {
  56. {{NULL}, LUA_TNIL}, /* value */
  57. {{{NULL}, LUA_TNIL, NULL}} /* key */
  58. };
  59. /*
  60. ** hash for lua_Numbers
  61. */
  62. static Node *hashnum (const Table *t, lua_Number n) {
  63. unsigned int a[numints];
  64. int i;
  65. if (luai_numeq(n, 0)) /* avoid problems with -0 */
  66. return gnode(t, 0);
  67. memcpy(a, &n, sizeof(a));
  68. for (i = 1; i < numints; i++) a[0] += a[i];
  69. return hashmod(t, a[0]);
  70. }
  71. /*
  72. ** returns the `main' position of an element in a table (that is, the index
  73. ** of its hash value)
  74. */
  75. static Node *mainposition (const Table *t, const TValue *key) {
  76. switch (ttype(key)) {
  77. case LUA_TNUMBER:
  78. return hashnum(t, nvalue(key));
  79. case LUA_TSTRING:
  80. return hashstr(t, rawtsvalue(key));
  81. case LUA_TBOOLEAN:
  82. return hashboolean(t, bvalue(key));
  83. case LUA_TLIGHTUSERDATA:
  84. return hashpointer(t, pvalue(key));
  85. default:
  86. return hashpointer(t, gcvalue(key));
  87. }
  88. }
  89. /*
  90. ** returns the index for `key' if `key' is an appropriate key to live in
  91. ** the array part of the table, -1 otherwise.
  92. */
  93. static int arrayindex (const TValue *key) {
  94. if (ttisnumber(key)) {
  95. lua_Number n = nvalue(key);
  96. int k;
  97. lua_number2int(k, n);
  98. if (luai_numeq(cast_num(k), n))
  99. return k;
  100. }
  101. return -1; /* `key' did not match some condition */
  102. }
  103. /*
  104. ** returns the index of a `key' for table traversals. First goes all
  105. ** elements in the array part, then elements in the hash part. The
  106. ** beginning of a traversal is signalled by -1.
  107. */
  108. static int findindex (lua_State *L, Table *t, StkId key) {
  109. int i;
  110. if (ttisnil(key)) return -1; /* first iteration */
  111. i = arrayindex(key);
  112. if (0 < i && i <= t->sizearray) /* is `key' inside array part? */
  113. return i-1; /* yes; that's the index (corrected to C) */
  114. else {
  115. Node *n = mainposition(t, key);
  116. do { /* check whether `key' is somewhere in the chain */
  117. /* key may be dead already, but it is ok to use it in `next' */
  118. if (luaO_rawequalObj(key2tval(n), key) ||
  119. (ttype(gkey(n)) == LUA_TDEADKEY && iscollectable(key) &&
  120. gcvalue(gkey(n)) == gcvalue(key))) {
  121. i = cast_int(n - gnode(t, 0)); /* key index in hash table */
  122. /* hash elements are numbered after array ones */
  123. return i + t->sizearray;
  124. }
  125. else n = gnext(n);
  126. } while (n);
  127. luaG_runerror(L, "invalid key to " LUA_QL("next")); /* key not found */
  128. return 0; /* to avoid warnings */
  129. }
  130. }
  131. int luaH_next (lua_State *L, Table *t, StkId key) {
  132. int i = findindex(L, t, key); /* find original element */
  133. for (i++; i < t->sizearray; i++) { /* try first array part */
  134. if (!ttisnil(&t->array[i])) { /* a non-nil value? */
  135. setnvalue(key, cast_num(i+1));
  136. setobj2s(L, key+1, &t->array[i]);
  137. return 1;
  138. }
  139. }
  140. for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */
  141. if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */
  142. setobj2s(L, key, key2tval(gnode(t, i)));
  143. setobj2s(L, key+1, gval(gnode(t, i)));
  144. return 1;
  145. }
  146. }
  147. return 0; /* no more elements */
  148. }
  149. /*
  150. ** {=============================================================
  151. ** Rehash
  152. ** ==============================================================
  153. */
  154. static int computesizes (int nums[], int *narray) {
  155. int i;
  156. int twotoi; /* 2^i */
  157. int a = 0; /* number of elements smaller than 2^i */
  158. int na = 0; /* number of elements to go to array part */
  159. int n = 0; /* optimal size for array part */
  160. for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) {
  161. if (nums[i] > 0) {
  162. a += nums[i];
  163. if (a > twotoi/2) { /* more than half elements present? */
  164. n = twotoi; /* optimal size (till now) */
  165. na = a; /* all elements smaller than n will go to array part */
  166. }
  167. }
  168. if (a == *narray) break; /* all elements already counted */
  169. }
  170. *narray = n;
  171. lua_assert(*narray/2 <= na && na <= *narray);
  172. return na;
  173. }
  174. static int countint (const TValue *key, int *nums) {
  175. int k = arrayindex(key);
  176. if (0 < k && k <= MAXASIZE) { /* is `key' an appropriate array index? */
  177. nums[ceillog2(k)]++; /* count as such */
  178. return 1;
  179. }
  180. else
  181. return 0;
  182. }
  183. static int numusearray (const Table *t, int *nums) {
  184. int lg;
  185. int ttlg; /* 2^lg */
  186. int ause = 0; /* summation of `nums' */
  187. int i = 1; /* count to traverse all array keys */
  188. for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) { /* for each slice */
  189. int lc = 0; /* counter */
  190. int lim = ttlg;
  191. if (lim > t->sizearray) {
  192. lim = t->sizearray; /* adjust upper limit */
  193. if (i > lim)
  194. break; /* no more elements to count */
  195. }
  196. /* count elements in range (2^(lg-1), 2^lg] */
  197. for (; i <= lim; i++) {
  198. if (!ttisnil(&t->array[i-1]))
  199. lc++;
  200. }
  201. nums[lg] += lc;
  202. ause += lc;
  203. }
  204. return ause;
  205. }
  206. static int numusehash (const Table *t, int *nums, int *pnasize) {
  207. int totaluse = 0; /* total number of elements */
  208. int ause = 0; /* summation of `nums' */
  209. int i = sizenode(t);
  210. while (i--) {
  211. Node *n = &t->node[i];
  212. if (!ttisnil(gval(n))) {
  213. ause += countint(key2tval(n), nums);
  214. totaluse++;
  215. }
  216. }
  217. *pnasize += ause;
  218. return totaluse;
  219. }
  220. static void setarrayvector (lua_State *L, Table *t, int size) {
  221. int i;
  222. luaM_reallocvector(L, t->array, t->sizearray, size, TValue);
  223. for (i=t->sizearray; i<size; i++)
  224. setnilvalue(&t->array[i]);
  225. t->sizearray = size;
  226. }
  227. static void setnodevector (lua_State *L, Table *t, int size) {
  228. int lsize;
  229. if (size == 0) { /* no elements to hash part? */
  230. t->node = cast(Node *, dummynode); /* use common `dummynode' */
  231. lsize = 0;
  232. }
  233. else {
  234. int i;
  235. lsize = ceillog2(size);
  236. if (lsize > MAXBITS)
  237. luaG_runerror(L, "table overflow");
  238. size = twoto(lsize);
  239. t->node = luaM_newvector(L, size, Node);
  240. for (i=0; i<size; i++) {
  241. Node *n = gnode(t, i);
  242. gnext(n) = NULL;
  243. setnilvalue(gkey(n));
  244. setnilvalue(gval(n));
  245. }
  246. }
  247. t->lsizenode = cast_byte(lsize);
  248. t->lastfree = gnode(t, size); /* all positions are free */
  249. }
  250. static void resize (lua_State *L, Table *t, int nasize, int nhsize) {
  251. int i;
  252. int oldasize = t->sizearray;
  253. int oldhsize = t->lsizenode;
  254. Node *nold = t->node; /* save old hash ... */
  255. if (nasize > oldasize) /* array part must grow? */
  256. setarrayvector(L, t, nasize);
  257. /* create new hash part with appropriate size */
  258. setnodevector(L, t, nhsize);
  259. if (nasize < oldasize) { /* array part must shrink? */
  260. t->sizearray = nasize;
  261. /* re-insert elements from vanishing slice */
  262. for (i=nasize; i<oldasize; i++) {
  263. if (!ttisnil(&t->array[i]))
  264. setobjt2t(L, luaH_setnum(L, t, i+1), &t->array[i]);
  265. }
  266. /* shrink array */
  267. luaM_reallocvector(L, t->array, oldasize, nasize, TValue);
  268. }
  269. /* re-insert elements from hash part */
  270. for (i = twoto(oldhsize) - 1; i >= 0; i--) {
  271. Node *old = nold+i;
  272. if (!ttisnil(gval(old)))
  273. setobjt2t(L, luaH_set(L, t, key2tval(old)), gval(old));
  274. }
  275. if (nold != dummynode)
  276. luaM_freearray(L, nold, twoto(oldhsize), Node); /* free old array */
  277. }
  278. void luaH_resizearray (lua_State *L, Table *t, int nasize) {
  279. int nsize = (t->node == dummynode) ? 0 : sizenode(t);
  280. resize(L, t, nasize, nsize);
  281. }
  282. static void rehash (lua_State *L, Table *t, const TValue *ek) {
  283. int nasize, na;
  284. int nums[MAXBITS+1]; /* nums[i] = number of keys between 2^(i-1) and 2^i */
  285. int i;
  286. int totaluse;
  287. for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */
  288. nasize = numusearray(t, nums); /* count keys in array part */
  289. totaluse = nasize; /* all those keys are integer keys */
  290. totaluse += numusehash(t, nums, &nasize); /* count keys in hash part */
  291. /* count extra key */
  292. nasize += countint(ek, nums);
  293. totaluse++;
  294. /* compute new size for array part */
  295. na = computesizes(nums, &nasize);
  296. /* resize the table to new computed sizes */
  297. resize(L, t, nasize, totaluse - na);
  298. }
  299. /*
  300. ** }=============================================================
  301. */
  302. Table *luaH_new (lua_State *L, int narray, int nhash) {
  303. Table *t = luaM_new(L, Table);
  304. luaC_link(L, obj2gco(t), LUA_TTABLE);
  305. t->metatable = NULL;
  306. t->flags = cast_byte(~0);
  307. /* temporary values (kept only if some malloc fails) */
  308. t->array = NULL;
  309. t->sizearray = 0;
  310. t->lsizenode = 0;
  311. t->node = cast(Node *, dummynode);
  312. setarrayvector(L, t, narray);
  313. setnodevector(L, t, nhash);
  314. return t;
  315. }
  316. void luaH_free (lua_State *L, Table *t) {
  317. if (t->node != dummynode)
  318. luaM_freearray(L, t->node, sizenode(t), Node);
  319. luaM_freearray(L, t->array, t->sizearray, TValue);
  320. luaM_free(L, t);
  321. }
  322. static Node *getfreepos (Table *t) {
  323. while (t->lastfree-- > t->node) {
  324. if (ttisnil(gkey(t->lastfree)))
  325. return t->lastfree;
  326. }
  327. return NULL; /* could not find a free place */
  328. }
  329. /*
  330. ** inserts a new key into a hash table; first, check whether key's main
  331. ** position is free. If not, check whether colliding node is in its main
  332. ** position or not: if it is not, move colliding node to an empty place and
  333. ** put new key in its main position; otherwise (colliding node is in its main
  334. ** position), new key goes to an empty position.
  335. */
  336. static TValue *newkey (lua_State *L, Table *t, const TValue *key) {
  337. Node *mp = mainposition(t, key);
  338. if (!ttisnil(gval(mp)) || mp == dummynode) {
  339. Node *othern;
  340. Node *n = getfreepos(t); /* get a free place */
  341. if (n == NULL) { /* cannot find a free place? */
  342. rehash(L, t, key); /* grow table */
  343. return luaH_set(L, t, key); /* re-insert key into grown table */
  344. }
  345. lua_assert(n != dummynode);
  346. othern = mainposition(t, key2tval(mp));
  347. if (othern != mp) { /* is colliding node out of its main position? */
  348. /* yes; move colliding node into free position */
  349. while (gnext(othern) != mp) othern = gnext(othern); /* find previous */
  350. gnext(othern) = n; /* redo the chain with `n' in place of `mp' */
  351. #if 0
  352. *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  353. #else
  354. memcpy (n, mp, sizeof (*n));
  355. #endif
  356. gnext(mp) = NULL; /* now `mp' is free */
  357. setnilvalue(gval(mp));
  358. }
  359. else { /* colliding node is in its own main position */
  360. /* new node will go into free position */
  361. gnext(n) = gnext(mp); /* chain new position */
  362. gnext(mp) = n;
  363. mp = n;
  364. }
  365. }
  366. gkey(mp)->value = key->value; gkey(mp)->tt = key->tt;
  367. luaC_barriert(L, t, key);
  368. lua_assert(ttisnil(gval(mp)));
  369. return gval(mp);
  370. }
  371. /*
  372. ** search function for integers
  373. */
  374. const TValue *luaH_getnum (Table *t, int key) {
  375. /* (1 <= key && key <= t->sizearray) */
  376. if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray))
  377. return &t->array[key-1];
  378. else {
  379. lua_Number nk = cast_num(key);
  380. Node *n = hashnum(t, nk);
  381. do { /* check whether `key' is somewhere in the chain */
  382. if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk))
  383. return gval(n); /* that's it */
  384. else n = gnext(n);
  385. } while (n);
  386. return luaO_nilobject;
  387. }
  388. }
  389. /*
  390. ** search function for strings
  391. */
  392. const TValue *luaH_getstr (Table *t, TString *key) {
  393. Node *n = hashstr(t, key);
  394. do { /* check whether `key' is somewhere in the chain */
  395. if (ttisstring(gkey(n)) && rawtsvalue(gkey(n)) == key)
  396. return gval(n); /* that's it */
  397. else n = gnext(n);
  398. } while (n);
  399. return luaO_nilobject;
  400. }
  401. /*
  402. ** main search function
  403. */
  404. const TValue *luaH_get (Table *t, const TValue *key) {
  405. switch (ttype(key)) {
  406. case LUA_TNIL: return luaO_nilobject;
  407. case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key));
  408. case LUA_TNUMBER: {
  409. int k;
  410. lua_Number n = nvalue(key);
  411. lua_number2int(k, n);
  412. if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */
  413. return luaH_getnum(t, k); /* use specialized version */
  414. /* else go through */
  415. }
  416. default: {
  417. Node *n = mainposition(t, key);
  418. do { /* check whether `key' is somewhere in the chain */
  419. if (luaO_rawequalObj(key2tval(n), key))
  420. return gval(n); /* that's it */
  421. else n = gnext(n);
  422. } while (n);
  423. return luaO_nilobject;
  424. }
  425. }
  426. }
  427. TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
  428. const TValue *p = luaH_get(t, key);
  429. t->flags = 0;
  430. if (p != luaO_nilobject)
  431. return cast(TValue *, p);
  432. else {
  433. if (ttisnil(key)) luaG_runerror(L, "table index is nil");
  434. else if (ttisnumber(key) && luai_numisnan(nvalue(key)))
  435. luaG_runerror(L, "table index is NaN");
  436. return newkey(L, t, key);
  437. }
  438. }
  439. TValue *luaH_setnum (lua_State *L, Table *t, int key) {
  440. const TValue *p = luaH_getnum(t, key);
  441. if (p != luaO_nilobject)
  442. return cast(TValue *, p);
  443. else {
  444. TValue k;
  445. setnvalue(&k, cast_num(key));
  446. return newkey(L, t, &k);
  447. }
  448. }
  449. TValue *luaH_setstr (lua_State *L, Table *t, TString *key) {
  450. const TValue *p = luaH_getstr(t, key);
  451. if (p != luaO_nilobject)
  452. return cast(TValue *, p);
  453. else {
  454. TValue k;
  455. setsvalue(L, &k, key);
  456. return newkey(L, t, &k);
  457. }
  458. }
  459. static int unbound_search (Table *t, unsigned int j) {
  460. unsigned int i = j; /* i is zero or a present index */
  461. j++;
  462. /* find `i' and `j' such that i is present and j is not */
  463. while (!ttisnil(luaH_getnum(t, j))) {
  464. i = j;
  465. j *= 2;
  466. if (j > cast(unsigned int, MAX_INT)) { /* overflow? */
  467. /* table was built with bad purposes: resort to linear search */
  468. i = 1;
  469. while (!ttisnil(luaH_getnum(t, i))) i++;
  470. return i - 1;
  471. }
  472. }
  473. /* now do a binary search between them */
  474. while (j - i > 1) {
  475. unsigned int m = (i+j)/2;
  476. if (ttisnil(luaH_getnum(t, m))) j = m;
  477. else i = m;
  478. }
  479. return i;
  480. }
  481. /*
  482. ** Try to find a boundary in table `t'. A `boundary' is an integer index
  483. ** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
  484. */
  485. int luaH_getn (Table *t) {
  486. unsigned int j = t->sizearray;
  487. if (j > 0 && ttisnil(&t->array[j - 1])) {
  488. /* there is a boundary in the array part: (binary) search for it */
  489. unsigned int i = 0;
  490. while (j - i > 1) {
  491. unsigned int m = (i+j)/2;
  492. if (ttisnil(&t->array[m - 1])) j = m;
  493. else i = m;
  494. }
  495. return i;
  496. }
  497. /* else must find a boundary in hash part */
  498. else if (t->node == dummynode) /* hash part is empty? */
  499. return j; /* that is easy... */
  500. else return unbound_search(t, j);
  501. }
  502. #if defined(LUA_DEBUG)
  503. Node *luaH_mainposition (const Table *t, const TValue *key) {
  504. return mainposition(t, key);
  505. }
  506. int luaH_isdummy (Node *n) { return n == dummynode; }
  507. #endif