ltable.c 17 KB

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