ltable.c 16 KB

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