ltable.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  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. #if (UINT_MAX >> 14) > 3 /* unsigned int has more than 16 bits */
  238. size |= (size >> 16);
  239. #if (UINT_MAX >> 30) > 3
  240. size |= (size >> 32); /* unsigned int has more than 32 bits */
  241. #endif
  242. #endif
  243. size++;
  244. lua_assert(ispow2(size) && size/2 < t->alimit && t->alimit < size);
  245. return size;
  246. }
  247. }
  248. /*
  249. ** Check whether real size of the array is a power of 2.
  250. ** (If it is not, 'alimit' cannot be changed to any other value
  251. ** without changing the real size.)
  252. */
  253. static int ispow2realasize (const Table *t) {
  254. return (!isrealasize(t) || ispow2(t->alimit));
  255. }
  256. static unsigned int setlimittosize (Table *t) {
  257. t->alimit = luaH_realasize(t);
  258. setrealasize(t);
  259. return t->alimit;
  260. }
  261. #define limitasasize(t) check_exp(isrealasize(t), t->alimit)
  262. /*
  263. ** "Generic" get version. (Not that generic: not valid for integers,
  264. ** which may be in array part, nor for floats with integral values.)
  265. ** See explanation about 'deadok' in function 'equalkey'.
  266. */
  267. static const TValue *getgeneric (Table *t, const TValue *key, int deadok) {
  268. Node *n = mainpositionTV(t, key);
  269. for (;;) { /* check whether 'key' is somewhere in the chain */
  270. if (equalkey(key, n, deadok))
  271. return gval(n); /* that's it */
  272. else {
  273. int nx = gnext(n);
  274. if (nx == 0)
  275. return &absentkey; /* not found */
  276. n += nx;
  277. }
  278. }
  279. }
  280. /*
  281. ** returns the index for 'k' if 'k' is an appropriate key to live in
  282. ** the array part of a table, 0 otherwise.
  283. */
  284. static unsigned int arrayindex (lua_Integer k) {
  285. if (l_castS2U(k) - 1u < MAXASIZE) /* 'k' in [1, MAXASIZE]? */
  286. return cast_uint(k); /* 'key' is an appropriate array index */
  287. else
  288. return 0;
  289. }
  290. /*
  291. ** returns the index of a 'key' for table traversals. First goes all
  292. ** elements in the array part, then elements in the hash part. The
  293. ** beginning of a traversal is signaled by 0.
  294. */
  295. static unsigned int findindex (lua_State *L, Table *t, TValue *key,
  296. unsigned int asize) {
  297. unsigned int i;
  298. if (ttisnil(key)) return 0; /* first iteration */
  299. i = ttisinteger(key) ? arrayindex(ivalue(key)) : 0;
  300. if (i - 1u < asize) /* is 'key' inside array part? */
  301. return i; /* yes; that's the index */
  302. else {
  303. const TValue *n = getgeneric(t, key, 1);
  304. if (l_unlikely(isabstkey(n)))
  305. luaG_runerror(L, "invalid key to 'next'"); /* key not found */
  306. i = cast_int(nodefromval(n) - gnode(t, 0)); /* key index in hash table */
  307. /* hash elements are numbered after array ones */
  308. return (i + 1) + asize;
  309. }
  310. }
  311. int luaH_next (lua_State *L, Table *t, StkId key) {
  312. unsigned int asize = luaH_realasize(t);
  313. unsigned int i = findindex(L, t, s2v(key), asize); /* find original key */
  314. for (; i < asize; i++) { /* try first array part */
  315. if (!isempty(&t->array[i])) { /* a non-empty entry? */
  316. setivalue(s2v(key), i + 1);
  317. setobj2s(L, key + 1, &t->array[i]);
  318. return 1;
  319. }
  320. }
  321. for (i -= asize; cast_int(i) < sizenode(t); i++) { /* hash part */
  322. if (!isempty(gval(gnode(t, i)))) { /* a non-empty entry? */
  323. Node *n = gnode(t, i);
  324. getnodekey(L, s2v(key), n);
  325. setobj2s(L, key + 1, gval(n));
  326. return 1;
  327. }
  328. }
  329. return 0; /* no more elements */
  330. }
  331. static void freehash (lua_State *L, Table *t) {
  332. if (!isdummy(t)) {
  333. size_t bsize = sizenode(t) * sizeof(Node); /* 'node' size in bytes */
  334. char *arr = cast_charp(t->node);
  335. if (haslastfree(t)) {
  336. bsize += sizeof(Limbox);
  337. arr -= sizeof(Limbox);
  338. }
  339. luaM_freearray(L, arr, bsize);
  340. }
  341. }
  342. /*
  343. ** {=============================================================
  344. ** Rehash
  345. ** ==============================================================
  346. */
  347. /*
  348. ** Compute the optimal size for the array part of table 't'. 'nums' is a
  349. ** "count array" where 'nums[i]' is the number of integers in the table
  350. ** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of
  351. ** integer keys in the table and leaves with the number of keys that
  352. ** will go to the array part; return the optimal size. (The condition
  353. ** 'twotoi > 0' in the for loop stops the loop if 'twotoi' overflows.)
  354. */
  355. static unsigned int computesizes (unsigned int nums[], unsigned int *pna) {
  356. int i;
  357. unsigned int twotoi; /* 2^i (candidate for optimal size) */
  358. unsigned int a = 0; /* number of elements smaller than 2^i */
  359. unsigned int na = 0; /* number of elements to go to array part */
  360. unsigned int optimal = 0; /* optimal size for array part */
  361. /* loop while keys can fill more than half of total size */
  362. for (i = 0, twotoi = 1;
  363. twotoi > 0 && *pna > twotoi / 2;
  364. i++, twotoi *= 2) {
  365. a += nums[i];
  366. if (a > twotoi/2) { /* more than half elements present? */
  367. optimal = twotoi; /* optimal size (till now) */
  368. na = a; /* all elements up to 'optimal' will go to array part */
  369. }
  370. }
  371. lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal);
  372. *pna = na;
  373. return optimal;
  374. }
  375. static int countint (lua_Integer key, unsigned int *nums) {
  376. unsigned int k = arrayindex(key);
  377. if (k != 0) { /* is 'key' an appropriate array index? */
  378. nums[luaO_ceillog2(k)]++; /* count as such */
  379. return 1;
  380. }
  381. else
  382. return 0;
  383. }
  384. /*
  385. ** Count keys in array part of table 't': Fill 'nums[i]' with
  386. ** number of keys that will go into corresponding slice and return
  387. ** total number of non-nil keys.
  388. */
  389. static unsigned int numusearray (const Table *t, unsigned int *nums) {
  390. int lg;
  391. unsigned int ttlg; /* 2^lg */
  392. unsigned int ause = 0; /* summation of 'nums' */
  393. unsigned int i = 1; /* count to traverse all array keys */
  394. unsigned int asize = limitasasize(t); /* real array size */
  395. /* traverse each slice */
  396. for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
  397. unsigned int lc = 0; /* counter */
  398. unsigned int lim = ttlg;
  399. if (lim > asize) {
  400. lim = asize; /* adjust upper limit */
  401. if (i > lim)
  402. break; /* no more elements to count */
  403. }
  404. /* count elements in range (2^(lg - 1), 2^lg] */
  405. for (; i <= lim; i++) {
  406. if (!isempty(&t->array[i-1]))
  407. lc++;
  408. }
  409. nums[lg] += lc;
  410. ause += lc;
  411. }
  412. return ause;
  413. }
  414. static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) {
  415. int totaluse = 0; /* total number of elements */
  416. int ause = 0; /* elements added to 'nums' (can go to array part) */
  417. int i = sizenode(t);
  418. while (i--) {
  419. Node *n = &t->node[i];
  420. if (!isempty(gval(n))) {
  421. if (keyisinteger(n))
  422. ause += countint(keyival(n), nums);
  423. totaluse++;
  424. }
  425. }
  426. *pna += ause;
  427. return totaluse;
  428. }
  429. /*
  430. ** Creates an array for the hash part of a table with the given
  431. ** size, or reuses the dummy node if size is zero.
  432. ** The computation for size overflow is in two steps: the first
  433. ** comparison ensures that the shift in the second one does not
  434. ** overflow.
  435. */
  436. static void setnodevector (lua_State *L, Table *t, unsigned int size) {
  437. if (size == 0) { /* no elements to hash part? */
  438. t->node = cast(Node *, dummynode); /* use common 'dummynode' */
  439. t->lsizenode = 0;
  440. setdummy(t); /* signal that it is using dummy node */
  441. }
  442. else {
  443. int i;
  444. int lsize = luaO_ceillog2(size);
  445. if (lsize > MAXHBITS || (1u << lsize) > MAXHSIZE)
  446. luaG_runerror(L, "table overflow");
  447. size = twoto(lsize);
  448. if (lsize <= LLIMFORLAST) /* no 'lastfree' field? */
  449. t->node = luaM_newvector(L, size, Node);
  450. else {
  451. size_t bsize = size * sizeof(Node) + sizeof(Limbox);
  452. char *node = luaM_newblock(L, bsize);
  453. t->node = cast(Node *, node + sizeof(Limbox));
  454. *getlastfree(t) = size; /* all positions are free */
  455. }
  456. t->lsizenode = cast_byte(lsize);
  457. setnodummy(t);
  458. for (i = 0; i < cast_int(size); i++) {
  459. Node *n = gnode(t, i);
  460. gnext(n) = 0;
  461. setnilkey(n);
  462. setempty(gval(n));
  463. }
  464. }
  465. }
  466. /*
  467. ** (Re)insert all elements from the hash part of 'ot' into table 't'.
  468. */
  469. static void reinsert (lua_State *L, Table *ot, Table *t) {
  470. int j;
  471. int size = sizenode(ot);
  472. for (j = 0; j < size; j++) {
  473. Node *old = gnode(ot, j);
  474. if (!isempty(gval(old))) {
  475. /* doesn't need barrier/invalidate cache, as entry was
  476. already present in the table */
  477. TValue k;
  478. getnodekey(L, &k, old);
  479. luaH_set(L, t, &k, gval(old));
  480. }
  481. }
  482. }
  483. /*
  484. ** Exchange the hash part of 't1' and 't2'. (In 'flags', only the
  485. ** dummy bit must be exchanged: The 'isrealasize' is not related
  486. ** to the hash part, and the metamethod bits do not change during
  487. ** a resize, so the "real" table can keep their values.)
  488. */
  489. static void exchangehashpart (Table *t1, Table *t2) {
  490. lu_byte lsizenode = t1->lsizenode;
  491. Node *node = t1->node;
  492. int bitdummy1 = t1->flags & BITDUMMY;
  493. t1->lsizenode = t2->lsizenode;
  494. t1->node = t2->node;
  495. t1->flags = (t1->flags & NOTBITDUMMY) | (t2->flags & BITDUMMY);
  496. t2->lsizenode = lsizenode;
  497. t2->node = node;
  498. t2->flags = (t2->flags & NOTBITDUMMY) | bitdummy1;
  499. }
  500. /*
  501. ** Resize table 't' for the new given sizes. Both allocations (for
  502. ** the hash part and for the array part) can fail, which creates some
  503. ** subtleties. If the first allocation, for the hash part, fails, an
  504. ** error is raised and that is it. Otherwise, it copies the elements from
  505. ** the shrinking part of the array (if it is shrinking) into the new
  506. ** hash. Then it reallocates the array part. If that fails, the table
  507. ** is in its original state; the function frees the new hash part and then
  508. ** raises the allocation error. Otherwise, it sets the new hash part
  509. ** into the table, initializes the new part of the array (if any) with
  510. ** nils and reinserts the elements of the old hash back into the new
  511. ** parts of the table.
  512. */
  513. void luaH_resize (lua_State *L, Table *t, unsigned int newasize,
  514. unsigned int nhsize) {
  515. unsigned int i;
  516. Table newt; /* to keep the new hash part */
  517. unsigned int oldasize = setlimittosize(t);
  518. TValue *newarray;
  519. /* create new hash part with appropriate size into 'newt' */
  520. newt.flags = 0;
  521. setnodevector(L, &newt, nhsize);
  522. if (newasize < oldasize) { /* will array shrink? */
  523. t->alimit = newasize; /* pretend array has new size... */
  524. exchangehashpart(t, &newt); /* and new hash */
  525. /* re-insert into the new hash the elements from vanishing slice */
  526. for (i = newasize; i < oldasize; i++) {
  527. if (!isempty(&t->array[i]))
  528. luaH_setint(L, t, i + 1, &t->array[i]);
  529. }
  530. t->alimit = oldasize; /* restore current size... */
  531. exchangehashpart(t, &newt); /* and hash (in case of errors) */
  532. }
  533. /* allocate new array */
  534. newarray = luaM_reallocvector(L, t->array, oldasize, newasize, TValue);
  535. if (l_unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */
  536. freehash(L, &newt); /* release new hash part */
  537. luaM_error(L); /* raise error (with array unchanged) */
  538. }
  539. /* allocation ok; initialize new part of the array */
  540. exchangehashpart(t, &newt); /* 't' has the new hash ('newt' has the old) */
  541. t->array = newarray; /* set new array part */
  542. t->alimit = newasize;
  543. for (i = oldasize; i < newasize; i++) /* clear new slice of the array */
  544. setempty(&t->array[i]);
  545. /* re-insert elements from old hash part into new parts */
  546. reinsert(L, &newt, t); /* 'newt' now has the old hash */
  547. freehash(L, &newt); /* free old hash part */
  548. }
  549. void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
  550. int nsize = allocsizenode(t);
  551. luaH_resize(L, t, nasize, nsize);
  552. }
  553. /*
  554. ** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
  555. */
  556. static void rehash (lua_State *L, Table *t, const TValue *ek) {
  557. unsigned int asize; /* optimal size for array part */
  558. unsigned int na; /* number of keys in the array part */
  559. unsigned int nums[MAXABITS + 1];
  560. int i;
  561. int totaluse;
  562. for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */
  563. setlimittosize(t);
  564. na = numusearray(t, nums); /* count keys in array part */
  565. totaluse = na; /* all those keys are integer keys */
  566. totaluse += numusehash(t, nums, &na); /* count keys in hash part */
  567. /* count extra key */
  568. if (ttisinteger(ek))
  569. na += countint(ivalue(ek), nums);
  570. totaluse++;
  571. /* compute new size for array part */
  572. asize = computesizes(nums, &na);
  573. /* resize the table to new computed sizes */
  574. luaH_resize(L, t, asize, totaluse - na);
  575. }
  576. /*
  577. ** }=============================================================
  578. */
  579. Table *luaH_new (lua_State *L) {
  580. GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
  581. Table *t = gco2t(o);
  582. t->metatable = NULL;
  583. t->flags = cast_byte(maskflags); /* table has no metamethod fields */
  584. t->array = NULL;
  585. t->alimit = 0;
  586. setnodevector(L, t, 0);
  587. return t;
  588. }
  589. void luaH_free (lua_State *L, Table *t) {
  590. freehash(L, t);
  591. luaM_freearray(L, t->array, luaH_realasize(t));
  592. luaM_free(L, t);
  593. }
  594. static Node *getfreepos (Table *t) {
  595. if (haslastfree(t)) { /* does it have 'lastfree' information? */
  596. /* look for a spot before 'lastfree', updating 'lastfree' */
  597. while (*getlastfree(t) > 0) {
  598. Node *free = gnode(t, --(*getlastfree(t)));
  599. if (keyisnil(free))
  600. return free;
  601. }
  602. }
  603. else { /* no 'lastfree' information */
  604. if (!isdummy(t)) {
  605. int i = sizenode(t);
  606. while (i--) { /* do a linear search */
  607. Node *free = gnode(t, i);
  608. if (keyisnil(free))
  609. return free;
  610. }
  611. }
  612. }
  613. return NULL; /* could not find a free place */
  614. }
  615. /*
  616. ** inserts a new key into a hash table; first, check whether key's main
  617. ** position is free. If not, check whether colliding node is in its main
  618. ** position or not: if it is not, move colliding node to an empty place and
  619. ** put new key in its main position; otherwise (colliding node is in its main
  620. ** position), new key goes to an empty position.
  621. */
  622. static void luaH_newkey (lua_State *L, Table *t, const TValue *key,
  623. TValue *value) {
  624. Node *mp;
  625. TValue aux;
  626. if (l_unlikely(ttisnil(key)))
  627. luaG_runerror(L, "table index is nil");
  628. else if (ttisfloat(key)) {
  629. lua_Number f = fltvalue(key);
  630. lua_Integer k;
  631. if (luaV_flttointeger(f, &k, F2Ieq)) { /* does key fit in an integer? */
  632. setivalue(&aux, k);
  633. key = &aux; /* insert it as an integer */
  634. }
  635. else if (l_unlikely(luai_numisnan(f)))
  636. luaG_runerror(L, "table index is NaN");
  637. }
  638. if (ttisnil(value))
  639. return; /* do not insert nil values */
  640. mp = mainpositionTV(t, key);
  641. if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */
  642. Node *othern;
  643. Node *f = getfreepos(t); /* get a free place */
  644. if (f == NULL) { /* cannot find a free place? */
  645. rehash(L, t, key); /* grow table */
  646. /* whatever called 'newkey' takes care of TM cache */
  647. luaH_set(L, t, key, value); /* insert key into grown table */
  648. return;
  649. }
  650. lua_assert(!isdummy(t));
  651. othern = mainpositionfromnode(t, mp);
  652. if (othern != mp) { /* is colliding node out of its main position? */
  653. /* yes; move colliding node into free position */
  654. while (othern + gnext(othern) != mp) /* find previous */
  655. othern += gnext(othern);
  656. gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */
  657. *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  658. if (gnext(mp) != 0) {
  659. gnext(f) += cast_int(mp - f); /* correct 'next' */
  660. gnext(mp) = 0; /* now 'mp' is free */
  661. }
  662. setempty(gval(mp));
  663. }
  664. else { /* colliding node is in its own main position */
  665. /* new node will go into free position */
  666. if (gnext(mp) != 0)
  667. gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */
  668. else lua_assert(gnext(f) == 0);
  669. gnext(mp) = cast_int(f - mp);
  670. mp = f;
  671. }
  672. }
  673. setnodekey(L, mp, key);
  674. luaC_barrierback(L, obj2gco(t), key);
  675. lua_assert(isempty(gval(mp)));
  676. setobj2t(L, gval(mp), value);
  677. }
  678. /*
  679. ** Search function for integers. If integer is inside 'alimit', get it
  680. ** directly from the array part. Otherwise, if 'alimit' is not equal to
  681. ** the real size of the array, key still can be in the array part. In
  682. ** this case, try to avoid a call to 'luaH_realasize' when key is just
  683. ** one more than the limit (so that it can be incremented without
  684. ** changing the real size of the array).
  685. */
  686. const TValue *luaH_getint (Table *t, lua_Integer key) {
  687. if (l_castS2U(key) - 1u < t->alimit) /* 'key' in [1, t->alimit]? */
  688. return &t->array[key - 1];
  689. else if (!limitequalsasize(t) && /* key still may be in the array part? */
  690. (l_castS2U(key) == t->alimit + 1 ||
  691. l_castS2U(key) - 1u < luaH_realasize(t))) {
  692. t->alimit = cast_uint(key); /* probably '#t' is here now */
  693. return &t->array[key - 1];
  694. }
  695. else {
  696. Node *n = hashint(t, key);
  697. for (;;) { /* check whether 'key' is somewhere in the chain */
  698. if (keyisinteger(n) && keyival(n) == key)
  699. return gval(n); /* that's it */
  700. else {
  701. int nx = gnext(n);
  702. if (nx == 0) break;
  703. n += nx;
  704. }
  705. }
  706. return &absentkey;
  707. }
  708. }
  709. /*
  710. ** search function for short strings
  711. */
  712. const TValue *luaH_getshortstr (Table *t, TString *key) {
  713. Node *n = hashstr(t, key);
  714. lua_assert(key->tt == LUA_VSHRSTR);
  715. for (;;) { /* check whether 'key' is somewhere in the chain */
  716. if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
  717. return gval(n); /* that's it */
  718. else {
  719. int nx = gnext(n);
  720. if (nx == 0)
  721. return &absentkey; /* not found */
  722. n += nx;
  723. }
  724. }
  725. }
  726. const TValue *luaH_getstr (Table *t, TString *key) {
  727. if (key->tt == LUA_VSHRSTR)
  728. return luaH_getshortstr(t, key);
  729. else { /* for long strings, use generic case */
  730. TValue ko;
  731. setsvalue(cast(lua_State *, NULL), &ko, key);
  732. return getgeneric(t, &ko, 0);
  733. }
  734. }
  735. /*
  736. ** main search function
  737. */
  738. const TValue *luaH_get (Table *t, const TValue *key) {
  739. switch (ttypetag(key)) {
  740. case LUA_VSHRSTR: return luaH_getshortstr(t, tsvalue(key));
  741. case LUA_VNUMINT: return luaH_getint(t, ivalue(key));
  742. case LUA_VNIL: return &absentkey;
  743. case LUA_VNUMFLT: {
  744. lua_Integer k;
  745. if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
  746. return luaH_getint(t, k); /* use specialized version */
  747. /* else... */
  748. } /* FALLTHROUGH */
  749. default:
  750. return getgeneric(t, key, 0);
  751. }
  752. }
  753. /*
  754. ** Finish a raw "set table" operation, where 'slot' is where the value
  755. ** should have been (the result of a previous "get table").
  756. ** Beware: when using this function you probably need to check a GC
  757. ** barrier and invalidate the TM cache.
  758. */
  759. void luaH_finishset (lua_State *L, Table *t, const TValue *key,
  760. const TValue *slot, TValue *value) {
  761. if (isabstkey(slot))
  762. luaH_newkey(L, t, key, value);
  763. else
  764. setobj2t(L, cast(TValue *, slot), value);
  765. }
  766. /*
  767. ** beware: when using this function you probably need to check a GC
  768. ** barrier and invalidate the TM cache.
  769. */
  770. void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) {
  771. const TValue *slot = luaH_get(t, key);
  772. luaH_finishset(L, t, key, slot, value);
  773. }
  774. void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
  775. const TValue *p = luaH_getint(t, key);
  776. if (isabstkey(p)) {
  777. TValue k;
  778. setivalue(&k, key);
  779. luaH_newkey(L, t, &k, value);
  780. }
  781. else
  782. setobj2t(L, cast(TValue *, p), value);
  783. }
  784. /*
  785. ** Try to find a boundary in the hash part of table 't'. From the
  786. ** caller, we know that 'j' is zero or present and that 'j + 1' is
  787. ** present. We want to find a larger key that is absent from the
  788. ** table, so that we can do a binary search between the two keys to
  789. ** find a boundary. We keep doubling 'j' until we get an absent index.
  790. ** If the doubling would overflow, we try LUA_MAXINTEGER. If it is
  791. ** absent, we are ready for the binary search. ('j', being max integer,
  792. ** is larger or equal to 'i', but it cannot be equal because it is
  793. ** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a
  794. ** boundary. ('j + 1' cannot be a present integer key because it is
  795. ** not a valid integer in Lua.)
  796. */
  797. static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
  798. lua_Unsigned i;
  799. if (j == 0) j++; /* the caller ensures 'j + 1' is present */
  800. do {
  801. i = j; /* 'i' is a present index */
  802. if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
  803. j *= 2;
  804. else {
  805. j = LUA_MAXINTEGER;
  806. if (isempty(luaH_getint(t, j))) /* t[j] not present? */
  807. break; /* 'j' now is an absent index */
  808. else /* weird case */
  809. return j; /* well, max integer is a boundary... */
  810. }
  811. } while (!isempty(luaH_getint(t, j))); /* repeat until an absent t[j] */
  812. /* i < j && t[i] present && t[j] absent */
  813. while (j - i > 1u) { /* do a binary search between them */
  814. lua_Unsigned m = (i + j) / 2;
  815. if (isempty(luaH_getint(t, m))) j = m;
  816. else i = m;
  817. }
  818. return i;
  819. }
  820. static unsigned int binsearch (const TValue *array, unsigned int i,
  821. unsigned int j) {
  822. while (j - i > 1u) { /* binary search */
  823. unsigned int m = (i + j) / 2;
  824. if (isempty(&array[m - 1])) j = m;
  825. else i = m;
  826. }
  827. return i;
  828. }
  829. /*
  830. ** Try to find a boundary in table 't'. (A 'boundary' is an integer index
  831. ** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent
  832. ** and 'maxinteger' if t[maxinteger] is present.)
  833. ** (In the next explanation, we use Lua indices, that is, with base 1.
  834. ** The code itself uses base 0 when indexing the array part of the table.)
  835. ** The code starts with 'limit = t->alimit', a position in the array
  836. ** part that may be a boundary.
  837. **
  838. ** (1) If 't[limit]' is empty, there must be a boundary before it.
  839. ** As a common case (e.g., after 't[#t]=nil'), check whether 'limit-1'
  840. ** is present. If so, it is a boundary. Otherwise, do a binary search
  841. ** between 0 and limit to find a boundary. In both cases, try to
  842. ** use this boundary as the new 'alimit', as a hint for the next call.
  843. **
  844. ** (2) If 't[limit]' is not empty and the array has more elements
  845. ** after 'limit', try to find a boundary there. Again, try first
  846. ** the special case (which should be quite frequent) where 'limit+1'
  847. ** is empty, so that 'limit' is a boundary. Otherwise, check the
  848. ** last element of the array part. If it is empty, there must be a
  849. ** boundary between the old limit (present) and the last element
  850. ** (absent), which is found with a binary search. (This boundary always
  851. ** can be a new limit.)
  852. **
  853. ** (3) The last case is when there are no elements in the array part
  854. ** (limit == 0) or its last element (the new limit) is present.
  855. ** In this case, must check the hash part. If there is no hash part
  856. ** or 'limit+1' is absent, 'limit' is a boundary. Otherwise, call
  857. ** 'hash_search' to find a boundary in the hash part of the table.
  858. ** (In those cases, the boundary is not inside the array part, and
  859. ** therefore cannot be used as a new limit.)
  860. */
  861. lua_Unsigned luaH_getn (Table *t) {
  862. unsigned int limit = t->alimit;
  863. if (limit > 0 && isempty(&t->array[limit - 1])) { /* (1)? */
  864. /* there must be a boundary before 'limit' */
  865. if (limit >= 2 && !isempty(&t->array[limit - 2])) {
  866. /* 'limit - 1' is a boundary; can it be a new limit? */
  867. if (ispow2realasize(t) && !ispow2(limit - 1)) {
  868. t->alimit = limit - 1;
  869. setnorealasize(t); /* now 'alimit' is not the real size */
  870. }
  871. return limit - 1;
  872. }
  873. else { /* must search for a boundary in [0, limit] */
  874. unsigned int boundary = binsearch(t->array, 0, limit);
  875. /* can this boundary represent the real size of the array? */
  876. if (ispow2realasize(t) && boundary > luaH_realasize(t) / 2) {
  877. t->alimit = boundary; /* use it as the new limit */
  878. setnorealasize(t);
  879. }
  880. return boundary;
  881. }
  882. }
  883. /* 'limit' is zero or present in table */
  884. if (!limitequalsasize(t)) { /* (2)? */
  885. /* 'limit' > 0 and array has more elements after 'limit' */
  886. if (isempty(&t->array[limit])) /* 'limit + 1' is empty? */
  887. return limit; /* this is the boundary */
  888. /* else, try last element in the array */
  889. limit = luaH_realasize(t);
  890. if (isempty(&t->array[limit - 1])) { /* empty? */
  891. /* there must be a boundary in the array after old limit,
  892. and it must be a valid new limit */
  893. unsigned int boundary = binsearch(t->array, t->alimit, limit);
  894. t->alimit = boundary;
  895. return boundary;
  896. }
  897. /* else, new limit is present in the table; check the hash part */
  898. }
  899. /* (3) 'limit' is the last element and either is zero or present in table */
  900. lua_assert(limit == luaH_realasize(t) &&
  901. (limit == 0 || !isempty(&t->array[limit - 1])));
  902. if (isdummy(t) || isempty(luaH_getint(t, cast(lua_Integer, limit + 1))))
  903. return limit; /* 'limit + 1' is absent */
  904. else /* 'limit + 1' is also present */
  905. return hash_search(t, limit);
  906. }
  907. #if defined(LUA_DEBUG)
  908. /* export these functions for the test library */
  909. Node *luaH_mainposition (const Table *t, const TValue *key) {
  910. return mainpositionTV(t, key);
  911. }
  912. #endif