ltable.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. /*
  2. ** $Id: ltable.c 4116 2012-04-12 22:35:23Z olereinhardt $
  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/lua.h>
  23. #include <lua/ldebug.h>
  24. #include <lua/ldo.h>
  25. #include <lua/lgc.h>
  26. #include <lua/lmem.h>
  27. #include <lua/lobject.h>
  28. #include <lua/lstate.h>
  29. #include <lua/ltable.h>
  30. #ifndef NUTLUA_TABLELIB_NOT_IMPLEMENTED
  31. /*
  32. ** max size of array part is 2^MAXBITS
  33. */
  34. #if LUAI_BITSINT > 26
  35. #define MAXBITS 26
  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. static const Node dummynode_ = {
  55. {{NULL}, LUA_TNIL}, /* value */
  56. {{{NULL}, LUA_TNIL, NULL}} /* key */
  57. };
  58. /*
  59. ** hash for lua_Numbers
  60. */
  61. static Node *hashnum (const Table *t, lua_Number n) {
  62. unsigned int a[numints];
  63. int i;
  64. if (luai_numeq(n, 0)) /* avoid problems with -0 */
  65. return gnode(t, 0);
  66. memcpy(a, &n, sizeof(a));
  67. for (i = 1; i < numints; i++) a[0] += a[i];
  68. return hashmod(t, a[0]);
  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. case LUA_TROTABLE:
  84. case LUA_TLIGHTFUNCTION:
  85. return hashpointer(t, (int)pvalue(key));
  86. default:
  87. return hashpointer(t, (int)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 signalled 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(key2tval(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, key2tval(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[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(key2tval(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 = 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. static void 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_setnum(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, key2tval(old)), gval(old));
  275. }
  276. if (nold != dummynode)
  277. luaM_freearray(L, nold, twoto(oldhsize), Node); /* free old array */
  278. }
  279. void luaH_resizearray (lua_State *L, Table *t, int nasize) {
  280. int nsize = (t->node == dummynode) ? 0 : sizenode(t);
  281. 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. resize(L, t, nasize, totaluse - na);
  299. }
  300. /*
  301. ** }=============================================================
  302. */
  303. Table *luaH_new (lua_State *L, int narray, int nhash) {
  304. Table *t = luaM_new(L, Table);
  305. luaC_link(L, obj2gco(t), LUA_TTABLE);
  306. t->metatable = NULL;
  307. t->flags = cast_byte(~0);
  308. /* temporary values (kept only if some malloc fails) */
  309. t->array = NULL;
  310. t->sizearray = 0;
  311. t->lsizenode = 0;
  312. t->node = cast(Node *, dummynode);
  313. setarrayvector(L, t, narray);
  314. setnodevector(L, t, nhash);
  315. return t;
  316. }
  317. void luaH_free (lua_State *L, Table *t) {
  318. if (t->node != dummynode)
  319. luaM_freearray(L, t->node, sizenode(t), Node);
  320. luaM_freearray(L, t->array, t->sizearray, TValue);
  321. luaM_free(L, t);
  322. }
  323. static Node *getfreepos (Table *t) {
  324. while (t->lastfree-- > t->node) {
  325. if (ttisnil(gkey(t->lastfree)))
  326. return t->lastfree;
  327. }
  328. return NULL; /* could not find a free place */
  329. }
  330. /*
  331. ** inserts a new key into a hash table; first, check whether key's main
  332. ** position is free. If not, check whether colliding node is in its main
  333. ** position or not: if it is not, move colliding node to an empty place and
  334. ** put new key in its main position; otherwise (colliding node is in its main
  335. ** position), new key goes to an empty position.
  336. */
  337. static TValue *newkey (lua_State *L, Table *t, const TValue *key) {
  338. Node *mp = mainposition(t, key);
  339. if (!ttisnil(gval(mp)) || mp == dummynode) {
  340. Node *othern;
  341. Node *n = getfreepos(t); /* get a free place */
  342. if (n == NULL) { /* cannot find a free place? */
  343. rehash(L, t, key); /* grow table */
  344. return luaH_set(L, t, key); /* re-insert key into grown table */
  345. }
  346. lua_assert(n != dummynode);
  347. othern = mainposition(t, key2tval(mp));
  348. if (othern != mp) { /* is colliding node out of its main position? */
  349. /* yes; move colliding node into free position */
  350. while (gnext(othern) != mp) othern = gnext(othern); /* find previous */
  351. gnext(othern) = n; /* redo the chain with `n' in place of `mp' */
  352. *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  353. gnext(mp) = NULL; /* now `mp' is free */
  354. setnilvalue(gval(mp));
  355. }
  356. else { /* colliding node is in its own main position */
  357. /* new node will go into free position */
  358. gnext(n) = gnext(mp); /* chain new position */
  359. gnext(mp) = n;
  360. mp = n;
  361. }
  362. }
  363. gkey(mp)->value = key->value; gkey(mp)->tt = key->tt;
  364. luaC_barriert(L, t, key);
  365. lua_assert(ttisnil(gval(mp)));
  366. return gval(mp);
  367. }
  368. /*
  369. ** search function for integers
  370. */
  371. const TValue *luaH_getnum (Table *t, int key) {
  372. /* (1 <= key && key <= t->sizearray) */
  373. if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray))
  374. return &t->array[key-1];
  375. else {
  376. lua_Number nk = cast_num(key);
  377. Node *n = hashnum(t, nk);
  378. do { /* check whether `key' is somewhere in the chain */
  379. if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk))
  380. return gval(n); /* that's it */
  381. else n = gnext(n);
  382. } while (n);
  383. return luaO_nilobject;
  384. }
  385. }
  386. /*
  387. ** search function for strings
  388. */
  389. const TValue *luaH_getstr (Table *t, TString *key) {
  390. Node *n = hashstr(t, key);
  391. do { /* check whether `key' is somewhere in the chain */
  392. if (ttisstring(gkey(n)) && rawtsvalue(gkey(n)) == key)
  393. return gval(n); /* that's it */
  394. else n = gnext(n);
  395. } while (n);
  396. return luaO_nilobject;
  397. }
  398. /*
  399. ** main search function
  400. */
  401. const TValue *luaH_get (Table *t, const TValue *key) {
  402. switch (ttype(key)) {
  403. case LUA_TNIL: return luaO_nilobject;
  404. case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key));
  405. case LUA_TNUMBER: {
  406. int k;
  407. lua_Number n = nvalue(key);
  408. lua_number2int(k, n);
  409. if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */
  410. return luaH_getnum(t, k); /* use specialized version */
  411. /* else go through */
  412. }
  413. default: {
  414. Node *n = mainposition(t, key);
  415. do { /* check whether `key' is somewhere in the chain */
  416. if (luaO_rawequalObj(key2tval(n), key))
  417. return gval(n); /* that's it */
  418. else n = gnext(n);
  419. } while (n);
  420. return luaO_nilobject;
  421. }
  422. }
  423. }
  424. TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
  425. const TValue *p = luaH_get(t, key);
  426. t->flags = 0;
  427. if (p != luaO_nilobject)
  428. return cast(TValue *, p);
  429. else {
  430. if (ttisnil(key)) luaG_runerror(L, "table index is nil");
  431. else if (ttisnumber(key) && luai_numisnan(nvalue(key)))
  432. luaG_runerror(L, "table index is NaN");
  433. return newkey(L, t, key);
  434. }
  435. }
  436. TValue *luaH_setnum (lua_State *L, Table *t, int key) {
  437. const TValue *p = luaH_getnum(t, key);
  438. if (p != luaO_nilobject)
  439. return cast(TValue *, p);
  440. else {
  441. TValue k;
  442. setnvalue(&k, cast_num(key));
  443. return newkey(L, t, &k);
  444. }
  445. }
  446. TValue *luaH_setstr (lua_State *L, Table *t, TString *key) {
  447. const TValue *p = luaH_getstr(t, key);
  448. if (p != luaO_nilobject)
  449. return cast(TValue *, p);
  450. else {
  451. TValue k;
  452. setsvalue(L, &k, key);
  453. return newkey(L, t, &k);
  454. }
  455. }
  456. static int unbound_search (Table *t, unsigned int j) {
  457. unsigned int i = j; /* i is zero or a present index */
  458. j++;
  459. /* find `i' and `j' such that i is present and j is not */
  460. while (!ttisnil(luaH_getnum(t, j))) {
  461. i = j;
  462. j *= 2;
  463. if (j > cast(unsigned int, MAX_INT)) { /* overflow? */
  464. /* table was built with bad purposes: resort to linear search */
  465. i = 1;
  466. while (!ttisnil(luaH_getnum(t, i))) i++;
  467. return i - 1;
  468. }
  469. }
  470. /* now do a binary search between them */
  471. while (j - i > 1) {
  472. unsigned int m = (i+j)/2;
  473. if (ttisnil(luaH_getnum(t, m))) j = m;
  474. else i = m;
  475. }
  476. return i;
  477. }
  478. /*
  479. ** Try to find a boundary in table `t'. A `boundary' is an integer index
  480. ** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
  481. */
  482. int luaH_getn (Table *t) {
  483. unsigned int j = t->sizearray;
  484. if (j > 0 && ttisnil(&t->array[j - 1])) {
  485. /* there is a boundary in the array part: (binary) search for it */
  486. unsigned int i = 0;
  487. while (j - i > 1) {
  488. unsigned int m = (i+j)/2;
  489. if (ttisnil(&t->array[m - 1])) j = m;
  490. else i = m;
  491. }
  492. return i;
  493. }
  494. /* else must find a boundary in hash part */
  495. else if (t->node == dummynode) /* hash part is empty? */
  496. return j; /* that is easy... */
  497. else return unbound_search(t, j);
  498. }
  499. #if defined(LUA_DEBUG)
  500. Node *luaH_mainposition (const Table *t, const TValue *key) {
  501. return mainposition(t, key);
  502. }
  503. int luaH_isdummy (Node *n) { return n == dummynode; }
  504. #endif
  505. #endif // NUTLUA_TABLELIB_NOT_IMPLEMENTED