ltable.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. /*
  2. ** $Id: ltable.c,v 1.125 2002/12/02 12:06:10 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; i <= MAXBITS && *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;
  153. int totaluse = 0;
  154. for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* init `nums' */
  155. /* count elements in array part */
  156. i = luaO_log2(t->sizearray) + 1; /* number of `slices' */
  157. while (i--) { /* for each slice [2^(i-1) to 2^i) */
  158. int to = twoto(i);
  159. int from = to/2;
  160. if (to > t->sizearray) to = t->sizearray;
  161. for (; from < to; from++)
  162. if (!ttisnil(&t->array[from])) {
  163. nums[i]++;
  164. totaluse++;
  165. }
  166. }
  167. *narray = totaluse; /* all previous uses were in array part */
  168. /* count elements in hash part */
  169. i = sizenode(t);
  170. while (i--) {
  171. if (!ttisnil(val(&t->node[i]))) {
  172. int k = arrayindex(key(&t->node[i]));
  173. if (k >= 0) { /* is `key' an appropriate array index? */
  174. nums[luaO_log2(k-1)+1]++; /* count as such */
  175. (*narray)++;
  176. }
  177. totaluse++;
  178. }
  179. }
  180. computesizes(nums, totaluse, narray, nhash);
  181. }
  182. static void setarrayvector (lua_State *L, Table *t, int size) {
  183. int i;
  184. luaM_reallocvector(L, t->array, t->sizearray, size, TObject);
  185. for (i=t->sizearray; i<size; i++)
  186. setnilvalue(&t->array[i]);
  187. t->sizearray = size;
  188. }
  189. static void setnodevector (lua_State *L, Table *t, int lsize) {
  190. int i;
  191. int size = twoto(lsize);
  192. if (lsize > MAXBITS)
  193. luaG_runerror(L, "table overflow");
  194. if (lsize == 0) { /* no elements to hash part? */
  195. t->node = G(L)->dummynode; /* use common `dummynode' */
  196. lua_assert(ttisnil(key(t->node))); /* assert invariants: */
  197. lua_assert(ttisnil(val(t->node)));
  198. lua_assert(t->node->next == NULL); /* (`dummynode' must be empty) */
  199. }
  200. else {
  201. t->node = luaM_newvector(L, size, Node);
  202. for (i=0; i<size; i++) {
  203. t->node[i].next = NULL;
  204. setnilvalue(key(node(t, i)));
  205. setnilvalue(val(node(t, i)));
  206. }
  207. }
  208. t->lsizenode = cast(lu_byte, lsize);
  209. t->firstfree = node(t, size-1); /* first free position to be used */
  210. }
  211. static void resize (lua_State *L, Table *t, int nasize, int nhsize) {
  212. int i;
  213. int oldasize = t->sizearray;
  214. int oldhsize = t->lsizenode;
  215. Node *nold;
  216. Node temp[1];
  217. if (oldhsize)
  218. nold = t->node; /* save old hash ... */
  219. else { /* old hash is `dummynode' */
  220. lua_assert(t->node == G(L)->dummynode);
  221. temp[0] = t->node[0]; /* copy it to `temp' */
  222. nold = temp;
  223. setnilvalue(key(G(L)->dummynode)); /* restate invariant */
  224. setnilvalue(val(G(L)->dummynode));
  225. lua_assert(G(L)->dummynode->next == NULL);
  226. }
  227. if (nasize > oldasize) /* array part must grow? */
  228. setarrayvector(L, t, nasize);
  229. /* create new hash part with appropriate size */
  230. setnodevector(L, t, nhsize);
  231. /* re-insert elements */
  232. if (nasize < oldasize) { /* array part must shrink? */
  233. t->sizearray = nasize;
  234. /* re-insert elements from vanishing slice */
  235. for (i=nasize; i<oldasize; i++) {
  236. if (!ttisnil(&t->array[i]))
  237. setobjt2t(luaH_setnum(L, t, i+1), &t->array[i]);
  238. }
  239. /* shrink array */
  240. luaM_reallocvector(L, t->array, oldasize, nasize, TObject);
  241. }
  242. /* re-insert elements in hash part */
  243. for (i = twoto(oldhsize) - 1; i >= 0; i--) {
  244. Node *old = nold+i;
  245. if (!ttisnil(val(old)))
  246. setobjt2t(luaH_set(L, t, key(old)), val(old));
  247. }
  248. if (oldhsize)
  249. luaM_freearray(L, nold, twoto(oldhsize), Node); /* free old array */
  250. }
  251. static void rehash (lua_State *L, Table *t) {
  252. int nasize, nhsize;
  253. numuse(t, &nasize, &nhsize); /* compute new sizes for array and hash parts */
  254. resize(L, t, nasize, luaO_log2(nhsize)+1);
  255. }
  256. /*
  257. ** }=============================================================
  258. */
  259. Table *luaH_new (lua_State *L, int narray, int lnhash) {
  260. Table *t = luaM_new(L, Table);
  261. luaC_link(L, valtogco(t), LUA_TTABLE);
  262. t->metatable = hvalue(defaultmeta(L));
  263. t->flags = cast(lu_byte, ~0);
  264. /* temporary values (kept only if some malloc fails) */
  265. t->array = NULL;
  266. t->sizearray = 0;
  267. t->lsizenode = 0;
  268. t->node = NULL;
  269. setarrayvector(L, t, narray);
  270. setnodevector(L, t, lnhash);
  271. return t;
  272. }
  273. void luaH_free (lua_State *L, Table *t) {
  274. if (t->lsizenode)
  275. luaM_freearray(L, t->node, sizenode(t), Node);
  276. luaM_freearray(L, t->array, t->sizearray, TObject);
  277. luaM_freelem(L, t);
  278. }
  279. #if 0
  280. /*
  281. ** try to remove an element from a hash table; cannot move any element
  282. ** (because gc can call `remove' during a table traversal)
  283. */
  284. void luaH_remove (Table *t, Node *e) {
  285. Node *mp = luaH_mainposition(t, key(e));
  286. if (e != mp) { /* element not in its main position? */
  287. while (mp->next != e) mp = mp->next; /* find previous */
  288. mp->next = e->next; /* remove `e' from its list */
  289. }
  290. else {
  291. if (e->next != NULL) ??
  292. }
  293. lua_assert(ttisnil(val(node)));
  294. setnilvalue(key(e)); /* clear node `e' */
  295. e->next = NULL;
  296. }
  297. #endif
  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 TObject *newkey (lua_State *L, Table *t, const TObject *key) {
  306. TObject *val;
  307. Node *mp = luaH_mainposition(t, key);
  308. if (!ttisnil(val(mp))) { /* main position is not free? */
  309. Node *othern = luaH_mainposition(t, key(mp)); /* `mp' of colliding node */
  310. Node *n = t->firstfree; /* get a free place */
  311. if (othern != mp) { /* is colliding node out of its main position? */
  312. /* yes; move colliding node into free position */
  313. while (othern->next != mp) othern = othern->next; /* find previous */
  314. othern->next = n; /* redo the chain with `n' in place of `mp' */
  315. *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  316. mp->next = NULL; /* now `mp' is free */
  317. setnilvalue(val(mp));
  318. }
  319. else { /* colliding node is in its own main position */
  320. /* new node will go into free position */
  321. n->next = mp->next; /* chain new position */
  322. mp->next = n;
  323. mp = n;
  324. }
  325. }
  326. setobj2t(key(mp), key); /* write barrier */
  327. lua_assert(ttisnil(val(mp)));
  328. for (;;) { /* correct `firstfree' */
  329. if (ttisnil(key(t->firstfree)))
  330. return val(mp); /* OK; table still has a free place */
  331. else if (t->firstfree == t->node) break; /* cannot decrement from here */
  332. else (t->firstfree)--;
  333. }
  334. /* no more free places; must create one */
  335. setbvalue(val(mp), 0); /* avoid new key being removed */
  336. rehash(L, t); /* grow table */
  337. val = cast(TObject *, luaH_get(t, key)); /* get new position */
  338. lua_assert(ttisboolean(val));
  339. setnilvalue(val);
  340. return val;
  341. }
  342. /*
  343. ** generic search function
  344. */
  345. static const TObject *luaH_getany (Table *t, const TObject *key) {
  346. if (ttisnil(key)) return &luaO_nilobject;
  347. else {
  348. Node *n = luaH_mainposition(t, key);
  349. do { /* check whether `key' is somewhere in the chain */
  350. if (luaO_rawequalObj(key(n), key)) return val(n); /* that's it */
  351. else n = n->next;
  352. } while (n);
  353. return &luaO_nilobject;
  354. }
  355. }
  356. /*
  357. ** search function for integers
  358. */
  359. const TObject *luaH_getnum (Table *t, int key) {
  360. if (1 <= key && key <= t->sizearray)
  361. return &t->array[key-1];
  362. else {
  363. Node *n = hashnum(t, key);
  364. do { /* check whether `key' is somewhere in the chain */
  365. if (ttisnumber(key(n)) && nvalue(key(n)) == (lua_Number)key)
  366. return val(n); /* that's it */
  367. else n = n->next;
  368. } while (n);
  369. return &luaO_nilobject;
  370. }
  371. }
  372. /*
  373. ** search function for strings
  374. */
  375. const TObject *luaH_getstr (Table *t, TString *key) {
  376. Node *n = hashstr(t, key);
  377. do { /* check whether `key' is somewhere in the chain */
  378. if (ttisstring(key(n)) && tsvalue(key(n)) == key)
  379. return val(n); /* that's it */
  380. else n = n->next;
  381. } while (n);
  382. return &luaO_nilobject;
  383. }
  384. /*
  385. ** main search function
  386. */
  387. const TObject *luaH_get (Table *t, const TObject *key) {
  388. switch (ttype(key)) {
  389. case LUA_TSTRING: return luaH_getstr(t, tsvalue(key));
  390. case LUA_TNUMBER: {
  391. int k;
  392. lua_number2int(k, (nvalue(key)));
  393. if (cast(lua_Number, k) == nvalue(key)) /* is an integer index? */
  394. return luaH_getnum(t, k); /* use specialized version */
  395. /* else go through */
  396. }
  397. default: return luaH_getany(t, key);
  398. }
  399. }
  400. TObject *luaH_set (lua_State *L, Table *t, const TObject *key) {
  401. const TObject *p = luaH_get(t, key);
  402. t->flags = 0;
  403. if (p != &luaO_nilobject)
  404. return cast(TObject *, p);
  405. else {
  406. if (ttisnil(key)) luaG_runerror(L, "table index is nil");
  407. else if (ttisnumber(key) && nvalue(key) != nvalue(key))
  408. luaG_runerror(L, "table index is NaN");
  409. return newkey(L, t, key);
  410. }
  411. }
  412. TObject *luaH_setnum (lua_State *L, Table *t, int key) {
  413. const TObject *p = luaH_getnum(t, key);
  414. if (p != &luaO_nilobject)
  415. return cast(TObject *, p);
  416. else {
  417. TObject k;
  418. setnvalue(&k, key);
  419. return newkey(L, t, &k);
  420. }
  421. }