ltable.c 14 KB

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