ltable.c 14 KB

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