589 line
16 KiB

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