ltable.c 14 KB

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