ltable.c 17 KB

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