ltablib.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. /*
  2. ** $Id: ltablib.c,v 1.84 2015/11/06 16:07:14 roberto Exp roberto $
  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 <time.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
  20. #define TAB_W 2
  21. #define TAB_L 4
  22. #define TAB_RW (TAB_R | TAB_W)
  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_argerror(L, arg, "table expected"); /* force an error */
  43. }
  44. }
  45. #if defined(LUA_COMPAT_MAXN)
  46. static int maxn (lua_State *L) {
  47. lua_Number max = 0;
  48. luaL_checktype(L, 1, LUA_TTABLE);
  49. lua_pushnil(L); /* first key */
  50. while (lua_next(L, 1)) {
  51. lua_pop(L, 1); /* remove value */
  52. if (lua_type(L, -1) == LUA_TNUMBER) {
  53. lua_Number v = lua_tonumber(L, -1);
  54. if (v > max) max = v;
  55. }
  56. }
  57. lua_pushnumber(L, max);
  58. return 1;
  59. }
  60. #endif
  61. static int tinsert (lua_State *L) {
  62. lua_Integer e = aux_getn(L, 1, TAB_RW) + 1; /* first empty element */
  63. lua_Integer pos; /* where to insert new element */
  64. switch (lua_gettop(L)) {
  65. case 2: { /* called with only 2 arguments */
  66. pos = e; /* insert new element at the end */
  67. break;
  68. }
  69. case 3: {
  70. lua_Integer i;
  71. pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */
  72. luaL_argcheck(L, 1 <= pos && pos <= e, 2, "position out of bounds");
  73. for (i = e; i > pos; i--) { /* move up elements */
  74. lua_geti(L, 1, i - 1);
  75. lua_seti(L, 1, i); /* t[i] = t[i - 1] */
  76. }
  77. break;
  78. }
  79. default: {
  80. return luaL_error(L, "wrong number of arguments to 'insert'");
  81. }
  82. }
  83. lua_seti(L, 1, pos); /* t[pos] = v */
  84. return 0;
  85. }
  86. static int tremove (lua_State *L) {
  87. lua_Integer size = aux_getn(L, 1, TAB_RW);
  88. lua_Integer pos = luaL_optinteger(L, 2, size);
  89. if (pos != size) /* validate 'pos' if given */
  90. luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, "position out of bounds");
  91. lua_geti(L, 1, pos); /* result = t[pos] */
  92. for ( ; pos < size; pos++) {
  93. lua_geti(L, 1, pos + 1);
  94. lua_seti(L, 1, pos); /* t[pos] = t[pos + 1] */
  95. }
  96. lua_pushnil(L);
  97. lua_seti(L, 1, pos); /* t[pos] = nil */
  98. return 1;
  99. }
  100. /*
  101. ** Copy elements (1[f], ..., 1[e]) into (tt[t], tt[t+1], ...). Whenever
  102. ** possible, copy in increasing order, which is better for rehashing.
  103. ** "possible" means destination after original range, or smaller
  104. ** than origin, or copying to another table.
  105. */
  106. static int tmove (lua_State *L) {
  107. lua_Integer f = luaL_checkinteger(L, 2);
  108. lua_Integer e = luaL_checkinteger(L, 3);
  109. lua_Integer t = luaL_checkinteger(L, 4);
  110. int tt = !lua_isnoneornil(L, 5) ? 5 : 1; /* destination table */
  111. checktab(L, 1, TAB_R);
  112. checktab(L, tt, TAB_W);
  113. if (e >= f) { /* otherwise, nothing to move */
  114. lua_Integer n, i;
  115. luaL_argcheck(L, f > 0 || e < LUA_MAXINTEGER + f, 3,
  116. "too many elements to move");
  117. n = e - f + 1; /* number of elements to move */
  118. luaL_argcheck(L, t <= LUA_MAXINTEGER - n + 1, 4,
  119. "destination wrap around");
  120. if (t > e || t <= f || tt != 1) {
  121. for (i = 0; i < n; i++) {
  122. lua_geti(L, 1, f + i);
  123. lua_seti(L, tt, t + i);
  124. }
  125. }
  126. else {
  127. for (i = n - 1; i >= 0; i--) {
  128. lua_geti(L, 1, f + i);
  129. lua_seti(L, tt, t + i);
  130. }
  131. }
  132. }
  133. lua_pushvalue(L, tt); /* return "to table" */
  134. return 1;
  135. }
  136. static void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) {
  137. lua_geti(L, 1, i);
  138. if (!lua_isstring(L, -1))
  139. luaL_error(L, "invalid value (%s) at index %d in table for 'concat'",
  140. luaL_typename(L, -1), i);
  141. luaL_addvalue(b);
  142. }
  143. static int tconcat (lua_State *L) {
  144. luaL_Buffer b;
  145. size_t lsep;
  146. lua_Integer i;
  147. lua_Integer last = aux_getn(L, 1, TAB_R);
  148. const char *sep = luaL_optlstring(L, 2, "", &lsep);
  149. i = luaL_optinteger(L, 3, 1);
  150. last = luaL_opt(L, luaL_checkinteger, 4, last);
  151. luaL_buffinit(L, &b);
  152. for (; i < last; i++) {
  153. addfield(L, &b, i);
  154. luaL_addlstring(&b, sep, lsep);
  155. }
  156. if (i == last) /* add last value (if interval was not empty) */
  157. addfield(L, &b, i);
  158. luaL_pushresult(&b);
  159. return 1;
  160. }
  161. /*
  162. ** {======================================================
  163. ** Pack/unpack
  164. ** =======================================================
  165. */
  166. static int pack (lua_State *L) {
  167. int i;
  168. int n = lua_gettop(L); /* number of elements to pack */
  169. lua_createtable(L, n, 1); /* create result table */
  170. lua_insert(L, 1); /* put it at index 1 */
  171. for (i = n; i >= 1; i--) /* assign elements */
  172. lua_seti(L, 1, i);
  173. lua_pushinteger(L, n);
  174. lua_setfield(L, 1, "n"); /* t.n = number of elements */
  175. return 1; /* return table */
  176. }
  177. static int unpack (lua_State *L) {
  178. lua_Integer i, e;
  179. lua_Unsigned n;
  180. i = luaL_optinteger(L, 2, 1);
  181. e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1));
  182. if (i > e) return 0; /* empty range */
  183. n = (lua_Unsigned)e - i; /* number of elements minus 1 (avoid overflows) */
  184. if (n >= (unsigned int)INT_MAX || !lua_checkstack(L, (int)(++n)))
  185. return luaL_error(L, "too many results to unpack");
  186. for (; i < e; i++) { /* push arg[i..e - 1] (to avoid overflows) */
  187. lua_geti(L, 1, i);
  188. }
  189. lua_geti(L, 1, e); /* push last element */
  190. return (int)n;
  191. }
  192. /* }====================================================== */
  193. /*
  194. ** {======================================================
  195. ** Quicksort
  196. ** (based on 'Algorithms in MODULA-3', Robert Sedgewick;
  197. ** Addison-Wesley, 1993.)
  198. ** =======================================================
  199. */
  200. static void set2 (lua_State *L, int i, int j) {
  201. lua_seti(L, 1, i);
  202. lua_seti(L, 1, j);
  203. }
  204. static int sort_comp (lua_State *L, int a, int b) {
  205. if (!lua_isnil(L, 2)) { /* function? */
  206. int res;
  207. lua_pushvalue(L, 2);
  208. lua_pushvalue(L, a-1); /* -1 to compensate function */
  209. lua_pushvalue(L, b-2); /* -2 to compensate function and 'a' */
  210. lua_call(L, 2, 1);
  211. res = lua_toboolean(L, -1);
  212. lua_pop(L, 1);
  213. return res;
  214. }
  215. else /* a < b? */
  216. return lua_compare(L, a, b, LUA_OPLT);
  217. }
  218. /*
  219. ** Does the partition: Pivot P is at the top of the stack.
  220. ** precondition: a[lo] <= P == a[up-1] <= a[up],
  221. ** so it only needs to do the partition from lo + 1 to up - 2.
  222. ** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up]
  223. ** returns 'i'.
  224. */
  225. static int partition (lua_State *L, int lo, int up) {
  226. int i = lo; /* will be incremented before first use */
  227. int j = up - 1; /* will be decremented before first use */
  228. /* loop invariant: a[lo .. i] <= P <= a[j .. up] */
  229. for (;;) {
  230. /* next loop: repeat ++i while a[i] < P */
  231. while (lua_geti(L, 1, ++i), sort_comp(L, -1, -2)) {
  232. if (i == up - 1) /* a[i] < P but a[up - 1] == P ?? */
  233. luaL_error(L, "invalid order function for sorting");
  234. lua_pop(L, 1); /* remove a[i] */
  235. }
  236. /* after the loop, a[i] >= P and a[lo .. i - 1] < P */
  237. /* next loop: repeat --j while P < a[j] */
  238. while (lua_geti(L, 1, --j), sort_comp(L, -3, -1)) {
  239. if (j < i) /* j < i but a[j] > P ?? */
  240. luaL_error(L, "invalid order function for sorting");
  241. lua_pop(L, 1); /* remove a[j] */
  242. }
  243. /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */
  244. if (j < i) { /* no elements out of place? */
  245. /* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */
  246. lua_pop(L, 1); /* pop a[j] */
  247. /* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */
  248. set2(L, up - 1, i);
  249. return i;
  250. }
  251. /* otherwise, swap a[i] - a[j] to restore invariant and repeat */
  252. set2(L, i, j);
  253. }
  254. }
  255. /*
  256. ** Choose a "random" pivot in the middle part of the interval [lo, up].
  257. ** Use 'time' and 'clock' as sources of "randomness".
  258. */
  259. static int choosePivot (int lo, int up) {
  260. unsigned int t = (unsigned int)(unsigned long)time(NULL); /* time */
  261. unsigned int c = (unsigned int)(unsigned long)clock(); /* clock */
  262. unsigned int r4 = (unsigned int)(up - lo) / 4u; /* range/4 */
  263. unsigned int p = (c + t) % (r4 * 2) + (lo + r4);
  264. lua_assert(lo + r4 <= p && p <= up - r4);
  265. return (int)p;
  266. }
  267. static void auxsort (lua_State *L, int lo, int up) {
  268. while (lo < up) { /* loop for tail recursion */
  269. int p;
  270. /* sort elements 'lo', '(lo + up)/2' and 'up' */
  271. lua_geti(L, 1, lo);
  272. lua_geti(L, 1, up);
  273. if (sort_comp(L, -1, -2)) /* a[up] < a[lo]? */
  274. set2(L, lo, up); /* swap a[lo] - a[up] */
  275. else
  276. lua_pop(L, 2); /* remove both values */
  277. if (up - lo == 1) /* only 2 elements? */
  278. return; /* already sorted */
  279. if (up - lo < 100) /* small interval? */
  280. p = (lo + up)/2; /* middle element is a good pivot */
  281. else /* for larger intervals, it is worth a random pivot */
  282. p = choosePivot(lo, up);
  283. lua_geti(L, 1, p);
  284. lua_geti(L, 1, lo);
  285. if (sort_comp(L, -2, -1)) /* a[p] < a[lo]? */
  286. set2(L, p, lo); /* swap a[p] - a[lo] */
  287. else {
  288. lua_pop(L, 1); /* remove a[lo] */
  289. lua_geti(L, 1, up);
  290. if (sort_comp(L, -1, -2)) /* a[up] < a[p]? */
  291. set2(L, p, up); /* swap a[up] - a[p] */
  292. else
  293. lua_pop(L, 2);
  294. }
  295. if (up - lo == 2) /* only 3 elements? */
  296. return; /* already sorted */
  297. lua_geti(L, 1, p); /* get middle element (Pivot) */
  298. lua_pushvalue(L, -1); /* push Pivot */
  299. lua_geti(L, 1, up - 1); /* push a[up - 1] */
  300. set2(L, p, up - 1); /* swap Pivot (a[p]) with a[up - 1] */
  301. p = partition(L, lo, up);
  302. /* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */
  303. if (p - lo < up - p) { /* lower interval is smaller? */
  304. auxsort(L, lo, p - 1); /* call recursively for lower interval */
  305. lo = p + 1; /* tail call for [p + 1 .. up] (upper interval) */
  306. }
  307. else {
  308. auxsort(L, p + 1, up); /* call recursively for upper interval */
  309. up = p - 1; /* tail call for [lo .. p - 1] (lower interval) */
  310. }
  311. } /* tail call auxsort(L, lo, up) */
  312. }
  313. static int sort (lua_State *L) {
  314. int n = (int)aux_getn(L, 1, TAB_RW);
  315. luaL_checkstack(L, 50, ""); /* assume array is smaller than 2^50 */
  316. if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */
  317. luaL_checktype(L, 2, LUA_TFUNCTION);
  318. lua_settop(L, 2); /* make sure there are two arguments */
  319. auxsort(L, 1, n);
  320. return 0;
  321. }
  322. /* }====================================================== */
  323. static const luaL_Reg tab_funcs[] = {
  324. {"concat", tconcat},
  325. #if defined(LUA_COMPAT_MAXN)
  326. {"maxn", maxn},
  327. #endif
  328. {"insert", tinsert},
  329. {"pack", pack},
  330. {"unpack", unpack},
  331. {"remove", tremove},
  332. {"move", tmove},
  333. {"sort", sort},
  334. {NULL, NULL}
  335. };
  336. LUAMOD_API int luaopen_table (lua_State *L) {
  337. luaL_newlib(L, tab_funcs);
  338. #if defined(LUA_COMPAT_UNPACK)
  339. /* _G.unpack = table.unpack */
  340. lua_getfield(L, -1, "unpack");
  341. lua_setglobal(L, "unpack");
  342. #endif
  343. return 1;
  344. }