ltable.c 16 KB

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