ltable.c 14 KB

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