2
0

ltablib.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. /*
  2. ** $Id: ltablib.c $
  3. ** Library for Table Manipulation
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define ltablib_c
  7. #define LUA_LIB
  8. #include "lprefix.h"
  9. #include <limits.h>
  10. #include <stddef.h>
  11. #include <string.h>
  12. #include "lua.h"
  13. #include "lauxlib.h"
  14. #include "lualib.h"
  15. #include "llimits.h"
  16. /*
  17. ** Operations that an object must define to mimic a table
  18. ** (some functions only need some of them)
  19. */
  20. #define TAB_R 1 /* read */
  21. #define TAB_W 2 /* write */
  22. #define TAB_L 4 /* length */
  23. #define TAB_RW (TAB_R | TAB_W) /* read/write */
  24. #define aux_getn(L,n,w) (checktab(L, n, (w) | TAB_L), luaL_len(L, n))
  25. static int checkfield (lua_State *L, const char *key, int n) {
  26. lua_pushstring(L, key);
  27. return (lua_rawget(L, -n) != LUA_TNIL);
  28. }
  29. /*
  30. ** Check that 'arg' either is a table or can behave like one (that is,
  31. ** has a metatable with the required metamethods)
  32. */
  33. static void checktab (lua_State *L, int arg, int what) {
  34. if (lua_type(L, arg) != LUA_TTABLE) { /* is it not a table? */
  35. int n = 1; /* number of elements to pop */
  36. if (lua_getmetatable(L, arg) && /* must have metatable */
  37. (!(what & TAB_R) || checkfield(L, "__index", ++n)) &&
  38. (!(what & TAB_W) || checkfield(L, "__newindex", ++n)) &&
  39. (!(what & TAB_L) || checkfield(L, "__len", ++n))) {
  40. lua_pop(L, n); /* pop metatable and tested metamethods */
  41. }
  42. else
  43. luaL_checktype(L, arg, LUA_TTABLE); /* force an error */
  44. }
  45. }
  46. static int tcreate (lua_State *L) {
  47. lua_Unsigned sizeseq = (lua_Unsigned)luaL_checkinteger(L, 1);
  48. lua_Unsigned sizerest = (lua_Unsigned)luaL_optinteger(L, 2, 0);
  49. luaL_argcheck(L, sizeseq <= cast_uint(INT_MAX), 1, "out of range");
  50. luaL_argcheck(L, sizerest <= cast_uint(INT_MAX), 2, "out of range");
  51. lua_createtable(L, cast_int(sizeseq), cast_int(sizerest));
  52. return 1;
  53. }
  54. static int tinsert (lua_State *L) {
  55. lua_Integer pos; /* where to insert new element */
  56. lua_Integer e = aux_getn(L, 1, TAB_RW);
  57. e = luaL_intop(+, e, 1); /* first empty element */
  58. switch (lua_gettop(L)) {
  59. case 2: { /* called with only 2 arguments */
  60. pos = e; /* insert new element at the end */
  61. break;
  62. }
  63. case 3: {
  64. lua_Integer i;
  65. pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */
  66. /* check whether 'pos' is in [1, e] */
  67. luaL_argcheck(L, (lua_Unsigned)pos - 1u < (lua_Unsigned)e, 2,
  68. "position out of bounds");
  69. for (i = e; i > pos; i--) { /* move up elements */
  70. lua_geti(L, 1, i - 1);
  71. lua_seti(L, 1, i); /* t[i] = t[i - 1] */
  72. }
  73. break;
  74. }
  75. default: {
  76. return luaL_error(L, "wrong number of arguments to 'insert'");
  77. }
  78. }
  79. lua_seti(L, 1, pos); /* t[pos] = v */
  80. return 0;
  81. }
  82. static int tremove (lua_State *L) {
  83. lua_Integer size = aux_getn(L, 1, TAB_RW);
  84. lua_Integer pos = luaL_optinteger(L, 2, size);
  85. if (pos != size) /* validate 'pos' if given */
  86. /* check whether 'pos' is in [1, size + 1] */
  87. luaL_argcheck(L, (lua_Unsigned)pos - 1u <= (lua_Unsigned)size, 2,
  88. "position out of bounds");
  89. lua_geti(L, 1, pos); /* result = t[pos] */
  90. for ( ; pos < size; pos++) {
  91. lua_geti(L, 1, pos + 1);
  92. lua_seti(L, 1, pos); /* t[pos] = t[pos + 1] */
  93. }
  94. lua_pushnil(L);
  95. lua_seti(L, 1, pos); /* remove entry t[pos] */
  96. return 1;
  97. }
  98. /*
  99. ** Copy elements (1[f], ..., 1[e]) into (tt[t], tt[t+1], ...). Whenever
  100. ** possible, copy in increasing order, which is better for rehashing.
  101. ** "possible" means destination after original range, or smaller
  102. ** than origin, or copying to another table.
  103. */
  104. static int tmove (lua_State *L) {
  105. lua_Integer f = luaL_checkinteger(L, 2);
  106. lua_Integer e = luaL_checkinteger(L, 3);
  107. lua_Integer t = luaL_checkinteger(L, 4);
  108. int tt = !lua_isnoneornil(L, 5) ? 5 : 1; /* destination table */
  109. checktab(L, 1, TAB_R);
  110. checktab(L, tt, TAB_W);
  111. if (e >= f) { /* otherwise, nothing to move */
  112. lua_Integer n, i;
  113. luaL_argcheck(L, f > 0 || e < LUA_MAXINTEGER + f, 3,
  114. "too many elements to move");
  115. n = e - f + 1; /* number of elements to move */
  116. luaL_argcheck(L, t <= LUA_MAXINTEGER - n + 1, 4,
  117. "destination wrap around");
  118. if (t > e || t <= f || (tt != 1 && !lua_compare(L, 1, tt, LUA_OPEQ))) {
  119. for (i = 0; i < n; i++) {
  120. lua_geti(L, 1, f + i);
  121. lua_seti(L, tt, t + i);
  122. }
  123. }
  124. else {
  125. for (i = n - 1; i >= 0; i--) {
  126. lua_geti(L, 1, f + i);
  127. lua_seti(L, tt, t + i);
  128. }
  129. }
  130. }
  131. lua_pushvalue(L, tt); /* return destination table */
  132. return 1;
  133. }
  134. static void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) {
  135. lua_geti(L, 1, i);
  136. if (l_unlikely(!lua_isstring(L, -1)))
  137. luaL_error(L, "invalid value (%s) at index %I in table for 'concat'",
  138. luaL_typename(L, -1), (LUAI_UACINT)i);
  139. luaL_addvalue(b);
  140. }
  141. static int tconcat (lua_State *L) {
  142. luaL_Buffer b;
  143. lua_Integer last = aux_getn(L, 1, TAB_R);
  144. size_t lsep;
  145. const char *sep = luaL_optlstring(L, 2, "", &lsep);
  146. lua_Integer i = luaL_optinteger(L, 3, 1);
  147. last = luaL_optinteger(L, 4, last);
  148. luaL_buffinit(L, &b);
  149. for (; i < last; i++) {
  150. addfield(L, &b, i);
  151. luaL_addlstring(&b, sep, lsep);
  152. }
  153. if (i == last) /* add last value (if interval was not empty) */
  154. addfield(L, &b, i);
  155. luaL_pushresult(&b);
  156. return 1;
  157. }
  158. /*
  159. ** {======================================================
  160. ** Pack/unpack
  161. ** =======================================================
  162. */
  163. static int tpack (lua_State *L) {
  164. int i;
  165. int n = lua_gettop(L); /* number of elements to pack */
  166. lua_createtable(L, n, 1); /* create result table */
  167. lua_insert(L, 1); /* put it at index 1 */
  168. for (i = n; i >= 1; i--) /* assign elements */
  169. lua_seti(L, 1, i);
  170. lua_pushinteger(L, n);
  171. lua_setfield(L, 1, "n"); /* t.n = number of elements */
  172. return 1; /* return table */
  173. }
  174. static int tunpack (lua_State *L) {
  175. lua_Unsigned n;
  176. lua_Integer i = luaL_optinteger(L, 2, 1);
  177. lua_Integer e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1));
  178. if (i > e) return 0; /* empty range */
  179. n = l_castS2U(e) - l_castS2U(i); /* number of elements minus 1 */
  180. if (l_unlikely(n >= (unsigned int)INT_MAX ||
  181. !lua_checkstack(L, (int)(++n))))
  182. return luaL_error(L, "too many results to unpack");
  183. for (; i < e; i++) { /* push arg[i..e - 1] (to avoid overflows) */
  184. lua_geti(L, 1, i);
  185. }
  186. lua_geti(L, 1, e); /* push last element */
  187. return (int)n;
  188. }
  189. /* }====================================================== */
  190. /*
  191. ** {======================================================
  192. ** Quicksort
  193. ** (based on 'Algorithms in MODULA-3', Robert Sedgewick;
  194. ** Addison-Wesley, 1993.)
  195. ** =======================================================
  196. */
  197. /*
  198. ** Type for array indices. These indices are always limited by INT_MAX,
  199. ** so it is safe to cast them to lua_Integer even for Lua 32 bits.
  200. */
  201. typedef unsigned int IdxT;
  202. /* Versions of lua_seti/lua_geti specialized for IdxT */
  203. #define geti(L,idt,idx) lua_geti(L, idt, l_castU2S(idx))
  204. #define seti(L,idt,idx) lua_seti(L, idt, l_castU2S(idx))
  205. /*
  206. ** Produce a "random" 'unsigned int' to randomize pivot choice. This
  207. ** macro is used only when 'sort' detects a big imbalance in the result
  208. ** of a partition. (If you don't want/need this "randomness", ~0 is a
  209. ** good choice.)
  210. */
  211. #if !defined(l_randomizePivot)
  212. #define l_randomizePivot(L) luaL_makeseed(L)
  213. #endif /* } */
  214. /* arrays larger than 'RANLIMIT' may use randomized pivots */
  215. #define RANLIMIT 100u
  216. static void set2 (lua_State *L, IdxT i, IdxT j) {
  217. seti(L, 1, i);
  218. seti(L, 1, j);
  219. }
  220. /*
  221. ** Return true iff value at stack index 'a' is less than the value at
  222. ** index 'b' (according to the order of the sort).
  223. */
  224. static int sort_comp (lua_State *L, int a, int b) {
  225. if (lua_isnil(L, 2)) /* no function? */
  226. return lua_compare(L, a, b, LUA_OPLT); /* a < b */
  227. else { /* function */
  228. int res;
  229. lua_pushvalue(L, 2); /* push function */
  230. lua_pushvalue(L, a-1); /* -1 to compensate function */
  231. lua_pushvalue(L, b-2); /* -2 to compensate function and 'a' */
  232. lua_call(L, 2, 1); /* call function */
  233. res = lua_toboolean(L, -1); /* get result */
  234. lua_pop(L, 1); /* pop result */
  235. return res;
  236. }
  237. }
  238. /*
  239. ** Does the partition: Pivot P is at the top of the stack.
  240. ** precondition: a[lo] <= P == a[up-1] <= a[up],
  241. ** so it only needs to do the partition from lo + 1 to up - 2.
  242. ** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up]
  243. ** returns 'i'.
  244. */
  245. static IdxT partition (lua_State *L, IdxT lo, IdxT up) {
  246. IdxT i = lo; /* will be incremented before first use */
  247. IdxT j = up - 1; /* will be decremented before first use */
  248. /* loop invariant: a[lo .. i] <= P <= a[j .. up] */
  249. for (;;) {
  250. /* next loop: repeat ++i while a[i] < P */
  251. while ((void)geti(L, 1, ++i), sort_comp(L, -1, -2)) {
  252. if (l_unlikely(i == up - 1)) /* a[up - 1] < P == a[up - 1] */
  253. luaL_error(L, "invalid order function for sorting");
  254. lua_pop(L, 1); /* remove a[i] */
  255. }
  256. /* after the loop, a[i] >= P and a[lo .. i - 1] < P (a) */
  257. /* next loop: repeat --j while P < a[j] */
  258. while ((void)geti(L, 1, --j), sort_comp(L, -3, -1)) {
  259. if (l_unlikely(j < i)) /* j <= i - 1 and a[j] > P, contradicts (a) */
  260. luaL_error(L, "invalid order function for sorting");
  261. lua_pop(L, 1); /* remove a[j] */
  262. }
  263. /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */
  264. if (j < i) { /* no elements out of place? */
  265. /* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */
  266. lua_pop(L, 1); /* pop a[j] */
  267. /* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */
  268. set2(L, up - 1, i);
  269. return i;
  270. }
  271. /* otherwise, swap a[i] - a[j] to restore invariant and repeat */
  272. set2(L, i, j);
  273. }
  274. }
  275. /*
  276. ** Choose an element in the middle (2nd-3th quarters) of [lo,up]
  277. ** "randomized" by 'rnd'
  278. */
  279. static IdxT choosePivot (IdxT lo, IdxT up, unsigned int rnd) {
  280. IdxT r4 = (up - lo) / 4; /* range/4 */
  281. IdxT p = (rnd ^ lo ^ up) % (r4 * 2) + (lo + r4);
  282. lua_assert(lo + r4 <= p && p <= up - r4);
  283. return p;
  284. }
  285. /*
  286. ** Quicksort algorithm (recursive function)
  287. */
  288. static void auxsort (lua_State *L, IdxT lo, IdxT up, unsigned rnd) {
  289. while (lo < up) { /* loop for tail recursion */
  290. IdxT p; /* Pivot index */
  291. IdxT n; /* to be used later */
  292. /* sort elements 'lo', 'p', and 'up' */
  293. geti(L, 1, lo);
  294. geti(L, 1, up);
  295. if (sort_comp(L, -1, -2)) /* a[up] < a[lo]? */
  296. set2(L, lo, up); /* swap a[lo] - a[up] */
  297. else
  298. lua_pop(L, 2); /* remove both values */
  299. if (up - lo == 1) /* only 2 elements? */
  300. return; /* already sorted */
  301. if (up - lo < RANLIMIT || rnd == 0) /* small interval or no randomize? */
  302. p = (lo + up)/2; /* middle element is a good pivot */
  303. else /* for larger intervals, it is worth a random pivot */
  304. p = choosePivot(lo, up, rnd);
  305. geti(L, 1, p);
  306. geti(L, 1, lo);
  307. if (sort_comp(L, -2, -1)) /* a[p] < a[lo]? */
  308. set2(L, p, lo); /* swap a[p] - a[lo] */
  309. else {
  310. lua_pop(L, 1); /* remove a[lo] */
  311. geti(L, 1, up);
  312. if (sort_comp(L, -1, -2)) /* a[up] < a[p]? */
  313. set2(L, p, up); /* swap a[up] - a[p] */
  314. else
  315. lua_pop(L, 2);
  316. }
  317. if (up - lo == 2) /* only 3 elements? */
  318. return; /* already sorted */
  319. geti(L, 1, p); /* get middle element (Pivot) */
  320. lua_pushvalue(L, -1); /* push Pivot */
  321. geti(L, 1, up - 1); /* push a[up - 1] */
  322. set2(L, p, up - 1); /* swap Pivot (a[p]) with a[up - 1] */
  323. p = partition(L, lo, up);
  324. /* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */
  325. if (p - lo < up - p) { /* lower interval is smaller? */
  326. auxsort(L, lo, p - 1, rnd); /* call recursively for lower interval */
  327. n = p - lo; /* size of smaller interval */
  328. lo = p + 1; /* tail call for [p + 1 .. up] (upper interval) */
  329. }
  330. else {
  331. auxsort(L, p + 1, up, rnd); /* call recursively for upper interval */
  332. n = up - p; /* size of smaller interval */
  333. up = p - 1; /* tail call for [lo .. p - 1] (lower interval) */
  334. }
  335. if ((up - lo) / 128 > n) /* partition too imbalanced? */
  336. rnd = l_randomizePivot(L); /* try a new randomization */
  337. } /* tail call auxsort(L, lo, up, rnd) */
  338. }
  339. static int sort (lua_State *L) {
  340. lua_Integer n = aux_getn(L, 1, TAB_RW);
  341. if (n > 1) { /* non-trivial interval? */
  342. luaL_argcheck(L, n < INT_MAX, 1, "array too big");
  343. if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */
  344. luaL_checktype(L, 2, LUA_TFUNCTION); /* must be a function */
  345. lua_settop(L, 2); /* make sure there are two arguments */
  346. auxsort(L, 1, (IdxT)n, 0);
  347. }
  348. return 0;
  349. }
  350. /* }====================================================== */
  351. static const luaL_Reg tab_funcs[] = {
  352. {"concat", tconcat},
  353. {"create", tcreate},
  354. {"insert", tinsert},
  355. {"pack", tpack},
  356. {"unpack", tunpack},
  357. {"remove", tremove},
  358. {"move", tmove},
  359. {"sort", sort},
  360. {NULL, NULL}
  361. };
  362. LUAMOD_API int luaopen_table (lua_State *L) {
  363. luaL_newlib(L, tab_funcs);
  364. return 1;
  365. }