ltable.c 17 KB

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