2
0

ltable.c 14 KB

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