Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 

592 wiersze
16 KiB

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