ltable.c 16 KB

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