ltable.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341
  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 <string.h>
  24. #include "lua.h"
  25. #include "ldebug.h"
  26. #include "ldo.h"
  27. #include "lgc.h"
  28. #include "lmem.h"
  29. #include "lobject.h"
  30. #include "lstate.h"
  31. #include "lstring.h"
  32. #include "ltable.h"
  33. #include "lvm.h"
  34. /*
  35. ** Only tables with hash parts larger than 2^LIMFORLAST has a 'lastfree'
  36. ** field that optimizes finding a free slot. That field is stored just
  37. ** before the array of nodes, in the same block. Smaller tables do a
  38. ** complete search when looking for a free slot.
  39. */
  40. #define LIMFORLAST 2 /* log2 of real limit */
  41. /*
  42. ** The union 'Limbox' stores 'lastfree' and ensures that what follows it
  43. ** is properly aligned to store a Node.
  44. */
  45. typedef struct { Node *dummy; Node follows_pNode; } Limbox_aux;
  46. typedef union {
  47. Node *lastfree;
  48. char padding[offsetof(Limbox_aux, follows_pNode)];
  49. } Limbox;
  50. #define haslastfree(t) ((t)->lsizenode > LIMFORLAST)
  51. #define getlastfree(t) ((cast(Limbox *, (t)->node) - 1)->lastfree)
  52. /*
  53. ** MAXABITS is the largest integer such that 2^MAXABITS fits in an
  54. ** unsigned int.
  55. */
  56. #define MAXABITS cast_int(sizeof(int) * CHAR_BIT - 1)
  57. /*
  58. ** MAXASIZEB is the maximum number of elements in the array part such
  59. ** that the size of the array fits in 'size_t'.
  60. */
  61. #define MAXASIZEB (MAX_SIZET/(sizeof(Value) + 1))
  62. /*
  63. ** MAXASIZE is the maximum size of the array part. It is the minimum
  64. ** between 2^MAXABITS and MAXASIZEB.
  65. */
  66. #define MAXASIZE \
  67. (((1u << MAXABITS) < MAXASIZEB) ? (1u << MAXABITS) : cast_uint(MAXASIZEB))
  68. /*
  69. ** MAXHBITS is the largest integer such that 2^MAXHBITS fits in a
  70. ** signed int.
  71. */
  72. #define MAXHBITS (MAXABITS - 1)
  73. /*
  74. ** MAXHSIZE is the maximum size of the hash part. It is the minimum
  75. ** between 2^MAXHBITS and the maximum size such that, measured in bytes,
  76. ** it fits in a 'size_t'.
  77. */
  78. #define MAXHSIZE luaM_limitN(1u << MAXHBITS, Node)
  79. /*
  80. ** When the original hash value is good, hashing by a power of 2
  81. ** avoids the cost of '%'.
  82. */
  83. #define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))
  84. /*
  85. ** for other types, it is better to avoid modulo by power of 2, as
  86. ** they can have many 2 factors.
  87. */
  88. #define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1u)|1u))))
  89. #define hashstr(t,str) hashpow2(t, (str)->hash)
  90. #define hashboolean(t,p) hashpow2(t, p)
  91. #define hashpointer(t,p) hashmod(t, point2uint(p))
  92. #define dummynode (&dummynode_)
  93. static const Node dummynode_ = {
  94. {{NULL}, LUA_VEMPTY, /* value's value and type */
  95. LUA_VNIL, 0, {NULL}} /* key type, next, and key value */
  96. };
  97. static const TValue absentkey = {ABSTKEYCONSTANT};
  98. /*
  99. ** Hash for integers. To allow a good hash, use the remainder operator
  100. ** ('%'). If integer fits as a non-negative int, compute an int
  101. ** remainder, which is faster. Otherwise, use an unsigned-integer
  102. ** remainder, which uses all bits and ensures a non-negative result.
  103. */
  104. static Node *hashint (const Table *t, lua_Integer i) {
  105. lua_Unsigned ui = l_castS2U(i);
  106. if (ui <= cast_uint(INT_MAX))
  107. return gnode(t, cast_int(ui) % cast_int((sizenode(t)-1) | 1));
  108. else
  109. return hashmod(t, ui);
  110. }
  111. /*
  112. ** Hash for floating-point numbers.
  113. ** The main computation should be just
  114. ** n = frexp(n, &i); return (n * INT_MAX) + i
  115. ** but there are some numerical subtleties.
  116. ** In a two-complement representation, INT_MAX does not has an exact
  117. ** representation as a float, but INT_MIN does; because the absolute
  118. ** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the
  119. ** absolute value of the product 'frexp * -INT_MIN' is smaller or equal
  120. ** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when
  121. ** adding 'i'; the use of '~u' (instead of '-u') avoids problems with
  122. ** INT_MIN.
  123. */
  124. #if !defined(l_hashfloat)
  125. static unsigned l_hashfloat (lua_Number n) {
  126. int i;
  127. lua_Integer ni;
  128. n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN);
  129. if (!lua_numbertointeger(n, &ni)) { /* is 'n' inf/-inf/NaN? */
  130. lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL));
  131. return 0;
  132. }
  133. else { /* normal case */
  134. unsigned int u = cast_uint(i) + cast_uint(ni);
  135. return (u <= cast_uint(INT_MAX) ? u : ~u);
  136. }
  137. }
  138. #endif
  139. /*
  140. ** returns the 'main' position of an element in a table (that is,
  141. ** the index of its hash value).
  142. */
  143. static Node *mainpositionTV (const Table *t, const TValue *key) {
  144. switch (ttypetag(key)) {
  145. case LUA_VNUMINT: {
  146. lua_Integer i = ivalue(key);
  147. return hashint(t, i);
  148. }
  149. case LUA_VNUMFLT: {
  150. lua_Number n = fltvalue(key);
  151. return hashmod(t, l_hashfloat(n));
  152. }
  153. case LUA_VSHRSTR: {
  154. TString *ts = tsvalue(key);
  155. return hashstr(t, ts);
  156. }
  157. case LUA_VLNGSTR: {
  158. TString *ts = tsvalue(key);
  159. return hashpow2(t, luaS_hashlongstr(ts));
  160. }
  161. case LUA_VFALSE:
  162. return hashboolean(t, 0);
  163. case LUA_VTRUE:
  164. return hashboolean(t, 1);
  165. case LUA_VLIGHTUSERDATA: {
  166. void *p = pvalue(key);
  167. return hashpointer(t, p);
  168. }
  169. case LUA_VLCF: {
  170. lua_CFunction f = fvalue(key);
  171. return hashpointer(t, f);
  172. }
  173. default: {
  174. GCObject *o = gcvalue(key);
  175. return hashpointer(t, o);
  176. }
  177. }
  178. }
  179. l_sinline Node *mainpositionfromnode (const Table *t, Node *nd) {
  180. TValue key;
  181. getnodekey(cast(lua_State *, NULL), &key, nd);
  182. return mainpositionTV(t, &key);
  183. }
  184. /*
  185. ** Check whether key 'k1' is equal to the key in node 'n2'. This
  186. ** equality is raw, so there are no metamethods. Floats with integer
  187. ** values have been normalized, so integers cannot be equal to
  188. ** floats. It is assumed that 'eqshrstr' is simply pointer equality, so
  189. ** that short strings are handled in the default case.
  190. ** A true 'deadok' means to accept dead keys as equal to their original
  191. ** values. All dead keys are compared in the default case, by pointer
  192. ** identity. (Only collectable objects can produce dead keys.) Note that
  193. ** dead long strings are also compared by identity.
  194. ** Once a key is dead, its corresponding value may be collected, and
  195. ** then another value can be created with the same address. If this
  196. ** other value is given to 'next', 'equalkey' will signal a false
  197. ** positive. In a regular traversal, this situation should never happen,
  198. ** as all keys given to 'next' came from the table itself, and therefore
  199. ** could not have been collected. Outside a regular traversal, we
  200. ** have garbage in, garbage out. What is relevant is that this false
  201. ** positive does not break anything. (In particular, 'next' will return
  202. ** some other valid item on the table or nil.)
  203. */
  204. static int equalkey (const TValue *k1, const Node *n2, int deadok) {
  205. if ((rawtt(k1) != keytt(n2)) && /* not the same variants? */
  206. !(deadok && keyisdead(n2) && iscollectable(k1)))
  207. return 0; /* cannot be same key */
  208. switch (keytt(n2)) {
  209. case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE:
  210. return 1;
  211. case LUA_VNUMINT:
  212. return (ivalue(k1) == keyival(n2));
  213. case LUA_VNUMFLT:
  214. return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2)));
  215. case LUA_VLIGHTUSERDATA:
  216. return pvalue(k1) == pvalueraw(keyval(n2));
  217. case LUA_VLCF:
  218. return fvalue(k1) == fvalueraw(keyval(n2));
  219. case ctb(LUA_VLNGSTR):
  220. return luaS_eqlngstr(tsvalue(k1), keystrval(n2));
  221. default:
  222. return gcvalue(k1) == gcvalueraw(keyval(n2));
  223. }
  224. }
  225. /*
  226. ** True if value of 'alimit' is equal to the real size of the array
  227. ** part of table 't'. (Otherwise, the array part must be larger than
  228. ** 'alimit'.)
  229. */
  230. #define limitequalsasize(t) (isrealasize(t) || ispow2((t)->alimit))
  231. /*
  232. ** Returns the real size of the 'array' array
  233. */
  234. unsigned int luaH_realasize (const Table *t) {
  235. if (limitequalsasize(t))
  236. return t->alimit; /* this is the size */
  237. else {
  238. unsigned int size = t->alimit;
  239. /* compute the smallest power of 2 not smaller than 'size' */
  240. size |= (size >> 1);
  241. size |= (size >> 2);
  242. size |= (size >> 4);
  243. size |= (size >> 8);
  244. #if (UINT_MAX >> 14) > 3 /* unsigned int has more than 16 bits */
  245. size |= (size >> 16);
  246. #if (UINT_MAX >> 30) > 3
  247. size |= (size >> 32); /* unsigned int has more than 32 bits */
  248. #endif
  249. #endif
  250. size++;
  251. lua_assert(ispow2(size) && size/2 < t->alimit && t->alimit < size);
  252. return size;
  253. }
  254. }
  255. /*
  256. ** Check whether real size of the array is a power of 2.
  257. ** (If it is not, 'alimit' cannot be changed to any other value
  258. ** without changing the real size.)
  259. */
  260. static int ispow2realasize (const Table *t) {
  261. return (!isrealasize(t) || ispow2(t->alimit));
  262. }
  263. static unsigned int setlimittosize (Table *t) {
  264. t->alimit = luaH_realasize(t);
  265. setrealasize(t);
  266. return t->alimit;
  267. }
  268. #define limitasasize(t) check_exp(isrealasize(t), t->alimit)
  269. /*
  270. ** "Generic" get version. (Not that generic: not valid for integers,
  271. ** which may be in array part, nor for floats with integral values.)
  272. ** See explanation about 'deadok' in function 'equalkey'.
  273. */
  274. static const TValue *getgeneric (Table *t, const TValue *key, int deadok) {
  275. Node *n = mainpositionTV(t, key);
  276. for (;;) { /* check whether 'key' is somewhere in the chain */
  277. if (equalkey(key, n, deadok))
  278. return gval(n); /* that's it */
  279. else {
  280. int nx = gnext(n);
  281. if (nx == 0)
  282. return &absentkey; /* not found */
  283. n += nx;
  284. }
  285. }
  286. }
  287. /*
  288. ** returns the index for 'k' if 'k' is an appropriate key to live in
  289. ** the array part of a table, 0 otherwise.
  290. */
  291. static unsigned int arrayindex (lua_Integer k) {
  292. if (l_castS2U(k) - 1u < MAXASIZE) /* 'k' in [1, MAXASIZE]? */
  293. return cast_uint(k); /* 'key' is an appropriate array index */
  294. else
  295. return 0;
  296. }
  297. /*
  298. ** returns the index of a 'key' for table traversals. First goes all
  299. ** elements in the array part, then elements in the hash part. The
  300. ** beginning of a traversal is signaled by 0.
  301. */
  302. static unsigned findindex (lua_State *L, Table *t, TValue *key,
  303. unsigned asize) {
  304. unsigned int i;
  305. if (ttisnil(key)) return 0; /* first iteration */
  306. i = ttisinteger(key) ? arrayindex(ivalue(key)) : 0;
  307. if (i - 1u < asize) /* is 'key' inside array part? */
  308. return i; /* yes; that's the index */
  309. else {
  310. const TValue *n = getgeneric(t, key, 1);
  311. if (l_unlikely(isabstkey(n)))
  312. luaG_runerror(L, "invalid key to 'next'"); /* key not found */
  313. i = cast_uint(nodefromval(n) - gnode(t, 0)); /* key index in hash table */
  314. /* hash elements are numbered after array ones */
  315. return (i + 1) + asize;
  316. }
  317. }
  318. int luaH_next (lua_State *L, Table *t, StkId key) {
  319. unsigned int asize = luaH_realasize(t);
  320. unsigned int i = findindex(L, t, s2v(key), asize); /* find original key */
  321. for (; i < asize; i++) { /* try first array part */
  322. lu_byte tag = *getArrTag(t, i);
  323. if (!tagisempty(tag)) { /* a non-empty entry? */
  324. setivalue(s2v(key), cast_int(i) + 1);
  325. farr2val(t, i, tag, s2v(key + 1));
  326. return 1;
  327. }
  328. }
  329. for (i -= asize; i < sizenode(t); i++) { /* hash part */
  330. if (!isempty(gval(gnode(t, i)))) { /* a non-empty entry? */
  331. Node *n = gnode(t, i);
  332. getnodekey(L, s2v(key), n);
  333. setobj2s(L, key + 1, gval(n));
  334. return 1;
  335. }
  336. }
  337. return 0; /* no more elements */
  338. }
  339. static void freehash (lua_State *L, Table *t) {
  340. if (!isdummy(t)) {
  341. /* 'node' size in bytes */
  342. size_t bsize = cast_sizet(sizenode(t)) * sizeof(Node);
  343. char *arr = cast_charp(t->node);
  344. if (haslastfree(t)) {
  345. bsize += sizeof(Limbox);
  346. arr -= sizeof(Limbox);
  347. }
  348. luaM_freearray(L, arr, bsize);
  349. }
  350. }
  351. /*
  352. ** Check whether an integer key is in the array part. If 'alimit' is
  353. ** not the real size of the array, the key still can be in the array
  354. ** part. In this case, do the "Xmilia trick" to check whether 'key-1'
  355. ** is smaller than the real size.
  356. ** The trick works as follow: let 'p' be the integer such that
  357. ** '2^(p+1) >= alimit > 2^p', or '2^(p+1) > alimit-1 >= 2^p'. That is,
  358. ** 'p' is the highest 1-bit in 'alimit-1', and 2^(p+1) is the real size
  359. ** of the array. What we have to check becomes 'key-1 < 2^(p+1)'. We
  360. ** compute '(key-1) & ~(alimit-1)', which we call 'res'; it will have
  361. ** the 'p' bit cleared. (It may also clear other bits smaller than 'p',
  362. ** but no bit higher than 'p'.) If the key is outside the array, that
  363. ** is, 'key-1 >= 2^(p+1)', then 'res' will have some 1-bit higher than
  364. ** 'p', therefore it will be larger or equal to 'alimit', and the check
  365. ** will fail. If 'key-1 < 2^(p+1)', then 'res' has no 1-bit higher than
  366. ** 'p', and as the bit 'p' itself was cleared, 'res' will be smaller
  367. ** than 2^p, therefore smaller than 'alimit', and the check succeeds.
  368. ** As special cases, when 'alimit' is 0 the condition is trivially false,
  369. ** and when 'alimit' is 1 the condition simplifies to 'key-1 < alimit'.
  370. ** If key is 0 or negative, 'res' will have its higher bit on, so that
  371. ** it cannot be smaller than 'alimit'.
  372. */
  373. static int keyinarray (Table *t, lua_Integer key) {
  374. lua_Unsigned alimit = t->alimit;
  375. if (l_castS2U(key) - 1u < alimit) /* 'key' in [1, t->alimit]? */
  376. return 1;
  377. else if (!isrealasize(t) && /* key still may be in the array part? */
  378. (((l_castS2U(key) - 1u) & ~(alimit - 1u)) < alimit)) {
  379. t->alimit = cast_uint(key); /* probably '#t' is here now */
  380. return 1;
  381. }
  382. else
  383. return 0;
  384. }
  385. /*
  386. ** {=============================================================
  387. ** Rehash
  388. ** ==============================================================
  389. */
  390. /*
  391. ** Structure to count the keys in a table.
  392. ** 'total' is the total number of keys in the table.
  393. ** 'na' is the number of *array indices* in the table (see 'arrayindex').
  394. ** 'deleted' is true if there are deleted nodes in the hash part.
  395. ** 'nums' is a "count array" where 'nums[i]' is the number of integer
  396. ** keys between 2^(i - 1) + 1 and 2^i. Note that 'na' is the summation
  397. ** of 'nums'.
  398. */
  399. typedef struct {
  400. unsigned total;
  401. unsigned na;
  402. int deleted;
  403. unsigned nums[MAXABITS + 1];
  404. } Counters;
  405. /*
  406. ** Check whether it is worth to use 'na' array entries instead of 'nh'
  407. ** hash nodes. (A hash node uses ~3 times more memory than an array
  408. ** entry: Two values plus 'next' versus one value.) Evaluate with size_t
  409. ** to avoid overflows.
  410. */
  411. #define arrayXhash(na,nh) (cast_sizet(na) <= cast_sizet(nh) * 3)
  412. /*
  413. ** Compute the optimal size for the array part of table 't'.
  414. ** This size maximizes the number of elements going to the array part
  415. ** while satisfying the condition 'arrayXhash' with the use of memory if
  416. ** all those elements went to the hash part.
  417. ** 'ct->na' enters with the total number of array indices in the table
  418. ** and leaves with the number of keys that will go to the array part;
  419. ** return the optimal size for the array part.
  420. */
  421. static unsigned computesizes (Counters *ct) {
  422. int i;
  423. unsigned int twotoi; /* 2^i (candidate for optimal size) */
  424. unsigned int a = 0; /* number of elements smaller than 2^i */
  425. unsigned int na = 0; /* number of elements to go to array part */
  426. unsigned int optimal = 0; /* optimal size for array part */
  427. /* traverse slices while 'twotoi' does not overflow and total of array
  428. indices still can satisfy 'arrayXhash' against the array size */
  429. for (i = 0, twotoi = 1;
  430. twotoi > 0 && arrayXhash(twotoi, ct->na);
  431. i++, twotoi *= 2) {
  432. unsigned nums = ct->nums[i];
  433. a += nums;
  434. if (nums > 0 && /* grows array only if it gets more elements... */
  435. arrayXhash(twotoi, a)) { /* ...while using "less memory" */
  436. optimal = twotoi; /* optimal size (till now) */
  437. na = a; /* all elements up to 'optimal' will go to array part */
  438. }
  439. }
  440. ct->na = na;
  441. return optimal;
  442. }
  443. static void countint (lua_Integer key, Counters *ct) {
  444. unsigned int k = arrayindex(key);
  445. if (k != 0) { /* is 'key' an array index? */
  446. ct->nums[luaO_ceillog2(k)]++; /* count as such */
  447. ct->na++;
  448. }
  449. }
  450. l_sinline int arraykeyisempty (const Table *t, lua_Unsigned key) {
  451. int tag = *getArrTag(t, key - 1);
  452. return tagisempty(tag);
  453. }
  454. /*
  455. ** Count keys in array part of table 't'.
  456. */
  457. static void numusearray (const Table *t, Counters *ct) {
  458. int lg;
  459. unsigned int ttlg; /* 2^lg */
  460. unsigned int ause = 0; /* summation of 'nums' */
  461. unsigned int i = 1; /* index to traverse all array keys */
  462. unsigned int asize = limitasasize(t); /* real array size */
  463. /* traverse each slice */
  464. for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
  465. unsigned int lc = 0; /* counter */
  466. unsigned int lim = ttlg;
  467. if (lim > asize) {
  468. lim = asize; /* adjust upper limit */
  469. if (i > lim)
  470. break; /* no more elements to count */
  471. }
  472. /* count elements in range (2^(lg - 1), 2^lg] */
  473. for (; i <= lim; i++) {
  474. if (!arraykeyisempty(t, i))
  475. lc++;
  476. }
  477. ct->nums[lg] += lc;
  478. ause += lc;
  479. }
  480. ct->total += ause;
  481. ct->na += ause;
  482. }
  483. /*
  484. ** Count keys in hash part of table 't'. As this only happens during
  485. ** a rehash, all nodes have been used. A node can have a nil value only
  486. ** if it was deleted after being created.
  487. */
  488. static void numusehash (const Table *t, Counters *ct) {
  489. unsigned i = sizenode(t);
  490. unsigned total = 0;
  491. while (i--) {
  492. Node *n = &t->node[i];
  493. if (isempty(gval(n))) {
  494. /* entry was deleted; key cannot be nil */
  495. lua_assert(isdummy(t) || !keyisnil(n));
  496. ct->deleted = 1;
  497. }
  498. else {
  499. total++;
  500. if (keyisinteger(n))
  501. countint(keyival(n), ct);
  502. }
  503. }
  504. ct->total += total;
  505. }
  506. /*
  507. ** Convert an "abstract size" (number of slots in an array) to
  508. ** "concrete size" (number of bytes in the array).
  509. */
  510. static size_t concretesize (unsigned int size) {
  511. return size * sizeof(Value) + size; /* space for the two arrays */
  512. }
  513. /*
  514. ** Resize the array part of a table. If new size is equal to the old,
  515. ** do nothing. Else, if new size is zero, free the old array. (It must
  516. ** be present, as the sizes are different.) Otherwise, allocate a new
  517. ** array, move the common elements to new proper position, and then
  518. ** frees the old array.
  519. ** We could reallocate the array, but we still would need to move the
  520. ** elements to their new position, so the copy implicit in realloc is a
  521. ** waste. Moreover, most allocators will move the array anyway when the
  522. ** new size is double the old one (the most common case).
  523. */
  524. static Value *resizearray (lua_State *L , Table *t,
  525. unsigned oldasize,
  526. unsigned newasize) {
  527. if (oldasize == newasize)
  528. return t->array; /* nothing to be done */
  529. else if (newasize == 0) { /* erasing array? */
  530. Value *op = t->array - oldasize; /* original array's real address */
  531. luaM_freemem(L, op, concretesize(oldasize)); /* free it */
  532. return NULL;
  533. }
  534. else {
  535. size_t newasizeb = concretesize(newasize);
  536. Value *np = cast(Value *,
  537. luaM_reallocvector(L, NULL, 0, newasizeb, lu_byte));
  538. if (np == NULL) /* allocation error? */
  539. return NULL;
  540. if (oldasize > 0) {
  541. /* move common elements to new position */
  542. Value *op = t->array - oldasize; /* real original array */
  543. unsigned tomove = (oldasize < newasize) ? oldasize : newasize;
  544. lua_assert(tomove > 0);
  545. memcpy(np + newasize - tomove,
  546. op + oldasize - tomove,
  547. concretesize(tomove));
  548. luaM_freemem(L, op, concretesize(oldasize));
  549. }
  550. return np + newasize; /* shift pointer to the end of value segment */
  551. }
  552. }
  553. /*
  554. ** Creates an array for the hash part of a table with the given
  555. ** size, or reuses the dummy node if size is zero.
  556. ** The computation for size overflow is in two steps: the first
  557. ** comparison ensures that the shift in the second one does not
  558. ** overflow.
  559. */
  560. static void setnodevector (lua_State *L, Table *t, unsigned size) {
  561. if (size == 0) { /* no elements to hash part? */
  562. t->node = cast(Node *, dummynode); /* use common 'dummynode' */
  563. t->lsizenode = 0;
  564. setdummy(t); /* signal that it is using dummy node */
  565. }
  566. else {
  567. int i;
  568. int lsize = luaO_ceillog2(size);
  569. if (lsize > MAXHBITS || (1u << lsize) > MAXHSIZE)
  570. luaG_runerror(L, "table overflow");
  571. size = twoto(lsize);
  572. if (lsize <= LIMFORLAST) /* no 'lastfree' field? */
  573. t->node = luaM_newvector(L, size, Node);
  574. else {
  575. size_t bsize = size * sizeof(Node) + sizeof(Limbox);
  576. char *node = luaM_newblock(L, bsize);
  577. t->node = cast(Node *, node + sizeof(Limbox));
  578. getlastfree(t) = gnode(t, size); /* all positions are free */
  579. }
  580. t->lsizenode = cast_byte(lsize);
  581. setnodummy(t);
  582. for (i = 0; i < cast_int(size); i++) {
  583. Node *n = gnode(t, i);
  584. gnext(n) = 0;
  585. setnilkey(n);
  586. setempty(gval(n));
  587. }
  588. }
  589. }
  590. /*
  591. ** (Re)insert all elements from the hash part of 'ot' into table 't'.
  592. */
  593. static void reinsert (lua_State *L, Table *ot, Table *t) {
  594. unsigned j;
  595. unsigned size = sizenode(ot);
  596. for (j = 0; j < size; j++) {
  597. Node *old = gnode(ot, j);
  598. if (!isempty(gval(old))) {
  599. /* doesn't need barrier/invalidate cache, as entry was
  600. already present in the table */
  601. TValue k;
  602. getnodekey(L, &k, old);
  603. luaH_set(L, t, &k, gval(old));
  604. }
  605. }
  606. }
  607. /*
  608. ** Exchange the hash part of 't1' and 't2'. (In 'flags', only the
  609. ** dummy bit must be exchanged: The 'isrealasize' is not related
  610. ** to the hash part, and the metamethod bits do not change during
  611. ** a resize, so the "real" table can keep their values.)
  612. */
  613. static void exchangehashpart (Table *t1, Table *t2) {
  614. lu_byte lsizenode = t1->lsizenode;
  615. Node *node = t1->node;
  616. int bitdummy1 = t1->flags & BITDUMMY;
  617. t1->lsizenode = t2->lsizenode;
  618. t1->node = t2->node;
  619. t1->flags = cast_byte((t1->flags & NOTBITDUMMY) | (t2->flags & BITDUMMY));
  620. t2->lsizenode = lsizenode;
  621. t2->node = node;
  622. t2->flags = cast_byte((t2->flags & NOTBITDUMMY) | bitdummy1);
  623. }
  624. /*
  625. ** Re-insert into the new hash part of a table the elements from the
  626. ** vanishing slice of the array part.
  627. */
  628. static void reinsertOldSlice (lua_State *L, Table *t, unsigned oldasize,
  629. unsigned newasize) {
  630. unsigned i;
  631. t->alimit = newasize; /* pretend array has new size... */
  632. for (i = newasize; i < oldasize; i++) { /* traverse vanishing slice */
  633. lu_byte tag = *getArrTag(t, i);
  634. if (!tagisempty(tag)) { /* a non-empty entry? */
  635. TValue aux;
  636. farr2val(t, i, tag, &aux); /* copy entry into 'aux' */
  637. /* re-insert it into the table */
  638. luaH_setint(L, t, cast_int(i) + 1, &aux);
  639. }
  640. }
  641. t->alimit = oldasize; /* restore current size... */
  642. }
  643. /*
  644. ** Clear new slice of the array.
  645. */
  646. static void clearNewSlice (Table *t, unsigned oldasize, unsigned newasize) {
  647. for (; oldasize < newasize; oldasize++)
  648. *getArrTag(t, oldasize) = LUA_VEMPTY;
  649. }
  650. /*
  651. ** Resize table 't' for the new given sizes. Both allocations (for
  652. ** the hash part and for the array part) can fail, which creates some
  653. ** subtleties. If the first allocation, for the hash part, fails, an
  654. ** error is raised and that is it. Otherwise, it copies the elements from
  655. ** the shrinking part of the array (if it is shrinking) into the new
  656. ** hash. Then it reallocates the array part. If that fails, the table
  657. ** is in its original state; the function frees the new hash part and then
  658. ** raises the allocation error. Otherwise, it sets the new hash part
  659. ** into the table, initializes the new part of the array (if any) with
  660. ** nils and reinserts the elements of the old hash back into the new
  661. ** parts of the table.
  662. ** Note that if the new size for the arry part ('newasize') is equal to
  663. ** the old one ('oldasize'), this function will do nothing with that
  664. ** part.
  665. */
  666. void luaH_resize (lua_State *L, Table *t, unsigned newasize,
  667. unsigned nhsize) {
  668. Table newt; /* to keep the new hash part */
  669. unsigned int oldasize = setlimittosize(t);
  670. Value *newarray;
  671. if (newasize > MAXASIZE)
  672. luaG_runerror(L, "table overflow");
  673. /* create new hash part with appropriate size into 'newt' */
  674. newt.flags = 0;
  675. setnodevector(L, &newt, nhsize);
  676. if (newasize < oldasize) { /* will array shrink? */
  677. /* re-insert into the new hash the elements from vanishing slice */
  678. exchangehashpart(t, &newt); /* pretend table has new hash */
  679. reinsertOldSlice(L, t, oldasize, newasize);
  680. exchangehashpart(t, &newt); /* restore old hash (in case of errors) */
  681. }
  682. /* allocate new array */
  683. newarray = resizearray(L, t, oldasize, newasize);
  684. if (l_unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */
  685. freehash(L, &newt); /* release new hash part */
  686. luaM_error(L); /* raise error (with array unchanged) */
  687. }
  688. /* allocation ok; initialize new part of the array */
  689. exchangehashpart(t, &newt); /* 't' has the new hash ('newt' has the old) */
  690. t->array = newarray; /* set new array part */
  691. t->alimit = newasize;
  692. clearNewSlice(t, oldasize, newasize);
  693. /* re-insert elements from old hash part into new parts */
  694. reinsert(L, &newt, t); /* 'newt' now has the old hash */
  695. freehash(L, &newt); /* free old hash part */
  696. }
  697. void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
  698. unsigned nsize = allocsizenode(t);
  699. luaH_resize(L, t, nasize, nsize);
  700. }
  701. /*
  702. ** Rehash a table. First, count its keys. If there are array indices
  703. ** outside the array part, compute the new best size for that part.
  704. ** Then, resize the table.
  705. */
  706. static void rehash (lua_State *L, Table *t, const TValue *ek) {
  707. unsigned asize; /* optimal size for array part */
  708. Counters ct;
  709. unsigned i;
  710. unsigned nsize; /* size for the hash part */
  711. setlimittosize(t);
  712. /* reset counts */
  713. for (i = 0; i <= MAXABITS; i++) ct.nums[i] = 0;
  714. ct.na = 0;
  715. ct.deleted = 0;
  716. ct.total = 1; /* count extra key */
  717. if (ttisinteger(ek))
  718. countint(ivalue(ek), &ct); /* extra key may go to array */
  719. numusehash(t, &ct); /* count keys in hash part */
  720. if (ct.na == 0) {
  721. /* no new keys to enter array part; keep it with the same size */
  722. asize = luaH_realasize(t);
  723. }
  724. else { /* compute best size for array part */
  725. numusearray(t, &ct); /* count keys in array part */
  726. asize = computesizes(&ct); /* compute new size for array part */
  727. }
  728. /* all keys not in the array part go to the hash part */
  729. nsize = ct.total - ct.na;
  730. if (ct.deleted) { /* table has deleted entries? */
  731. /* insertion-deletion-insertion: give hash some extra size to
  732. avoid constant resizings */
  733. nsize += nsize >> 2;
  734. }
  735. /* resize the table to new computed sizes */
  736. luaH_resize(L, t, asize, nsize);
  737. }
  738. /*
  739. ** }=============================================================
  740. */
  741. Table *luaH_new (lua_State *L) {
  742. GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
  743. Table *t = gco2t(o);
  744. t->metatable = NULL;
  745. t->flags = maskflags; /* table has no metamethod fields */
  746. t->array = NULL;
  747. t->alimit = 0;
  748. setnodevector(L, t, 0);
  749. return t;
  750. }
  751. size_t luaH_size (Table *t) {
  752. size_t sz = sizeof(Table)
  753. + luaH_realasize(t) * (sizeof(Value) + 1);
  754. if (!isdummy(t)) {
  755. sz += sizenode(t) * sizeof(Node);
  756. if (haslastfree(t))
  757. sz += sizeof(Limbox);
  758. }
  759. return sz;
  760. }
  761. /*
  762. ** Frees a table.
  763. */
  764. void luaH_free (lua_State *L, Table *t) {
  765. unsigned int realsize = luaH_realasize(t);
  766. freehash(L, t);
  767. resizearray(L, t, realsize, 0);
  768. luaM_free(L, t);
  769. }
  770. static Node *getfreepos (Table *t) {
  771. if (haslastfree(t)) { /* does it have 'lastfree' information? */
  772. /* look for a spot before 'lastfree', updating 'lastfree' */
  773. while (getlastfree(t) > t->node) {
  774. Node *free = --getlastfree(t);
  775. if (keyisnil(free))
  776. return free;
  777. }
  778. }
  779. else { /* no 'lastfree' information */
  780. if (!isdummy(t)) {
  781. unsigned i = sizenode(t);
  782. while (i--) { /* do a linear search */
  783. Node *free = gnode(t, i);
  784. if (keyisnil(free))
  785. return free;
  786. }
  787. }
  788. }
  789. return NULL; /* could not find a free place */
  790. }
  791. /*
  792. ** Inserts a new key into a hash table; first, check whether key's main
  793. ** position is free. If not, check whether colliding node is in its main
  794. ** position or not: if it is not, move colliding node to an empty place
  795. ** and put new key in its main position; otherwise (colliding node is in
  796. ** its main position), new key goes to an empty position.
  797. */
  798. static void luaH_newkey (lua_State *L, Table *t, const TValue *key,
  799. TValue *value) {
  800. Node *mp;
  801. TValue aux;
  802. if (l_unlikely(ttisnil(key)))
  803. luaG_runerror(L, "table index is nil");
  804. else if (ttisfloat(key)) {
  805. lua_Number f = fltvalue(key);
  806. lua_Integer k;
  807. if (luaV_flttointeger(f, &k, F2Ieq)) { /* does key fit in an integer? */
  808. setivalue(&aux, k);
  809. key = &aux; /* insert it as an integer */
  810. }
  811. else if (l_unlikely(luai_numisnan(f)))
  812. luaG_runerror(L, "table index is NaN");
  813. }
  814. if (ttisnil(value))
  815. return; /* do not insert nil values */
  816. mp = mainpositionTV(t, key);
  817. if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */
  818. Node *othern;
  819. Node *f = getfreepos(t); /* get a free place */
  820. if (f == NULL) { /* cannot find a free place? */
  821. rehash(L, t, key); /* grow table */
  822. /* whatever called 'newkey' takes care of TM cache */
  823. luaH_set(L, t, key, value); /* insert key into grown table */
  824. return;
  825. }
  826. lua_assert(!isdummy(t));
  827. othern = mainpositionfromnode(t, mp);
  828. if (othern != mp) { /* is colliding node out of its main position? */
  829. /* yes; move colliding node into free position */
  830. while (othern + gnext(othern) != mp) /* find previous */
  831. othern += gnext(othern);
  832. gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */
  833. *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */
  834. if (gnext(mp) != 0) {
  835. gnext(f) += cast_int(mp - f); /* correct 'next' */
  836. gnext(mp) = 0; /* now 'mp' is free */
  837. }
  838. setempty(gval(mp));
  839. }
  840. else { /* colliding node is in its own main position */
  841. /* new node will go into free position */
  842. if (gnext(mp) != 0)
  843. gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */
  844. else lua_assert(gnext(f) == 0);
  845. gnext(mp) = cast_int(f - mp);
  846. mp = f;
  847. }
  848. }
  849. setnodekey(L, mp, key);
  850. luaC_barrierback(L, obj2gco(t), key);
  851. lua_assert(isempty(gval(mp)));
  852. setobj2t(L, gval(mp), value);
  853. }
  854. static const TValue *getintfromhash (Table *t, lua_Integer key) {
  855. Node *n = hashint(t, key);
  856. lua_assert(l_castS2U(key) - 1u >= luaH_realasize(t));
  857. for (;;) { /* check whether 'key' is somewhere in the chain */
  858. if (keyisinteger(n) && keyival(n) == key)
  859. return gval(n); /* that's it */
  860. else {
  861. int nx = gnext(n);
  862. if (nx == 0) break;
  863. n += nx;
  864. }
  865. }
  866. return &absentkey;
  867. }
  868. static int hashkeyisempty (Table *t, lua_Unsigned key) {
  869. const TValue *val = getintfromhash(t, l_castU2S(key));
  870. return isempty(val);
  871. }
  872. static lu_byte finishnodeget (const TValue *val, TValue *res) {
  873. if (!ttisnil(val)) {
  874. setobj(((lua_State*)NULL), res, val);
  875. }
  876. return ttypetag(val);
  877. }
  878. lu_byte luaH_getint (Table *t, lua_Integer key, TValue *res) {
  879. if (keyinarray(t, key)) {
  880. lu_byte tag = *getArrTag(t, key - 1);
  881. if (!tagisempty(tag))
  882. farr2val(t, cast_uint(key) - 1, tag, res);
  883. return tag;
  884. }
  885. else
  886. return finishnodeget(getintfromhash(t, key), res);
  887. }
  888. /*
  889. ** search function for short strings
  890. */
  891. const TValue *luaH_Hgetshortstr (Table *t, TString *key) {
  892. Node *n = hashstr(t, key);
  893. lua_assert(key->tt == LUA_VSHRSTR);
  894. for (;;) { /* check whether 'key' is somewhere in the chain */
  895. if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
  896. return gval(n); /* that's it */
  897. else {
  898. int nx = gnext(n);
  899. if (nx == 0)
  900. return &absentkey; /* not found */
  901. n += nx;
  902. }
  903. }
  904. }
  905. lu_byte luaH_getshortstr (Table *t, TString *key, TValue *res) {
  906. return finishnodeget(luaH_Hgetshortstr(t, key), res);
  907. }
  908. static const TValue *Hgetstr (Table *t, TString *key) {
  909. if (key->tt == LUA_VSHRSTR)
  910. return luaH_Hgetshortstr(t, key);
  911. else { /* for long strings, use generic case */
  912. TValue ko;
  913. setsvalue(cast(lua_State *, NULL), &ko, key);
  914. return getgeneric(t, &ko, 0);
  915. }
  916. }
  917. lu_byte luaH_getstr (Table *t, TString *key, TValue *res) {
  918. return finishnodeget(Hgetstr(t, key), res);
  919. }
  920. TString *luaH_getstrkey (Table *t, TString *key) {
  921. const TValue *o = Hgetstr(t, key);
  922. if (!isabstkey(o)) /* string already present? */
  923. return keystrval(nodefromval(o)); /* get saved copy */
  924. else
  925. return NULL;
  926. }
  927. /*
  928. ** main search function
  929. */
  930. lu_byte luaH_get (Table *t, const TValue *key, TValue *res) {
  931. const TValue *slot;
  932. switch (ttypetag(key)) {
  933. case LUA_VSHRSTR:
  934. slot = luaH_Hgetshortstr(t, tsvalue(key));
  935. break;
  936. case LUA_VNUMINT:
  937. return luaH_getint(t, ivalue(key), res);
  938. case LUA_VNIL:
  939. slot = &absentkey;
  940. break;
  941. case LUA_VNUMFLT: {
  942. lua_Integer k;
  943. if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
  944. return luaH_getint(t, k, res); /* use specialized version */
  945. /* else... */
  946. } /* FALLTHROUGH */
  947. default:
  948. slot = getgeneric(t, key, 0);
  949. break;
  950. }
  951. return finishnodeget(slot, res);
  952. }
  953. static int finishnodeset (Table *t, const TValue *slot, TValue *val) {
  954. if (!ttisnil(slot)) {
  955. setobj(((lua_State*)NULL), cast(TValue*, slot), val);
  956. return HOK; /* success */
  957. }
  958. else if (isabstkey(slot))
  959. return HNOTFOUND; /* no slot with that key */
  960. else /* return node encoded */
  961. return cast_int((cast(Node*, slot) - t->node)) + HFIRSTNODE;
  962. }
  963. static int rawfinishnodeset (const TValue *slot, TValue *val) {
  964. if (isabstkey(slot))
  965. return 0; /* no slot with that key */
  966. else {
  967. setobj(((lua_State*)NULL), cast(TValue*, slot), val);
  968. return 1; /* success */
  969. }
  970. }
  971. int luaH_psetint (Table *t, lua_Integer key, TValue *val) {
  972. if (keyinarray(t, key)) {
  973. lu_byte *tag = getArrTag(t, key - 1);
  974. if (!tagisempty(*tag) || checknoTM(t->metatable, TM_NEWINDEX)) {
  975. fval2arr(t, cast_uint(key) - 1, tag, val);
  976. return HOK; /* success */
  977. }
  978. else
  979. return ~cast_int(key - 1); /* empty slot in the array part */
  980. }
  981. else
  982. return finishnodeset(t, getintfromhash(t, key), val);
  983. }
  984. int luaH_psetshortstr (Table *t, TString *key, TValue *val) {
  985. return finishnodeset(t, luaH_Hgetshortstr(t, key), val);
  986. }
  987. int luaH_psetstr (Table *t, TString *key, TValue *val) {
  988. return finishnodeset(t, Hgetstr(t, key), val);
  989. }
  990. int luaH_pset (Table *t, const TValue *key, TValue *val) {
  991. switch (ttypetag(key)) {
  992. case LUA_VSHRSTR: return luaH_psetshortstr(t, tsvalue(key), val);
  993. case LUA_VNUMINT: return luaH_psetint(t, ivalue(key), val);
  994. case LUA_VNIL: return HNOTFOUND;
  995. case LUA_VNUMFLT: {
  996. lua_Integer k;
  997. if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
  998. return luaH_psetint(t, k, val); /* use specialized version */
  999. /* else... */
  1000. } /* FALLTHROUGH */
  1001. default:
  1002. return finishnodeset(t, getgeneric(t, key, 0), val);
  1003. }
  1004. }
  1005. /*
  1006. ** Finish a raw "set table" operation, where 'slot' is where the value
  1007. ** should have been (the result of a previous "get table").
  1008. ** Beware: when using this function you probably need to check a GC
  1009. ** barrier and invalidate the TM cache.
  1010. */
  1011. void luaH_finishset (lua_State *L, Table *t, const TValue *key,
  1012. TValue *value, int hres) {
  1013. lua_assert(hres != HOK);
  1014. if (hres == HNOTFOUND) {
  1015. luaH_newkey(L, t, key, value);
  1016. }
  1017. else if (hres > 0) { /* regular Node? */
  1018. setobj2t(L, gval(gnode(t, hres - HFIRSTNODE)), value);
  1019. }
  1020. else { /* array entry */
  1021. hres = ~hres; /* real index */
  1022. obj2arr(t, cast_uint(hres), value);
  1023. }
  1024. }
  1025. /*
  1026. ** beware: when using this function you probably need to check a GC
  1027. ** barrier and invalidate the TM cache.
  1028. */
  1029. void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) {
  1030. int hres = luaH_pset(t, key, value);
  1031. if (hres != HOK)
  1032. luaH_finishset(L, t, key, value, hres);
  1033. }
  1034. /*
  1035. ** Ditto for a GC barrier. (No need to invalidate the TM cache, as
  1036. ** integers cannot be keys to metamethods.)
  1037. */
  1038. void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
  1039. if (keyinarray(t, key))
  1040. obj2arr(t, cast_uint(key) - 1, value);
  1041. else {
  1042. int ok = rawfinishnodeset(getintfromhash(t, key), value);
  1043. if (!ok) {
  1044. TValue k;
  1045. setivalue(&k, key);
  1046. luaH_newkey(L, t, &k, value);
  1047. }
  1048. }
  1049. }
  1050. /*
  1051. ** Try to find a boundary in the hash part of table 't'. From the
  1052. ** caller, we know that 'j' is zero or present and that 'j + 1' is
  1053. ** present. We want to find a larger key that is absent from the
  1054. ** table, so that we can do a binary search between the two keys to
  1055. ** find a boundary. We keep doubling 'j' until we get an absent index.
  1056. ** If the doubling would overflow, we try LUA_MAXINTEGER. If it is
  1057. ** absent, we are ready for the binary search. ('j', being max integer,
  1058. ** is larger or equal to 'i', but it cannot be equal because it is
  1059. ** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a
  1060. ** boundary. ('j + 1' cannot be a present integer key because it is
  1061. ** not a valid integer in Lua.)
  1062. */
  1063. static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
  1064. lua_Unsigned i;
  1065. if (j == 0) j++; /* the caller ensures 'j + 1' is present */
  1066. do {
  1067. i = j; /* 'i' is a present index */
  1068. if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
  1069. j *= 2;
  1070. else {
  1071. j = LUA_MAXINTEGER;
  1072. if (hashkeyisempty(t, j)) /* t[j] not present? */
  1073. break; /* 'j' now is an absent index */
  1074. else /* weird case */
  1075. return j; /* well, max integer is a boundary... */
  1076. }
  1077. } while (!hashkeyisempty(t, j)); /* repeat until an absent t[j] */
  1078. /* i < j && t[i] present && t[j] absent */
  1079. while (j - i > 1u) { /* do a binary search between them */
  1080. lua_Unsigned m = (i + j) / 2;
  1081. if (hashkeyisempty(t, m)) j = m;
  1082. else i = m;
  1083. }
  1084. return i;
  1085. }
  1086. static unsigned int binsearch (Table *array, unsigned int i, unsigned int j) {
  1087. while (j - i > 1u) { /* binary search */
  1088. unsigned int m = (i + j) / 2;
  1089. if (arraykeyisempty(array, m)) j = m;
  1090. else i = m;
  1091. }
  1092. return i;
  1093. }
  1094. /*
  1095. ** Try to find a boundary in table 't'. (A 'boundary' is an integer index
  1096. ** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent
  1097. ** and 'maxinteger' if t[maxinteger] is present.)
  1098. ** (In the next explanation, we use Lua indices, that is, with base 1.
  1099. ** The code itself uses base 0 when indexing the array part of the table.)
  1100. ** The code starts with 'limit = t->alimit', a position in the array
  1101. ** part that may be a boundary.
  1102. **
  1103. ** (1) If 't[limit]' is empty, there must be a boundary before it.
  1104. ** As a common case (e.g., after 't[#t]=nil'), check whether 'limit-1'
  1105. ** is present. If so, it is a boundary. Otherwise, do a binary search
  1106. ** between 0 and limit to find a boundary. In both cases, try to
  1107. ** use this boundary as the new 'alimit', as a hint for the next call.
  1108. **
  1109. ** (2) If 't[limit]' is not empty and the array has more elements
  1110. ** after 'limit', try to find a boundary there. Again, try first
  1111. ** the special case (which should be quite frequent) where 'limit+1'
  1112. ** is empty, so that 'limit' is a boundary. Otherwise, check the
  1113. ** last element of the array part. If it is empty, there must be a
  1114. ** boundary between the old limit (present) and the last element
  1115. ** (absent), which is found with a binary search. (This boundary always
  1116. ** can be a new limit.)
  1117. **
  1118. ** (3) The last case is when there are no elements in the array part
  1119. ** (limit == 0) or its last element (the new limit) is present.
  1120. ** In this case, must check the hash part. If there is no hash part
  1121. ** or 'limit+1' is absent, 'limit' is a boundary. Otherwise, call
  1122. ** 'hash_search' to find a boundary in the hash part of the table.
  1123. ** (In those cases, the boundary is not inside the array part, and
  1124. ** therefore cannot be used as a new limit.)
  1125. */
  1126. lua_Unsigned luaH_getn (Table *t) {
  1127. unsigned int limit = t->alimit;
  1128. if (limit > 0 && arraykeyisempty(t, limit)) { /* (1)? */
  1129. /* there must be a boundary before 'limit' */
  1130. if (limit >= 2 && !arraykeyisempty(t, limit - 1)) {
  1131. /* 'limit - 1' is a boundary; can it be a new limit? */
  1132. if (ispow2realasize(t) && !ispow2(limit - 1)) {
  1133. t->alimit = limit - 1;
  1134. setnorealasize(t); /* now 'alimit' is not the real size */
  1135. }
  1136. return limit - 1;
  1137. }
  1138. else { /* must search for a boundary in [0, limit] */
  1139. unsigned int boundary = binsearch(t, 0, limit);
  1140. /* can this boundary represent the real size of the array? */
  1141. if (ispow2realasize(t) && boundary > luaH_realasize(t) / 2) {
  1142. t->alimit = boundary; /* use it as the new limit */
  1143. setnorealasize(t);
  1144. }
  1145. return boundary;
  1146. }
  1147. }
  1148. /* 'limit' is zero or present in table */
  1149. if (!limitequalsasize(t)) { /* (2)? */
  1150. /* 'limit' > 0 and array has more elements after 'limit' */
  1151. if (arraykeyisempty(t, limit + 1)) /* 'limit + 1' is empty? */
  1152. return limit; /* this is the boundary */
  1153. /* else, try last element in the array */
  1154. limit = luaH_realasize(t);
  1155. if (arraykeyisempty(t, limit)) { /* empty? */
  1156. /* there must be a boundary in the array after old limit,
  1157. and it must be a valid new limit */
  1158. unsigned int boundary = binsearch(t, t->alimit, limit);
  1159. t->alimit = boundary;
  1160. return boundary;
  1161. }
  1162. /* else, new limit is present in the table; check the hash part */
  1163. }
  1164. /* (3) 'limit' is the last element and either is zero or present in table */
  1165. lua_assert(limit == luaH_realasize(t) &&
  1166. (limit == 0 || !arraykeyisempty(t, limit)));
  1167. if (isdummy(t) || hashkeyisempty(t, limit + 1))
  1168. return limit; /* 'limit + 1' is absent */
  1169. else /* 'limit + 1' is also present */
  1170. return hash_search(t, limit);
  1171. }
  1172. #if defined(LUA_DEBUG)
  1173. /* export these functions for the test library */
  1174. Node *luaH_mainposition (const Table *t, const TValue *key) {
  1175. return mainpositionTV(t, key);
  1176. }
  1177. #endif