ltablib.c 13 KB

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