ltable.c 16 KB

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