ltable.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. /*
  2. ** $Id: ltable.c,v 1.109 2002/05/27 20:35:40 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. #include "lua.h"
  22. #include "ldebug.h"
  23. #include "ldo.h"
  24. #include "lmem.h"
  25. #include "lobject.h"
  26. #include "lstate.h"
  27. #include "ltable.h"
  28. /*
  29. ** max size of array part is 2^MAXBITS
  30. */
  31. #if BITS_INT > 26
  32. #define MAXBITS 24
  33. #else
  34. #define MAXBITS (BITS_INT-2)
  35. #endif
  36. /* check whether `x' < 2^MAXBITS */
  37. #define toobig(x) ((((x)-1) >> MAXBITS) != 0)
  38. #define TagDefault LUA_TTABLE
  39. #define hashnum(t,n) \
  40. (node(t, lmod(cast(lu_hash, cast(ls_hash, n)), sizenode(t))))
  41. #define hashstr(t,str) (node(t, lmod((str)->tsv.hash, sizenode(t))))
  42. #define hashboolean(t,p) (node(t, lmod(p, sizenode(t))))
  43. /*
  44. ** avoid modulus by power of 2 for pointers, as they tend to have many
  45. ** 2 factors.
  46. */
  47. #define hashpointer(t,p) (node(t, (IntPoint(p) % ((sizenode(t)-1)|1))))
  48. /*
  49. ** returns the `main' position of an element in a table (that is, the index
  50. ** of its hash value)
  51. */
  52. Node *luaH_mainposition (const Table *t, const TObject *key) {
  53. switch (ttype(key)) {
  54. case LUA_TNUMBER:
  55. return hashnum(t, nvalue(key));
  56. case LUA_TSTRING:
  57. return hashstr(t, tsvalue(key));
  58. case LUA_TBOOLEAN:
  59. return hashboolean(t, bvalue(key));
  60. case LUA_TUDATAVAL:
  61. return hashpointer(t, pvalue(key));
  62. case LUA_TUSERDATA:
  63. return hashpointer(t, uvalue(key));
  64. case LUA_TFUNCTION:
  65. return hashpointer(t, clvalue(key));
  66. case LUA_TTABLE:
  67. return hashpointer(t, hvalue(key));
  68. }
  69. lua_assert(0);
  70. return 0; /* to avoid warnings */
  71. }
  72. /*
  73. ** returns the index for `key' if `key' is an appropriate key to live in
  74. ** the array part of the table, -1 otherwise.
  75. */
  76. static int arrayindex (const TObject *key) {
  77. if (ttype(key) == LUA_TNUMBER) {
  78. int k;
  79. lua_number2int(k, (nvalue(key)));
  80. if (cast(lua_Number, k) == nvalue(key) && k >= 1 && !toobig(k))
  81. return k;
  82. }
  83. return -1; /* `key' did not match some condition */
  84. }
  85. /*
  86. ** returns the index of a `key' for table traversals. First goes all
  87. ** elements in the array part, then elements in the hash part. The
  88. ** beginning and end of a traversal are signalled by -1.
  89. */
  90. static int luaH_index (lua_State *L, Table *t, const TObject *key) {
  91. int i;
  92. if (ttype(key) == LUA_TNIL) return -1; /* first iteration */
  93. i = arrayindex(key);
  94. if (0 <= i && i <= t->sizearray) { /* is `key' inside array part? */
  95. return i-1; /* yes; that's the index (corrected to C) */
  96. }
  97. else {
  98. const TObject *v = luaH_get(t, key);
  99. if (v == &luaO_nilobject)
  100. luaG_runerror(L, "invalid key for `next'");
  101. i = cast(int, (cast(const lu_byte *, v) -
  102. cast(const lu_byte *, val(node(t, 0)))) / sizeof(Node));
  103. return i + t->sizearray; /* hash elements are numbered after array ones */
  104. }
  105. }
  106. int luaH_next (lua_State *L, Table *t, TObject *key) {
  107. int i = luaH_index(L, t, key); /* find original element */
  108. for (i++; i < t->sizearray; i++) { /* try first array part */
  109. if (ttype(&t->array[i]) != LUA_TNIL) { /* a non-nil value? */
  110. setnvalue(key, i+1);
  111. setobj(key+1, &t->array[i]);
  112. return 1;
  113. }
  114. }
  115. for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */
  116. if (ttype(val(node(t, i))) != LUA_TNIL) { /* a non-nil value? */
  117. setobj(key, key(node(t, i)));
  118. setobj(key+1, val(node(t, i)));
  119. return 1;
  120. }
  121. }
  122. return 0; /* no more elements */
  123. }
  124. /*
  125. ** {=============================================================
  126. ** Rehash
  127. ** ==============================================================
  128. */
  129. static void computesizes (int nums[], int ntotal, int *narray, int *nhash) {
  130. int i;
  131. int a = nums[0]; /* number of elements smaller than 2^i */
  132. int na = a; /* number of elements to go to array part */
  133. int n = (na == 0) ? -1 : 0; /* (log of) optimal size for array part */
  134. for (i = 1; i <= MAXBITS && *narray >= twoto(i-1); i++) {
  135. if (nums[i] > 0) {
  136. a += nums[i];
  137. if (a >= twoto(i-1)) { /* more than half elements in use? */
  138. n = i;
  139. na = a;
  140. }
  141. }
  142. }
  143. lua_assert(na <= *narray && *narray <= ntotal);
  144. *nhash = ntotal - na;
  145. *narray = (n == -1) ? 0 : twoto(n);
  146. lua_assert(na <= *narray && na >= *narray/2);
  147. }
  148. static void numuse (const Table *t, int *narray, int *nhash) {
  149. int nums[MAXBITS+1];
  150. int i;
  151. int totaluse = 0;
  152. for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* init `nums' */
  153. /* count elements in array part */
  154. i = luaO_log2(t->sizearray) + 1; /* number of `slices' */
  155. while (i--) { /* for each slice [2^(i-1) to 2^i) */
  156. int to = twoto(i);
  157. int from = to/2;
  158. if (to > t->sizearray) to = t->sizearray;
  159. for (; from < to; from++)
  160. if (ttype(&t->array[from]) != LUA_TNIL) {
  161. nums[i]++;
  162. totaluse++;
  163. }
  164. }
  165. *narray = totaluse; /* all previous uses were in array part */
  166. /* count elements in hash part */
  167. i = sizenode(t);
  168. while (i--) {
  169. if (ttype(val(&t->node[i])) != LUA_TNIL) {
  170. int k = arrayindex(key(&t->node[i]));
  171. if (k >= 0) { /* is `key' an appropriate array index? */
  172. nums[luaO_log2(k-1)+1]++; /* count as such */
  173. (*narray)++;
  174. }
  175. totaluse++;
  176. }
  177. }
  178. computesizes(nums, totaluse, narray, nhash);
  179. }
  180. static void setarrayvector (lua_State *L, Table *t, int size) {
  181. int i;
  182. luaM_reallocvector(L, t->array, t->sizearray, size, TObject);
  183. for (i=t->sizearray; i<size; i++)
  184. setnilvalue(&t->array[i]);
  185. t->sizearray = size;
  186. }
  187. static void setnodevector (lua_State *L, Table *t, int lsize) {
  188. int i;
  189. int size = twoto(lsize);
  190. if (lsize > MAXBITS)
  191. luaG_runerror(L, "table overflow");
  192. if (lsize == 0) { /* no elements to hash part? */
  193. t->node = G(L)->dummynode; /* use common `dummynode' */
  194. lua_assert(ttype(key(t->node)) == LUA_TNIL); /* assert invariants: */
  195. lua_assert(ttype(val(t->node)) == LUA_TNIL);
  196. lua_assert(t->node->next == NULL); /* (`dummynode' must be empty) */
  197. }
  198. else {
  199. t->node = luaM_newvector(L, size, Node);
  200. for (i=0; i<size; i++) {
  201. t->node[i].next = NULL;
  202. setnilvalue(key(node(t, i)));
  203. setnilvalue(val(node(t, i)));
  204. }
  205. }
  206. t->lsizenode = cast(lu_byte, lsize);
  207. t->firstfree = node(t, size-1); /* first free position to be used */
  208. }
  209. static void resize (lua_State *L, Table *t, int nasize, int nhsize) {
  210. int i;
  211. int oldasize = t->sizearray;
  212. int oldhsize = t->lsizenode;
  213. Node *nold;
  214. Node temp[1];
  215. if (oldhsize)
  216. nold = t->node; /* save old hash ... */
  217. else { /* old hash is `dummynode' */
  218. lua_assert(t->node == G(L)->dummynode);
  219. temp[0] = t->node[0]; /* copy it to `temp' */
  220. nold = temp;
  221. setnilvalue(key(G(L)->dummynode)); /* restate invariant */
  222. setnilvalue(val(G(L)->dummynode));
  223. lua_assert(G(L)->dummynode->next == NULL);
  224. }
  225. if (nasize > oldasize) /* array part must grow? */
  226. setarrayvector(L, t, nasize);
  227. /* create new hash part with appropriate size */
  228. setnodevector(L, t, nhsize);
  229. /* re-insert elements */
  230. if (nasize < oldasize) { /* array part must shrink? */
  231. t->sizearray = nasize;
  232. /* re-insert elements from vanishing slice */
  233. for (i=nasize; i<oldasize; i++) {
  234. if (ttype(&t->array[i]) != LUA_TNIL)
  235. setobj(luaH_setnum(L, t, i+1), &t->array[i]);
  236. }
  237. /* shrink array */
  238. luaM_reallocvector(L, t->array, oldasize, nasize, TObject);
  239. }
  240. /* re-insert elements in hash part */
  241. for (i = twoto(oldhsize) - 1; i >= 0; i--) {
  242. Node *old = nold+i;
  243. if (ttype(val(old)) != LUA_TNIL)
  244. setobj(luaH_set(L, t, key(old)), val(old));
  245. }
  246. if (oldhsize)
  247. luaM_freearray(L, nold, twoto(oldhsize), Node); /* free old array */
  248. }
  249. static void rehash (lua_State *L, Table *t) {
  250. int nasize, nhsize;
  251. numuse(t, &nasize, &nhsize); /* compute new sizes for array and hash parts */
  252. resize(L, t, nasize, luaO_log2(nhsize)+1);
  253. }
  254. /*
  255. ** }=============================================================
  256. */
  257. Table *luaH_new (lua_State *L, int narray, int lnhash) {
  258. Table *t = luaM_new(L, Table);
  259. t->metatable = hvalue(defaultmeta(L));
  260. t->next = G(L)->roottable;
  261. G(L)->roottable = t;
  262. t->mark = t;
  263. t->flags = cast(unsigned short, ~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(ttype(val(node)) == LUA_TNIL);
  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 (ttype(val(mp)) != LUA_TNIL) { /* 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. setobj(key(mp), key);
  327. lua_assert(ttype(val(mp)) == LUA_TNIL);
  328. for (;;) { /* correct `firstfree' */
  329. if (ttype(key(t->firstfree)) == LUA_TNIL)
  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(ttype(val) == LUA_TBOOLEAN);
  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 (ttype(key) == LUA_TNIL) 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 (ttype(key(n)) == LUA_TNUMBER && 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 (ttype(key(n)) == LUA_TSTRING && 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 (ttype(key) == LUA_TNIL) luaG_runerror(L, "table index is nil");
  407. return newkey(L, t, key);
  408. }
  409. }
  410. TObject *luaH_setnum (lua_State *L, Table *t, int key) {
  411. const TObject *p = luaH_getnum(t, key);
  412. if (p != &luaO_nilobject)
  413. return cast(TObject *, p);
  414. else {
  415. TObject k;
  416. setnvalue(&k, key);
  417. return newkey(L, t, &k);
  418. }
  419. }