ltable.c 13 KB

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