ltable.c 14 KB

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