ltable.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. /*
  2. ** $Id: ltable.c $
  3. ** Lua tables (hash)
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define ltable_c
  7. #define LUA_CORE
  8. #include "lprefix.h"
  9. /*
  10. ** Implementation of tables (aka arrays, objects, or hash tables).
  11. ** Tables keep its elements in two parts: an array part and a hash part.
  12. ** Non-negative integer keys are all candidates to be kept in the array
  13. ** part. The actual size of the array is the largest 'n' such that
  14. ** more than half the slots between 1 and n are in use.
  15. ** Hash uses a mix of chained scatter table with Brent's variation.
  16. ** A main invariant of these tables is that, if an element is not
  17. ** in its main position (i.e. the 'original' position that its hash gives
  18. ** to it), then the colliding element is in its own main position.
  19. ** Hence even when the load factor reaches 100%, performance remains good.
  20. */
  21. #include <math.h>
  22. #include <limits.h>
  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 "lstring.h"
  31. #include "ltable.h"
  32. #include "lvm.h"
  33. /*
  34. ** Only tables with hash parts larget than LIMFORLAST has a 'lastfree'
  35. ** field that optimizes finding a free slot. Smaller tables do a
  36. ** complete search when looking for a free slot.
  37. */
  38. #define LLIMFORLAST 2 /* log2 of LIMTFORLAST */
  39. #define LIMFORLAST twoto(LLIMFORLAST)
  40. /*
  41. ** Union to store an int field ensuring that what follows it in
  42. ** memory is properly aligned to store a TValue.
  43. */
  44. typedef union {
  45. int lastfree;
  46. char padding[offsetof(struct { int i; TValue v; }, v)];
  47. } Limbox;
  48. #define haslastfree(t) ((t)->lsizenode > LLIMFORLAST)
  49. #define getlastfree(t) (&((cast(Limbox *, (t)->node) - 1)->lastfree))
  50. /*
  51. ** MAXABITS is the largest integer such that MAXASIZE fits in an
  52. ** unsigned int.
  53. */
  54. #define MAXABITS cast_int(sizeof(int) * CHAR_BIT - 1)
  55. /*
  56. ** MAXASIZE is the maximum size of the array part. It is the minimum
  57. ** between 2^MAXABITS and the maximum size that, measured in bytes,
  58. ** fits in a 'size_t'.
  59. */
  60. #define MAXASIZE luaM_limitN(1u << MAXABITS, TValue)
  61. /*
  62. ** MAXHBITS is the largest integer such that 2^MAXHBITS fits in a
  63. ** signed int.
  64. */
  65. #define MAXHBITS (MAXABITS - 1)
  66. /*
  67. ** MAXHSIZE is the maximum size of the hash part. It is the minimum
  68. ** between 2^MAXHBITS and the maximum size such that, measured in bytes,
  69. ** it fits in a 'size_t'.
  70. */
  71. #define MAXHSIZE luaM_limitN(1u << MAXHBITS, Node)
  72. /*
  73. ** When the original hash value is good, hashing by a power of 2
  74. ** avoids the cost of '%'.
  75. */
  76. #define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))
  77. /*
  78. ** for other types, it is better to avoid modulo by power of 2, as
  79. ** they can have many 2 factors.
  80. */
  81. #define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))
  82. #define hashstr(t,str) hashpow2(t, (str)->hash)
  83. #define hashboolean(t,p) hashpow2(t, p)
  84. #define hashpointer(t,p) hashmod(t, point2uint(p))
  85. #define dummynode (&dummynode_)
  86. static const Node dummynode_ = {
  87. {{NULL}, LUA_VEMPTY, /* value's value and type */
  88. LUA_VNIL, 0, {NULL}} /* key type, next, and key value */
  89. };
  90. static const TValue absentkey = {ABSTKEYCONSTANT};
  91. /*
  92. ** Hash for integers. To allow a good hash, use the remainder operator
  93. ** ('%'). If integer fits as a non-negative int, compute an int
  94. ** remainder, which is faster. Otherwise, use an unsigned-integer
  95. ** remainder, which uses all bits and ensures a non-negative result.
  96. */
  97. static Node *hashint (const Table *t, lua_Integer i) {
  98. lua_Unsigned ui = l_castS2U(i);
  99. if (ui <= cast_uint(INT_MAX))
  100. return hashmod(t, cast_int(ui));
  101. else
  102. return hashmod(t, ui);
  103. }
  104. /*
  105. ** Hash for floating-point numbers.
  106. ** The main computation should be just
  107. ** n = frexp(n, &i); return (n * INT_MAX) + i
  108. ** but there are some numerical subtleties.
  109. ** In a two-complement representation, INT_MAX does not has an exact
  110. ** representation as a float, but INT_MIN does; because the absolute
  111. ** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the
  112. ** absolute value of the product 'frexp * -INT_MIN' is smaller or equal
  113. ** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when
  114. ** adding 'i'; the use of '~u' (instead of '-u') avoids problems with
  115. ** INT_MIN.
  116. */
  117. #if !defined(l_hashfloat)
  118. static int l_hashfloat (lua_Number n) {
  119. int i;
  120. lua_Integer ni;
  121. n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN);
  122. if (!lua_numbertointeger(n, &ni)) { /* is 'n' inf/-inf/NaN? */
  123. lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL));
  124. return 0;
  125. }
  126. else { /* normal case */
  127. unsigned int u = cast_uint(i) + cast_uint(ni);
  128. return cast_int(u <= cast_uint(INT_MAX) ? u : ~u);
  129. }
  130. }
  131. #endif
  132. /*
  133. ** returns the 'main' position of an element in a table (that is,
  134. ** the index of its hash value).
  135. */
  136. static Node *mainpositionTV (const Table *t, const TValue *key) {
  137. switch (ttypetag(key)) {
  138. case LUA_VNUMINT: {
  139. lua_Integer i = ivalue(key);
  140. return hashint(t, i);
  141. }
  142. case LUA_VNUMFLT: {
  143. lua_Number n = fltvalue(key);
  144. return hashmod(t, l_hashfloat(n));
  145. }
  146. case LUA_VSHRSTR: {
  147. TString *ts = tsvalue(key);
  148. return hashstr(t, ts);
  149. }
  150. case LUA_VLNGSTR: {
  151. TString *ts = tsvalue(key);
  152. return hashpow2(t, luaS_hashlongstr(ts));
  153. }
  154. case LUA_VFALSE:
  155. return hashboolean(t, 0);
  156. case LUA_VTRUE:
  157. return hashboolean(t, 1);
  158. case LUA_VLIGHTUSERDATA: {
  159. void *p = pvalue(key);
  160. return hashpointer(t, p);
  161. }
  162. case LUA_VLCF: {
  163. lua_CFunction f = fvalue(key);
  164. return hashpointer(t, f);
  165. }
  166. default: {
  167. GCObject *o = gcvalue(key);
  168. return hashpointer(t, o);
  169. }
  170. }
  171. }
  172. l_sinline Node *mainpositionfromnode (const Table *t, Node *nd) {
  173. TValue key;
  174. getnodekey(cast(lua_State *, NULL), &key, nd);
  175. return mainpositionTV(t, &key);
  176. }
  177. /*
  178. ** Check whether key 'k1' is equal to the key in node 'n2'. This
  179. ** equality is raw, so there are no metamethods. Floats with integer
  180. ** values have been normalized, so integers cannot be equal to
  181. ** floats. It is assumed that 'eqshrstr' is simply pointer equality, so
  182. ** that short strings are handled in the default case.
  183. ** A true 'deadok' means to accept dead keys as equal to their original
  184. ** values. All dead keys are compared in the default case, by pointer
  185. ** identity. (Only collectable objects can produce dead keys.) Note that
  186. ** dead long strings are also compared by identity.
  187. ** Once a key is dead, its corresponding value may be collected, and
  188. ** then another value can be created with the same address. If this
  189. ** other value is given to 'next', 'equalkey' will signal a false
  190. ** positive. In a regular traversal, this situation should never happen,
  191. ** as all keys given to 'next' came from the table itself, and therefore
  192. ** could not have been collected. Outside a regular traversal, we
  193. ** have garbage in, garbage out. What is relevant is that this false
  194. ** positive does not break anything. (In particular, 'next' will return
  195. ** some other valid item on the table or nil.)
  196. */
  197. static int equalkey (const TValue *k1, const Node *n2, int deadok) {
  198. if ((rawtt(k1) != keytt(n2)) && /* not the same variants? */
  199. !(deadok && keyisdead(n2) && iscollectable(k1)))
  200. return 0; /* cannot be same key */
  201. switch (keytt(n2)) {
  202. case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE:
  203. return 1;
  204. case LUA_VNUMINT:
  205. return (ivalue(k1) == keyival(n2));
  206. case LUA_VNUMFLT:
  207. return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2)));
  208. case LUA_VLIGHTUSERDATA:
  209. return pvalue(k1) == pvalueraw(keyval(n2));
  210. case LUA_VLCF:
  211. return fvalue(k1) == fvalueraw(keyval(n2));
  212. case ctb(LUA_VLNGSTR):
  213. return luaS_eqlngstr(tsvalue(k1), keystrval(n2));
  214. default:
  215. return gcvalue(k1) == gcvalueraw(keyval(n2));
  216. }
  217. }
  218. /*
  219. ** True if value of 'alimit' is equal to the real size of the array
  220. ** part of table 't'. (Otherwise, the array part must be larger than
  221. ** 'alimit'.)
  222. */
  223. #define limitequalsasize(t) (isrealasize(t) || ispow2((t)->alimit))
  224. /*
  225. ** Returns the real size of the 'array' array
  226. */
  227. LUAI_FUNC unsigned int luaH_realasize (const Table *t) {
  228. if (limitequalsasize(t))
  229. return t->alimit; /* this is the size */
  230. else {
  231. unsigned int size = t->alimit;
  232. /* compute the smallest power of 2 not smaller than 'n' */
  233. size |= (size >> 1);
  234. size |= (size >> 2);
  235. size |= (size >> 4);
  236. size |= (size >> 8);
  237. size |= (size >> 16);
  238. #if (UINT_MAX >> 30) > 3
  239. size |= (size >> 32); /* unsigned int has more than 32 bits */
  240. #endif
  241. size++;
  242. lua_assert(ispow2(size) && size/2 < t->alimit && t->alimit < size);
  243. return size;
  244. }
  245. }
  246. /*
  247. ** Check whether real size of the array is a power of 2.
  248. ** (If it is not, 'alimit' cannot be changed to any other value
  249. ** without changing the real size.)
  250. */
  251. static int ispow2realasize (const Table *t) {
  252. return (!isrealasize(t) || ispow2(t->alimit));
  253. }
  254. static unsigned int setlimittosize (Table *t) {
  255. t->alimit = luaH_realasize(t);
  256. setrealasize(t);
  257. return t->alimit;
  258. }
  259. #define limitasasize(t) check_exp(isrealasize(t), t->alimit)
  260. /*
  261. ** "Generic" get version. (Not that generic: not valid for integers,
  262. ** which may be in array part, nor for floats with integral values.)
  263. ** See explanation about 'deadok' in function 'equalkey'.
  264. */
  265. static const TValue *getgeneric (Table *t, const TValue *key, int deadok) {
  266. Node *n = mainpositionTV(t, key);
  267. for (;;) { /* check whether 'key' is somewhere in the chain */
  268. if (equalkey(key, n, deadok))
  269. return gval(n); /* that's it */
  270. else {
  271. int nx = gnext(n);
  272. if (nx == 0)
  273. return &absentkey; /* not found */
  274. n += nx;
  275. }
  276. }
  277. }
  278. /*
  279. ** returns the index for 'k' if 'k' is an appropriate key to live in
  280. ** the array part of a table, 0 otherwise.
  281. */
  282. static unsigned int arrayindex (lua_Integer k) {
  283. if (l_castS2U(k) - 1u < MAXASIZE) /* 'k' in [1, MAXASIZE]? */
  284. return cast_uint(k); /* 'key' is an appropriate array index */
  285. else
  286. return 0;
  287. }
  288. /*
  289. ** returns the index of a 'key' for table traversals. First goes all
  290. ** elements in the array part, then elements in the hash part. The
  291. ** beginning of a traversal is signaled by 0.
  292. */
  293. static unsigned int findindex (lua_State *L, Table *t, TValue *key,
  294. unsigned int asize) {
  295. unsigned int i;
  296. if (ttisnil(key)) return 0; /* first iteration */
  297. i = ttisinteger(key) ? arrayindex(ivalue(key)) : 0;
  298. if (i - 1u < asize) /* is 'key' inside array part? */
  299. return i; /* yes; that's the index */
  300. else {
  301. const TValue *n = getgeneric(t, key, 1);
  302. if (l_unlikely(isabstkey(n)))
  303. luaG_runerror(L, "invalid key to 'next'"); /* key not found */
  304. i = cast_int(nodefromval(n) - gnode(t, 0)); /* key index in hash table */
  305. /* hash elements are numbered after array ones */
  306. return (i + 1) + asize;
  307. }
  308. }
  309. int luaH_next (lua_State *L, Table *t, StkId key) {
  310. unsigned int asize = luaH_realasize(t);
  311. unsigned int i = findindex(L, t, s2v(key), asize); /* find original key */
  312. for (; i < asize; i++) { /* try first array part */
  313. if (!isempty(&t->array[i])) { /* a non-empty entry? */
  314. setivalue(s2v(key), i + 1);
  315. setobj2s(L, key + 1, &t->array[i]);
  316. return 1;
  317. }
  318. }
  319. for (i -= asize; cast_int(i) < sizenode(t); i++) { /* hash part */
  320. if (!isempty(gval(gnode(t, i)))) { /* a non-empty entry? */
  321. Node *n = gnode(t, i);
  322. getnodekey(L, s2v(key), n);
  323. setobj2s(L, key + 1, gval(n));
  324. return 1;
  325. }
  326. }
  327. return 0; /* no more elements */
  328. }
  329. static void freehash (lua_State *L, Table *t) {
  330. if (!isdummy(t)) {
  331. size_t bsize = sizenode(t) * sizeof(Node); /* 'node' size in bytes */
  332. char *arr = cast_charp(t->node);
  333. if (haslastfree(t)) {
  334. bsize += sizeof(Limbox);
  335. arr -= sizeof(Limbox);
  336. }
  337. luaM_freearray(L, arr, bsize);
  338. }
  339. }
  340. /*
  341. ** {=============================================================
  342. ** Rehash
  343. ** ==============================================================
  344. */
  345. /*
  346. ** Compute the optimal size for the array part of table 't'. 'nums' is a
  347. ** "count array" where 'nums[i]' is the number of integers in the table
  348. ** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of
  349. ** integer keys in the table and leaves with the number of keys that
  350. ** will go to the array part; return the optimal size. (The condition
  351. ** 'twotoi > 0' in the for loop stops the loop if 'twotoi' overflows.)
  352. */
  353. static unsigned int computesizes (unsigned int nums[], unsigned int *pna) {
  354. int i;
  355. unsigned int twotoi; /* 2^i (candidate for optimal size) */
  356. unsigned int a = 0; /* number of elements smaller than 2^i */
  357. unsigned int na = 0; /* number of elements to go to array part */
  358. unsigned int optimal = 0; /* optimal size for array part */
  359. /* loop while keys can fill more than half of total size */
  360. for (i = 0, twotoi = 1;
  361. twotoi > 0 && *pna > twotoi / 2;
  362. i++, twotoi *= 2) {
  363. a += nums[i];
  364. if (a > twotoi/2) { /* more than half elements present? */
  365. optimal = twotoi; /* optimal size (till now) */
  366. na = a; /* all elements up to 'optimal' will go to array part */
  367. }
  368. }
  369. lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal);
  370. *pna = na;
  371. return optimal;
  372. }
  373. static int countint (lua_Integer key, unsigned int *nums) {
  374. unsigned int k = arrayindex(key);
  375. if (k != 0) { /* is 'key' an appropriate array index? */
  376. nums[luaO_ceillog2(k)]++; /* count as such */
  377. return 1;
  378. }
  379. else
  380. return 0;
  381. }
  382. /*
  383. ** Count keys in array part of table 't': Fill 'nums[i]' with
  384. ** number of keys that will go into corresponding slice and return
  385. ** total number of non-nil keys.
  386. */
  387. static unsigned int numusearray (const Table *t, unsigned int *nums) {
  388. int lg;
  389. unsigned int ttlg; /* 2^lg */
  390. unsigned int ause = 0; /* summation of 'nums' */
  391. unsigned int i = 1; /* count to traverse all array keys */
  392. unsigned int asize = limitasasize(t); /* real array size */
  393. /* traverse each slice */
  394. for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
  395. unsigned int lc = 0; /* counter */
  396. unsigned int lim = ttlg;
  397. if (lim > asize) {
  398. lim = asize; /* adjust upper limit */
  399. if (i > lim)
  400. break; /* no more elements to count */
  401. }
  402. /* count elements in range (2^(lg - 1), 2^lg] */
  403. for (; i <= lim; i++) {
  404. if (!isempty(&t->array[i-1]))
  405. lc++;
  406. }
  407. nums[lg] += lc;
  408. ause += lc;
  409. }
  410. return ause;
  411. }
  412. static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) {
  413. int totaluse = 0; /* total number of elements */
  414. int ause = 0; /* elements added to 'nums' (can go to array part) */
  415. int i = sizenode(t);
  416. while (i--) {
  417. Node *n = &t->node[i];
  418. if (!isempty(gval(n))) {
  419. if (keyisinteger(n))
  420. ause += countint(keyival(n), nums);
  421. totaluse++;
  422. }
  423. }
  424. *pna += ause;
  425. return totaluse;
  426. }
  427. /*
  428. ** Creates an array for the hash part of a table with the given
  429. ** size, or reuses the dummy node if size is zero.
  430. ** The computation for size overflow is in two steps: the first
  431. ** comparison ensures that the shift in the second one does not
  432. ** overflow.
  433. */
  434. static void setnodevector (lua_State *L, Table *t, unsigned int size) {
  435. if (size == 0) { /* no elements to hash part? */
  436. t->node = cast(Node *, dummynode); /* use common 'dummynode' */
  437. t->lsizenode = 0;
  438. setdummy(t); /* signal that it is using dummy node */
  439. }
  440. else {
  441. int i;
  442. int lsize = luaO_ceillog2(size);
  443. if (lsize > MAXHBITS || (1u << lsize) > MAXHSIZE)
  444. luaG_runerror(L, "table overflow");
  445. size = twoto(lsize);
  446. if (lsize <= LLIMFORLAST) /* no 'lastfree' field? */
  447. t->node = luaM_newvector(L, size, Node);
  448. else {
  449. size_t bsize = size * sizeof(Node) + sizeof(Limbox);
  450. char *node = luaM_newblock(L, bsize);
  451. t->node = cast(Node *, node + sizeof(Limbox));
  452. *getlastfree(t) = size; /* all positions are free */
  453. }
  454. t->lsizenode = cast_byte(lsize);
  455. setnodummy(t);
  456. for (i = 0; i < cast_int(size); i++) {
  457. Node *n = gnode(t, i);
  458. gnext(n) = 0;
  459. setnilkey(n);
  460. setempty(gval(n));
  461. }
  462. }
  463. }
  464. /*
  465. ** (Re)insert all elements from the hash part of 'ot' into table 't'.
  466. */
  467. static void reinsert (lua_State *L, Table *ot, Table *t) {
  468. int j;
  469. int size = sizenode(ot);
  470. for (j = 0; j < size; j++) {
  471. Node *old = gnode(ot, j);
  472. if (!isempty(gval(old))) {
  473. /* doesn't need barrier/invalidate cache, as entry was
  474. already present in the table */
  475. TValue k;
  476. getnodekey(L, &k, old);
  477. luaH_set(L, t, &k, gval(old));
  478. }
  479. }
  480. }
  481. /*
  482. ** Exchange the hash part of 't1' and 't2'. (In 'flags', only the
  483. ** dummy bit must be exchanged: The 'isrealasize' is not related
  484. ** to the hash part, and the metamethod bits do not change during
  485. ** a resize, so the "real" table can keep their values.)
  486. */
  487. static void exchangehashpart (Table *t1, Table *t2) {
  488. lu_byte lsizenode = t1->lsizenode;
  489. Node *node = t1->node;
  490. int bitdummy1 = t1->flags & BITDUMMY;
  491. t1->lsizenode = t2->lsizenode;
  492. t1->node = t2->node;
  493. t1->flags = (t1->flags & NOTBITDUMMY) | (t2->flags & BITDUMMY);
  494. t2->lsizenode = lsizenode;
  495. t2->node = node;
  496. t2->flags = (t2->flags & NOTBITDUMMY) | bitdummy1;
  497. }
  498. /*
  499. ** Resize table 't' for the new given sizes. Both allocations (for
  500. ** the hash part and for the array part) can fail, which creates some
  501. ** subtleties. If the first allocation, for the hash part, fails, an
  502. ** error is raised and that is it. Otherwise, it copies the elements from
  503. ** the shrinking part of the array (if it is shrinking) into the new
  504. ** hash. Then it reallocates the array part. If that fails, the table
  505. ** is in its original state; the function frees the new hash part and then
  506. ** raises the allocation error. Otherwise, it sets the new hash part
  507. ** into the table, initializes the new part of the array (if any) with
  508. ** nils and reinserts the elements of the old hash back into the new
  509. ** parts of the table.
  510. */
  511. void luaH_resize (lua_State *L, Table *t, unsigned int newasize,
  512. unsigned int nhsize) {
  513. unsigned int i;
  514. Table newt; /* to keep the new hash part */
  515. unsigned int oldasize = setlimittosize(t);
  516. TValue *newarray;
  517. /* create new hash part with appropriate size into 'newt' */
  518. newt.flags = 0;
  519. setnodevector(L, &newt, nhsize);
  520. if (newasize < oldasize) { /* will array shrink? */
  521. t->alimit = newasize; /* pretend array has new size... */
  522. exchangehashpart(t, &newt); /* and new hash */
  523. /* re-insert into the new hash the elements from vanishing slice */
  524. for (i = newasize; i < oldasize; i++) {
  525. if (!isempty(&t->array[i]))
  526. luaH_setint(L, t, i + 1, &t->array[i]);
  527. }
  528. t->alimit = oldasize; /* restore current size... */
  529. exchangehashpart(t, &newt); /* and hash (in case of errors) */
  530. }
  531. /* allocate new array */
  532. newarray = luaM_reallocvector(L, t->array, oldasize, newasize, TValue);
  533. if (l_unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */
  534. freehash(L, &newt); /* release new hash part */
  535. luaM_error(L); /* raise error (with array unchanged) */
  536. }
  537. /* allocation ok; initialize new part of the array */
  538. exchangehashpart(t, &newt); /* 't' has the new hash ('newt' has the old) */
  539. t->array = newarray; /* set new array part */
  540. t->alimit = newasize;
  541. for (i = oldasize; i < newasize; i++) /* clear new slice of the array */
  542. setempty(&t->array[i]);
  543. /* re-insert elements from old hash part into new parts */
  544. reinsert(L, &newt, t); /* 'newt' now has the old hash */
  545. freehash(L, &newt); /* free old hash part */
  546. }
  547. void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
  548. int nsize = allocsizenode(t);
  549. luaH_resize(L, t, nasize, nsize);
  550. }
  551. /*
  552. ** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
  553. */
  554. static void rehash (lua_State *L, Table *t, const TValue *ek) {
  555. unsigned int asize; /* optimal size for array part */
  556. unsigned int na; /* number of keys in the array part */
  557. unsigned int nums[MAXABITS + 1];
  558. int i;
  559. int totaluse;
  560. for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */
  561. setlimittosize(t);
  562. na = numusearray(t, nums); /* count keys in array part */
  563. totaluse = na; /* all those keys are integer keys */
  564. totaluse += numusehash(t, nums, &na); /* count keys in hash part */
  565. /* count extra key */
  566. if (ttisinteger(ek))
  567. na += countint(ivalue(ek), nums);
  568. totaluse++;
  569. /* compute new size for array part */
  570. asize = computesizes(nums, &na);
  571. /* resize the table to new computed sizes */
  572. luaH_resize(L, t, asize, totaluse - na);
  573. }
  574. /*
  575. ** }=============================================================
  576. */
  577. Table *luaH_new (lua_State *L) {
  578. GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
  579. Table *t = gco2t(o);
  580. t->metatable = NULL;
  581. t->flags = cast_byte(maskflags); /* table has no metamethod fields */
  582. t->array = NULL;
  583. t->alimit = 0;
  584. setnodevector(L, t, 0);
  585. return t;
  586. }
  587. void luaH_free (lua_State *L, Table *t) {
  588. freehash(L, t);
  589. luaM_freearray(L, t->array, luaH_realasize(t));
  590. luaM_free(L, t);
  591. }
  592. static Node *getfreepos (Table *t) {
  593. if (haslastfree(t)) { /* does it have 'lastfree' information? */
  594. /* look for a spot before 'lastfree', updating 'lastfree' */
  595. while (*getlastfree(t) > 0) {
  596. Node *free = gnode(t, --(*getlastfree(t)));
  597. if (keyisnil(free))
  598. return free;
  599. }
  600. }
  601. else { /* no 'lastfree' information */
  602. if (!isdummy(t)) {
  603. int i = sizenode(t);
  604. while (i--) { /* do a linear search */
  605. Node *free = gnode(t, i);
  606. if (keyisnil(free))
  607. return free;
  608. }
  609. }
  610. }
  611. return NULL; /* could not find a free place */
  612. }
  613. /*
  614. ** inserts a new key into a hash table; first, check whether key's main
  615. ** position is free. If not, check whether colliding node is in its main
  616. ** position or not: if it is not, move colliding node to an empty place and
  617. ** put new key in its main position; otherwise (colliding node is in its main
  618. ** position), new key goes to an empty position.
  619. */
  620. void luaH_newkey (lua_State *L, Table *t, const TValue *key, TValue *value) {
  621. Node *mp;
  622. TValue aux;
  623. if (l_unlikely(ttisnil(key)))
  624. luaG_runerror(L, "table index is nil");
  625. else if (ttisfloat(key)) {
  626. lua_Number f = fltvalue(key);
  627. lua_Integer k;
  628. if (luaV_flttointeger(f, &k, F2Ieq)) { /* does key fit in an integer? */
  629. setivalue(&aux, k);
  630. key = &aux; /* insert it as an integer */
  631. }
  632. else if (l_unlikely(luai_numisnan(f)))
  633. luaG_runerror(L, "table index is NaN");
  634. }
  635. if (ttisnil(value))
  636. return; /* do not insert nil values */
  637. mp = mainpositionTV(t, key);
  638. if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */
  639. Node *othern;
  640. Node *f = getfreepos(t); /* get a free place */
  641. if (f == NULL) { /* cannot find a free place? */
  642. rehash(L, t, key); /* grow table */
  643. /* whatever called 'newkey' takes care of TM cache */
  644. luaH_set(L, t, key, value); /* insert key into grown table */
  645. return;
  646. }
  647. lua_assert(!isdummy(t));
  648. othern = mainpositionfromnode(t, mp);
  649. if (othern != mp) { /* is colliding node out of its main position? */
  650. /* yes; move colliding node into free position */
  651. while (othern + gnext(othern) != mp) /* find previous */
  652. othern += gnext(othern);
  653. gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */
  654. *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  655. if (gnext(mp) != 0) {
  656. gnext(f) += cast_int(mp - f); /* correct 'next' */
  657. gnext(mp) = 0; /* now 'mp' is free */
  658. }
  659. setempty(gval(mp));
  660. }
  661. else { /* colliding node is in its own main position */
  662. /* new node will go into free position */
  663. if (gnext(mp) != 0)
  664. gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */
  665. else lua_assert(gnext(f) == 0);
  666. gnext(mp) = cast_int(f - mp);
  667. mp = f;
  668. }
  669. }
  670. setnodekey(L, mp, key);
  671. luaC_barrierback(L, obj2gco(t), key);
  672. lua_assert(isempty(gval(mp)));
  673. setobj2t(L, gval(mp), value);
  674. }
  675. /*
  676. ** Search function for integers. If integer is inside 'alimit', get it
  677. ** directly from the array part. Otherwise, if 'alimit' is not equal to
  678. ** the real size of the array, key still can be in the array part. In
  679. ** this case, try to avoid a call to 'luaH_realasize' when key is just
  680. ** one more than the limit (so that it can be incremented without
  681. ** changing the real size of the array).
  682. */
  683. const TValue *luaH_getint (Table *t, lua_Integer key) {
  684. if (l_castS2U(key) - 1u < t->alimit) /* 'key' in [1, t->alimit]? */
  685. return &t->array[key - 1];
  686. else if (!limitequalsasize(t) && /* key still may be in the array part? */
  687. (l_castS2U(key) == t->alimit + 1 ||
  688. l_castS2U(key) - 1u < luaH_realasize(t))) {
  689. t->alimit = cast_uint(key); /* probably '#t' is here now */
  690. return &t->array[key - 1];
  691. }
  692. else {
  693. Node *n = hashint(t, key);
  694. for (;;) { /* check whether 'key' is somewhere in the chain */
  695. if (keyisinteger(n) && keyival(n) == key)
  696. return gval(n); /* that's it */
  697. else {
  698. int nx = gnext(n);
  699. if (nx == 0) break;
  700. n += nx;
  701. }
  702. }
  703. return &absentkey;
  704. }
  705. }
  706. /*
  707. ** search function for short strings
  708. */
  709. const TValue *luaH_getshortstr (Table *t, TString *key) {
  710. Node *n = hashstr(t, key);
  711. lua_assert(key->tt == LUA_VSHRSTR);
  712. for (;;) { /* check whether 'key' is somewhere in the chain */
  713. if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
  714. return gval(n); /* that's it */
  715. else {
  716. int nx = gnext(n);
  717. if (nx == 0)
  718. return &absentkey; /* not found */
  719. n += nx;
  720. }
  721. }
  722. }
  723. const TValue *luaH_getstr (Table *t, TString *key) {
  724. if (key->tt == LUA_VSHRSTR)
  725. return luaH_getshortstr(t, key);
  726. else { /* for long strings, use generic case */
  727. TValue ko;
  728. setsvalue(cast(lua_State *, NULL), &ko, key);
  729. return getgeneric(t, &ko, 0);
  730. }
  731. }
  732. /*
  733. ** main search function
  734. */
  735. const TValue *luaH_get (Table *t, const TValue *key) {
  736. switch (ttypetag(key)) {
  737. case LUA_VSHRSTR: return luaH_getshortstr(t, tsvalue(key));
  738. case LUA_VNUMINT: return luaH_getint(t, ivalue(key));
  739. case LUA_VNIL: return &absentkey;
  740. case LUA_VNUMFLT: {
  741. lua_Integer k;
  742. if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
  743. return luaH_getint(t, k); /* use specialized version */
  744. /* else... */
  745. } /* FALLTHROUGH */
  746. default:
  747. return getgeneric(t, key, 0);
  748. }
  749. }
  750. /*
  751. ** Finish a raw "set table" operation, where 'slot' is where the value
  752. ** should have been (the result of a previous "get table").
  753. ** Beware: when using this function you probably need to check a GC
  754. ** barrier and invalidate the TM cache.
  755. */
  756. void luaH_finishset (lua_State *L, Table *t, const TValue *key,
  757. const TValue *slot, TValue *value) {
  758. if (isabstkey(slot))
  759. luaH_newkey(L, t, key, value);
  760. else
  761. setobj2t(L, cast(TValue *, slot), value);
  762. }
  763. /*
  764. ** beware: when using this function you probably need to check a GC
  765. ** barrier and invalidate the TM cache.
  766. */
  767. void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) {
  768. const TValue *slot = luaH_get(t, key);
  769. luaH_finishset(L, t, key, slot, value);
  770. }
  771. void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
  772. const TValue *p = luaH_getint(t, key);
  773. if (isabstkey(p)) {
  774. TValue k;
  775. setivalue(&k, key);
  776. luaH_newkey(L, t, &k, value);
  777. }
  778. else
  779. setobj2t(L, cast(TValue *, p), value);
  780. }
  781. /*
  782. ** Try to find a boundary in the hash part of table 't'. From the
  783. ** caller, we know that 'j' is zero or present and that 'j + 1' is
  784. ** present. We want to find a larger key that is absent from the
  785. ** table, so that we can do a binary search between the two keys to
  786. ** find a boundary. We keep doubling 'j' until we get an absent index.
  787. ** If the doubling would overflow, we try LUA_MAXINTEGER. If it is
  788. ** absent, we are ready for the binary search. ('j', being max integer,
  789. ** is larger or equal to 'i', but it cannot be equal because it is
  790. ** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a
  791. ** boundary. ('j + 1' cannot be a present integer key because it is
  792. ** not a valid integer in Lua.)
  793. */
  794. static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
  795. lua_Unsigned i;
  796. if (j == 0) j++; /* the caller ensures 'j + 1' is present */
  797. do {
  798. i = j; /* 'i' is a present index */
  799. if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
  800. j *= 2;
  801. else {
  802. j = LUA_MAXINTEGER;
  803. if (isempty(luaH_getint(t, j))) /* t[j] not present? */
  804. break; /* 'j' now is an absent index */
  805. else /* weird case */
  806. return j; /* well, max integer is a boundary... */
  807. }
  808. } while (!isempty(luaH_getint(t, j))); /* repeat until an absent t[j] */
  809. /* i < j && t[i] present && t[j] absent */
  810. while (j - i > 1u) { /* do a binary search between them */
  811. lua_Unsigned m = (i + j) / 2;
  812. if (isempty(luaH_getint(t, m))) j = m;
  813. else i = m;
  814. }
  815. return i;
  816. }
  817. static unsigned int binsearch (const TValue *array, unsigned int i,
  818. unsigned int j) {
  819. while (j - i > 1u) { /* binary search */
  820. unsigned int m = (i + j) / 2;
  821. if (isempty(&array[m - 1])) j = m;
  822. else i = m;
  823. }
  824. return i;
  825. }
  826. /*
  827. ** Try to find a boundary in table 't'. (A 'boundary' is an integer index
  828. ** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent
  829. ** and 'maxinteger' if t[maxinteger] is present.)
  830. ** (In the next explanation, we use Lua indices, that is, with base 1.
  831. ** The code itself uses base 0 when indexing the array part of the table.)
  832. ** The code starts with 'limit = t->alimit', a position in the array
  833. ** part that may be a boundary.
  834. **
  835. ** (1) If 't[limit]' is empty, there must be a boundary before it.
  836. ** As a common case (e.g., after 't[#t]=nil'), check whether 'limit-1'
  837. ** is present. If so, it is a boundary. Otherwise, do a binary search
  838. ** between 0 and limit to find a boundary. In both cases, try to
  839. ** use this boundary as the new 'alimit', as a hint for the next call.
  840. **
  841. ** (2) If 't[limit]' is not empty and the array has more elements
  842. ** after 'limit', try to find a boundary there. Again, try first
  843. ** the special case (which should be quite frequent) where 'limit+1'
  844. ** is empty, so that 'limit' is a boundary. Otherwise, check the
  845. ** last element of the array part. If it is empty, there must be a
  846. ** boundary between the old limit (present) and the last element
  847. ** (absent), which is found with a binary search. (This boundary always
  848. ** can be a new limit.)
  849. **
  850. ** (3) The last case is when there are no elements in the array part
  851. ** (limit == 0) or its last element (the new limit) is present.
  852. ** In this case, must check the hash part. If there is no hash part
  853. ** or 'limit+1' is absent, 'limit' is a boundary. Otherwise, call
  854. ** 'hash_search' to find a boundary in the hash part of the table.
  855. ** (In those cases, the boundary is not inside the array part, and
  856. ** therefore cannot be used as a new limit.)
  857. */
  858. lua_Unsigned luaH_getn (Table *t) {
  859. unsigned int limit = t->alimit;
  860. if (limit > 0 && isempty(&t->array[limit - 1])) { /* (1)? */
  861. /* there must be a boundary before 'limit' */
  862. if (limit >= 2 && !isempty(&t->array[limit - 2])) {
  863. /* 'limit - 1' is a boundary; can it be a new limit? */
  864. if (ispow2realasize(t) && !ispow2(limit - 1)) {
  865. t->alimit = limit - 1;
  866. setnorealasize(t); /* now 'alimit' is not the real size */
  867. }
  868. return limit - 1;
  869. }
  870. else { /* must search for a boundary in [0, limit] */
  871. unsigned int boundary = binsearch(t->array, 0, limit);
  872. /* can this boundary represent the real size of the array? */
  873. if (ispow2realasize(t) && boundary > luaH_realasize(t) / 2) {
  874. t->alimit = boundary; /* use it as the new limit */
  875. setnorealasize(t);
  876. }
  877. return boundary;
  878. }
  879. }
  880. /* 'limit' is zero or present in table */
  881. if (!limitequalsasize(t)) { /* (2)? */
  882. /* 'limit' > 0 and array has more elements after 'limit' */
  883. if (isempty(&t->array[limit])) /* 'limit + 1' is empty? */
  884. return limit; /* this is the boundary */
  885. /* else, try last element in the array */
  886. limit = luaH_realasize(t);
  887. if (isempty(&t->array[limit - 1])) { /* empty? */
  888. /* there must be a boundary in the array after old limit,
  889. and it must be a valid new limit */
  890. unsigned int boundary = binsearch(t->array, t->alimit, limit);
  891. t->alimit = boundary;
  892. return boundary;
  893. }
  894. /* else, new limit is present in the table; check the hash part */
  895. }
  896. /* (3) 'limit' is the last element and either is zero or present in table */
  897. lua_assert(limit == luaH_realasize(t) &&
  898. (limit == 0 || !isempty(&t->array[limit - 1])));
  899. if (isdummy(t) || isempty(luaH_getint(t, cast(lua_Integer, limit + 1))))
  900. return limit; /* 'limit + 1' is absent */
  901. else /* 'limit + 1' is also present */
  902. return hash_search(t, limit);
  903. }
  904. #if defined(LUA_DEBUG)
  905. /* export these functions for the test library */
  906. Node *luaH_mainposition (const Table *t, const TValue *key) {
  907. return mainpositionTV(t, key);
  908. }
  909. #endif