ltable.c 17 KB

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