ltable.c 14 KB

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