ltable.c 14 KB

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