ltable.c 17 KB

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