ltablib.c 13 KB

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