ltable.c 13 KB

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