ltable.c 14 KB

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