PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/branches/model-enhancements/Source_Files/Lua/ltable.c

#
C | 588 lines | 410 code | 87 blank | 91 comment | 109 complexity | 40f17bf9eb684a33708d260c3ba6fec7 MD5 | raw file
Possible License(s): LGPL-2.0, LGPL-2.1, BSD-3-Clause, GPL-3.0, LGPL-3.0, MPL-2.0-no-copyleft-exception, Zlib, GPL-2.0
  1. /*
  2. ** $Id: ltable.c 3049 2007-05-15 01:58:42Z ghs $
  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. n += 1; /* normalize number (avoid -0) */
  64. lua_assert(sizeof(a) <= sizeof(n));
  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 computesizes (int nums[], int *narray) {
  153. int i;
  154. int twotoi; /* 2^i */
  155. int a = 0; /* number of elements smaller than 2^i */
  156. int na = 0; /* number of elements to go to array part */
  157. int n = 0; /* optimal size for array part */
  158. for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) {
  159. if (nums[i] > 0) {
  160. a += nums[i];
  161. if (a > twotoi/2) { /* more than half elements present? */
  162. n = twotoi; /* optimal size (till now) */
  163. na = a; /* all elements smaller than n will go to array part */
  164. }
  165. }
  166. if (a == *narray) break; /* all elements already counted */
  167. }
  168. *narray = n;
  169. lua_assert(*narray/2 <= na && na <= *narray);
  170. return na;
  171. }
  172. static int countint (const TValue *key, int *nums) {
  173. int k = arrayindex(key);
  174. if (0 < k && k <= MAXASIZE) { /* is `key' an appropriate array index? */
  175. nums[ceillog2(k)]++; /* count as such */
  176. return 1;
  177. }
  178. else
  179. return 0;
  180. }
  181. static int numusearray (const Table *t, int *nums) {
  182. int lg;
  183. int ttlg; /* 2^lg */
  184. int ause = 0; /* summation of `nums' */
  185. int i = 1; /* count to traverse all array keys */
  186. for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) { /* for each slice */
  187. int lc = 0; /* counter */
  188. int lim = ttlg;
  189. if (lim > t->sizearray) {
  190. lim = t->sizearray; /* adjust upper limit */
  191. if (i > lim)
  192. break; /* no more elements to count */
  193. }
  194. /* count elements in range (2^(lg-1), 2^lg] */
  195. for (; i <= lim; i++) {
  196. if (!ttisnil(&t->array[i-1]))
  197. lc++;
  198. }
  199. nums[lg] += lc;
  200. ause += lc;
  201. }
  202. return ause;
  203. }
  204. static int numusehash (const Table *t, int *nums, int *pnasize) {
  205. int totaluse = 0; /* total number of elements */
  206. int ause = 0; /* summation of `nums' */
  207. int i = sizenode(t);
  208. while (i--) {
  209. Node *n = &t->node[i];
  210. if (!ttisnil(gval(n))) {
  211. ause += countint(key2tval(n), nums);
  212. totaluse++;
  213. }
  214. }
  215. *pnasize += ause;
  216. return totaluse;
  217. }
  218. static void setarrayvector (lua_State *L, Table *t, int size) {
  219. int i;
  220. luaM_reallocvector(L, t->array, t->sizearray, size, TValue);
  221. for (i=t->sizearray; i<size; i++)
  222. setnilvalue(&t->array[i]);
  223. t->sizearray = size;
  224. }
  225. static void setnodevector (lua_State *L, Table *t, int size) {
  226. int lsize;
  227. if (size == 0) { /* no elements to hash part? */
  228. t->node = cast(Node *, dummynode); /* use common `dummynode' */
  229. lsize = 0;
  230. }
  231. else {
  232. int i;
  233. lsize = ceillog2(size);
  234. if (lsize > MAXBITS)
  235. luaG_runerror(L, "table overflow");
  236. size = twoto(lsize);
  237. t->node = luaM_newvector(L, size, Node);
  238. for (i=0; i<size; i++) {
  239. Node *n = gnode(t, i);
  240. gnext(n) = NULL;
  241. setnilvalue(gkey(n));
  242. setnilvalue(gval(n));
  243. }
  244. }
  245. t->lsizenode = cast_byte(lsize);
  246. t->lastfree = gnode(t, size); /* all positions are free */
  247. }
  248. static void resize (lua_State *L, Table *t, int nasize, int nhsize) {
  249. int i;
  250. int oldasize = t->sizearray;
  251. int oldhsize = t->lsizenode;
  252. Node *nold = t->node; /* save old hash ... */
  253. if (nasize > oldasize) /* array part must grow? */
  254. setarrayvector(L, t, nasize);
  255. /* create new hash part with appropriate size */
  256. setnodevector(L, t, nhsize);
  257. if (nasize < oldasize) { /* array part must shrink? */
  258. t->sizearray = nasize;
  259. /* re-insert elements from vanishing slice */
  260. for (i=nasize; i<oldasize; i++) {
  261. if (!ttisnil(&t->array[i]))
  262. setobjt2t(L, luaH_setnum(L, t, i+1), &t->array[i]);
  263. }
  264. /* shrink array */
  265. luaM_reallocvector(L, t->array, oldasize, nasize, TValue);
  266. }
  267. /* re-insert elements from hash part */
  268. for (i = twoto(oldhsize) - 1; i >= 0; i--) {
  269. Node *old = nold+i;
  270. if (!ttisnil(gval(old)))
  271. setobjt2t(L, luaH_set(L, t, key2tval(old)), gval(old));
  272. }
  273. if (nold != dummynode)
  274. luaM_freearray(L, nold, twoto(oldhsize), Node); /* free old array */
  275. }
  276. void luaH_resizearray (lua_State *L, Table *t, int nasize) {
  277. int nsize = (t->node == dummynode) ? 0 : sizenode(t);
  278. resize(L, t, nasize, nsize);
  279. }
  280. static void rehash (lua_State *L, Table *t, const TValue *ek) {
  281. int nasize, na;
  282. int nums[MAXBITS+1]; /* nums[i] = number of keys between 2^(i-1) and 2^i */
  283. int i;
  284. int totaluse;
  285. for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */
  286. nasize = numusearray(t, nums); /* count keys in array part */
  287. totaluse = nasize; /* all those keys are integer keys */
  288. totaluse += numusehash(t, nums, &nasize); /* count keys in hash part */
  289. /* count extra key */
  290. nasize += countint(ek, nums);
  291. totaluse++;
  292. /* compute new size for array part */
  293. na = computesizes(nums, &nasize);
  294. /* resize the table to new computed sizes */
  295. resize(L, t, nasize, totaluse - na);
  296. }
  297. /*
  298. ** }=============================================================
  299. */
  300. Table *luaH_new (lua_State *L, int narray, int nhash) {
  301. Table *t = luaM_new(L, Table);
  302. luaC_link(L, obj2gco(t), LUA_TTABLE);
  303. t->metatable = NULL;
  304. t->flags = cast_byte(~0);
  305. /* temporary values (kept only if some malloc fails) */
  306. t->array = NULL;
  307. t->sizearray = 0;
  308. t->lsizenode = 0;
  309. t->node = cast(Node *, dummynode);
  310. setarrayvector(L, t, narray);
  311. setnodevector(L, t, nhash);
  312. return t;
  313. }
  314. void luaH_free (lua_State *L, Table *t) {
  315. if (t->node != dummynode)
  316. luaM_freearray(L, t->node, sizenode(t), Node);
  317. luaM_freearray(L, t->array, t->sizearray, TValue);
  318. luaM_free(L, t);
  319. }
  320. static Node *getfreepos (Table *t) {
  321. while (t->lastfree-- > t->node) {
  322. if (ttisnil(gkey(t->lastfree)))
  323. return t->lastfree;
  324. }
  325. return NULL; /* could not find a free place */
  326. }
  327. /*
  328. ** inserts a new key into a hash table; first, check whether key's main
  329. ** position is free. If not, check whether colliding node is in its main
  330. ** position or not: if it is not, move colliding node to an empty place and
  331. ** put new key in its main position; otherwise (colliding node is in its main
  332. ** position), new key goes to an empty position.
  333. */
  334. static TValue *newkey (lua_State *L, Table *t, const TValue *key) {
  335. Node *mp = mainposition(t, key);
  336. if (!ttisnil(gval(mp)) || mp == dummynode) {
  337. Node *othern;
  338. Node *n = getfreepos(t); /* get a free place */
  339. if (n == NULL) { /* cannot find a free place? */
  340. rehash(L, t, key); /* grow table */
  341. return luaH_set(L, t, key); /* re-insert key into grown table */
  342. }
  343. lua_assert(n != dummynode);
  344. othern = mainposition(t, key2tval(mp));
  345. if (othern != mp) { /* is colliding node out of its main position? */
  346. /* yes; move colliding node into free position */
  347. while (gnext(othern) != mp) othern = gnext(othern); /* find previous */
  348. gnext(othern) = n; /* redo the chain with `n' in place of `mp' */
  349. *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  350. gnext(mp) = NULL; /* now `mp' is free */
  351. setnilvalue(gval(mp));
  352. }
  353. else { /* colliding node is in its own main position */
  354. /* new node will go into free position */
  355. gnext(n) = gnext(mp); /* chain new position */
  356. gnext(mp) = n;
  357. mp = n;
  358. }
  359. }
  360. gkey(mp)->value = key->value; gkey(mp)->tt = key->tt;
  361. luaC_barriert(L, t, key);
  362. lua_assert(ttisnil(gval(mp)));
  363. return gval(mp);
  364. }
  365. /*
  366. ** search function for integers
  367. */
  368. const TValue *luaH_getnum (Table *t, int key) {
  369. /* (1 <= key && key <= t->sizearray) */
  370. if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray))
  371. return &t->array[key-1];
  372. else {
  373. lua_Number nk = cast_num(key);
  374. Node *n = hashnum(t, nk);
  375. do { /* check whether `key' is somewhere in the chain */
  376. if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk))
  377. return gval(n); /* that's it */
  378. else n = gnext(n);
  379. } while (n);
  380. return luaO_nilobject;
  381. }
  382. }
  383. /*
  384. ** search function for strings
  385. */
  386. const TValue *luaH_getstr (Table *t, TString *key) {
  387. Node *n = hashstr(t, key);
  388. do { /* check whether `key' is somewhere in the chain */
  389. if (ttisstring(gkey(n)) && rawtsvalue(gkey(n)) == key)
  390. return gval(n); /* that's it */
  391. else n = gnext(n);
  392. } while (n);
  393. return luaO_nilobject;
  394. }
  395. /*
  396. ** main search function
  397. */
  398. const TValue *luaH_get (Table *t, const TValue *key) {
  399. switch (ttype(key)) {
  400. case LUA_TNIL: return luaO_nilobject;
  401. case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key));
  402. case LUA_TNUMBER: {
  403. int k;
  404. lua_Number n = nvalue(key);
  405. lua_number2int(k, n);
  406. if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */
  407. return luaH_getnum(t, k); /* use specialized version */
  408. /* else go through */
  409. }
  410. default: {
  411. Node *n = mainposition(t, key);
  412. do { /* check whether `key' is somewhere in the chain */
  413. if (luaO_rawequalObj(key2tval(n), key))
  414. return gval(n); /* that's it */
  415. else n = gnext(n);
  416. } while (n);
  417. return luaO_nilobject;
  418. }
  419. }
  420. }
  421. TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
  422. const TValue *p = luaH_get(t, key);
  423. t->flags = 0;
  424. if (p != luaO_nilobject)
  425. return cast(TValue *, p);
  426. else {
  427. if (ttisnil(key)) luaG_runerror(L, "table index is nil");
  428. else if (ttisnumber(key) && luai_numisnan(nvalue(key)))
  429. luaG_runerror(L, "table index is NaN");
  430. return newkey(L, t, key);
  431. }
  432. }
  433. TValue *luaH_setnum (lua_State *L, Table *t, int key) {
  434. const TValue *p = luaH_getnum(t, key);
  435. if (p != luaO_nilobject)
  436. return cast(TValue *, p);
  437. else {
  438. TValue k;
  439. setnvalue(&k, cast_num(key));
  440. return newkey(L, t, &k);
  441. }
  442. }
  443. TValue *luaH_setstr (lua_State *L, Table *t, TString *key) {
  444. const TValue *p = luaH_getstr(t, key);
  445. if (p != luaO_nilobject)
  446. return cast(TValue *, p);
  447. else {
  448. TValue k;
  449. setsvalue(L, &k, key);
  450. return newkey(L, t, &k);
  451. }
  452. }
  453. static int unbound_search (Table *t, unsigned int j) {
  454. unsigned int i = j; /* i is zero or a present index */
  455. j++;
  456. /* find `i' and `j' such that i is present and j is not */
  457. while (!ttisnil(luaH_getnum(t, j))) {
  458. i = j;
  459. j *= 2;
  460. if (j > cast(unsigned int, MAX_INT)) { /* overflow? */
  461. /* table was built with bad purposes: resort to linear search */
  462. i = 1;
  463. while (!ttisnil(luaH_getnum(t, i))) i++;
  464. return i - 1;
  465. }
  466. }
  467. /* now do a binary search between them */
  468. while (j - i > 1) {
  469. unsigned int m = (i+j)/2;
  470. if (ttisnil(luaH_getnum(t, m))) j = m;
  471. else i = m;
  472. }
  473. return i;
  474. }
  475. /*
  476. ** Try to find a boundary in table `t'. A `boundary' is an integer index
  477. ** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
  478. */
  479. int luaH_getn (Table *t) {
  480. unsigned int j = t->sizearray;
  481. if (j > 0 && ttisnil(&t->array[j - 1])) {
  482. /* there is a boundary in the array part: (binary) search for it */
  483. unsigned int i = 0;
  484. while (j - i > 1) {
  485. unsigned int m = (i+j)/2;
  486. if (ttisnil(&t->array[m - 1])) j = m;
  487. else i = m;
  488. }
  489. return i;
  490. }
  491. /* else must find a boundary in hash part */
  492. else if (t->node == dummynode) /* hash part is empty? */
  493. return j; /* that is easy... */
  494. else return unbound_search(t, j);
  495. }
  496. #if defined(LUA_DEBUG)
  497. Node *luaH_mainposition (const Table *t, const TValue *key) {
  498. return mainposition(t, key);
  499. }
  500. int luaH_isdummy (Node *n) { return n == dummynode; }
  501. #endif