ltable.c 15 KB

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