ltable.c 39 KB

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