ltable.c 16 KB

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