ltable.c 16 KB

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