ltable.c 17 KB

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