ltable.c 16 KB

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