ltable.c 15 KB

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