ltable.c 13 KB

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