ltable.c 16 KB

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