PageRenderTime 27ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/ports/dingux/tags/v3-20101128/Source_Files/Lua/ltable.c

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