ltablib.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. /*
  2. ** $Id: ltablib.c,v 1.93 2016/02/25 19:41:54 roberto Exp $
  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. #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 && !lua_compare(L, 1, tt, LUA_OPEQ))) {
  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 destination 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. lua_Integer last = aux_getn(L, 1, TAB_R);
  146. size_t lsep;
  147. const char *sep = luaL_optlstring(L, 2, "", &lsep);
  148. lua_Integer i = luaL_optinteger(L, 3, 1);
  149. last = luaL_optinteger(L, 4, last);
  150. luaL_buffinit(L, &b);
  151. for (; i < last; i++) {
  152. addfield(L, &b, i);
  153. luaL_addlstring(&b, sep, lsep);
  154. }
  155. if (i == last) /* add last value (if interval was not empty) */
  156. addfield(L, &b, i);
  157. luaL_pushresult(&b);
  158. return 1;
  159. }
  160. /*
  161. ** {======================================================
  162. ** Pack/unpack
  163. ** =======================================================
  164. */
  165. static int pack (lua_State *L) {
  166. int i;
  167. int n = lua_gettop(L); /* number of elements to pack */
  168. lua_createtable(L, n, 1); /* create result table */
  169. lua_insert(L, 1); /* put it at index 1 */
  170. for (i = n; i >= 1; i--) /* assign elements */
  171. lua_seti(L, 1, i);
  172. lua_pushinteger(L, n);
  173. lua_setfield(L, 1, "n"); /* t.n = number of elements */
  174. return 1; /* return table */
  175. }
  176. static int unpack (lua_State *L) {
  177. lua_Unsigned n;
  178. lua_Integer i = luaL_optinteger(L, 2, 1);
  179. lua_Integer e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1));
  180. if (i > e) return 0; /* empty range */
  181. n = (lua_Unsigned)e - i; /* number of elements minus 1 (avoid overflows) */
  182. if (n >= (unsigned int)INT_MAX || !lua_checkstack(L, (int)(++n)))
  183. return luaL_error(L, "too many results to unpack");
  184. for (; i < e; i++) { /* push arg[i..e - 1] (to avoid overflows) */
  185. lua_geti(L, 1, i);
  186. }
  187. lua_geti(L, 1, e); /* push last element */
  188. return (int)n;
  189. }
  190. /* }====================================================== */
  191. /*
  192. ** {======================================================
  193. ** Quicksort
  194. ** (based on 'Algorithms in MODULA-3', Robert Sedgewick;
  195. ** Addison-Wesley, 1993.)
  196. ** =======================================================
  197. */
  198. /* type for array indices */
  199. typedef unsigned int IdxT;
  200. /*
  201. ** Produce a "random" 'unsigned int' to randomize pivot choice. This
  202. ** macro is used only when 'sort' detects a big imbalance in the result
  203. ** of a partition. (If you don't want/need this "randomness", ~0 is a
  204. ** good choice.)
  205. */
  206. #if !defined(l_randomizePivot) /* { */
  207. #include <time.h>
  208. /* size of 'e' measured in number of 'unsigned int's */
  209. #define sof(e) (sizeof(e) / sizeof(unsigned int))
  210. /*
  211. ** Use 'time' and 'clock' as sources of "randomness". Because we don't
  212. ** know the types 'clock_t' and 'time_t', we cannot cast them to
  213. ** anything without risking overflows. A safe way to use their values
  214. ** is to copy them to an array of a known type and use the array values.
  215. */
  216. static unsigned int l_randomizePivot (void) {
  217. clock_t c = clock();
  218. time_t t = time(NULL);
  219. unsigned int buff[sof(c) + sof(t)];
  220. unsigned int i, rnd = 0;
  221. memcpy(buff, &c, sof(c) * sizeof(unsigned int));
  222. memcpy(buff + sof(c), &t, sof(t) * sizeof(unsigned int));
  223. for (i = 0; i < sof(buff); i++)
  224. rnd += buff[i];
  225. return rnd;
  226. }
  227. #endif /* } */
  228. /* arrays larger than 'RANLIMIT' may use randomized pivots */
  229. #define RANLIMIT 100u
  230. static void set2 (lua_State *L, IdxT i, IdxT j) {
  231. lua_seti(L, 1, i);
  232. lua_seti(L, 1, j);
  233. }
  234. /*
  235. ** Return true iff value at stack index 'a' is less than the value at
  236. ** index 'b' (according to the order of the sort).
  237. */
  238. static int sort_comp (lua_State *L, int a, int b) {
  239. if (lua_isnil(L, 2)) /* no function? */
  240. return lua_compare(L, a, b, LUA_OPLT); /* a < b */
  241. else { /* function */
  242. int res;
  243. lua_pushvalue(L, 2); /* push function */
  244. lua_pushvalue(L, a-1); /* -1 to compensate function */
  245. lua_pushvalue(L, b-2); /* -2 to compensate function and 'a' */
  246. lua_call(L, 2, 1); /* call function */
  247. res = lua_toboolean(L, -1); /* get result */
  248. lua_pop(L, 1); /* pop result */
  249. return res;
  250. }
  251. }
  252. /*
  253. ** Does the partition: Pivot P is at the top of the stack.
  254. ** precondition: a[lo] <= P == a[up-1] <= a[up],
  255. ** so it only needs to do the partition from lo + 1 to up - 2.
  256. ** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up]
  257. ** returns 'i'.
  258. */
  259. static IdxT partition (lua_State *L, IdxT lo, IdxT up) {
  260. IdxT i = lo; /* will be incremented before first use */
  261. IdxT j = up - 1; /* will be decremented before first use */
  262. /* loop invariant: a[lo .. i] <= P <= a[j .. up] */
  263. for (;;) {
  264. /* next loop: repeat ++i while a[i] < P */
  265. while (lua_geti(L, 1, ++i), sort_comp(L, -1, -2)) {
  266. if (i == up - 1) /* a[i] < P but a[up - 1] == P ?? */
  267. luaL_error(L, "invalid order function for sorting");
  268. lua_pop(L, 1); /* remove a[i] */
  269. }
  270. /* after the loop, a[i] >= P and a[lo .. i - 1] < P */
  271. /* next loop: repeat --j while P < a[j] */
  272. while (lua_geti(L, 1, --j), sort_comp(L, -3, -1)) {
  273. if (j < i) /* j < i but a[j] > P ?? */
  274. luaL_error(L, "invalid order function for sorting");
  275. lua_pop(L, 1); /* remove a[j] */
  276. }
  277. /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */
  278. if (j < i) { /* no elements out of place? */
  279. /* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */
  280. lua_pop(L, 1); /* pop a[j] */
  281. /* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */
  282. set2(L, up - 1, i);
  283. return i;
  284. }
  285. /* otherwise, swap a[i] - a[j] to restore invariant and repeat */
  286. set2(L, i, j);
  287. }
  288. }
  289. /*
  290. ** Choose an element in the middle (2nd-3th quarters) of [lo,up]
  291. ** "randomized" by 'rnd'
  292. */
  293. static IdxT choosePivot (IdxT lo, IdxT up, unsigned int rnd) {
  294. IdxT r4 = (up - lo) / 4; /* range/4 */
  295. IdxT p = rnd % (r4 * 2) + (lo + r4);
  296. lua_assert(lo + r4 <= p && p <= up - r4);
  297. return p;
  298. }
  299. /*
  300. ** QuickSort algorithm (recursive function)
  301. */
  302. static void auxsort (lua_State *L, IdxT lo, IdxT up,
  303. unsigned int rnd) {
  304. while (lo < up) { /* loop for tail recursion */
  305. IdxT p; /* Pivot index */
  306. IdxT n; /* to be used later */
  307. /* sort elements 'lo', 'p', and 'up' */
  308. lua_geti(L, 1, lo);
  309. lua_geti(L, 1, up);
  310. if (sort_comp(L, -1, -2)) /* a[up] < a[lo]? */
  311. set2(L, lo, up); /* swap a[lo] - a[up] */
  312. else
  313. lua_pop(L, 2); /* remove both values */
  314. if (up - lo == 1) /* only 2 elements? */
  315. return; /* already sorted */
  316. if (up - lo < RANLIMIT || rnd == 0) /* small interval or no randomize? */
  317. p = (lo + up)/2; /* middle element is a good pivot */
  318. else /* for larger intervals, it is worth a random pivot */
  319. p = choosePivot(lo, up, rnd);
  320. lua_geti(L, 1, p);
  321. lua_geti(L, 1, lo);
  322. if (sort_comp(L, -2, -1)) /* a[p] < a[lo]? */
  323. set2(L, p, lo); /* swap a[p] - a[lo] */
  324. else {
  325. lua_pop(L, 1); /* remove a[lo] */
  326. lua_geti(L, 1, up);
  327. if (sort_comp(L, -1, -2)) /* a[up] < a[p]? */
  328. set2(L, p, up); /* swap a[up] - a[p] */
  329. else
  330. lua_pop(L, 2);
  331. }
  332. if (up - lo == 2) /* only 3 elements? */
  333. return; /* already sorted */
  334. lua_geti(L, 1, p); /* get middle element (Pivot) */
  335. lua_pushvalue(L, -1); /* push Pivot */
  336. lua_geti(L, 1, up - 1); /* push a[up - 1] */
  337. set2(L, p, up - 1); /* swap Pivot (a[p]) with a[up - 1] */
  338. p = partition(L, lo, up);
  339. /* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */
  340. if (p - lo < up - p) { /* lower interval is smaller? */
  341. auxsort(L, lo, p - 1, rnd); /* call recursively for lower interval */
  342. n = p - lo; /* size of smaller interval */
  343. lo = p + 1; /* tail call for [p + 1 .. up] (upper interval) */
  344. }
  345. else {
  346. auxsort(L, p + 1, up, rnd); /* call recursively for upper interval */
  347. n = up - p; /* size of smaller interval */
  348. up = p - 1; /* tail call for [lo .. p - 1] (lower interval) */
  349. }
  350. if ((up - lo) / 128 > n) /* partition too imbalanced? */
  351. rnd = l_randomizePivot(); /* try a new randomization */
  352. } /* tail call auxsort(L, lo, up, rnd) */
  353. }
  354. static int sort (lua_State *L) {
  355. lua_Integer n = aux_getn(L, 1, TAB_RW);
  356. if (n > 1) { /* non-trivial interval? */
  357. luaL_argcheck(L, n < INT_MAX, 1, "array too big");
  358. if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */
  359. luaL_checktype(L, 2, LUA_TFUNCTION); /* must be a function */
  360. lua_settop(L, 2); /* make sure there are two arguments */
  361. auxsort(L, 1, (IdxT)n, 0);
  362. }
  363. return 0;
  364. }
  365. /* }====================================================== */
  366. static const luaL_Reg tab_funcs[] = {
  367. {"concat", tconcat},
  368. #if defined(LUA_COMPAT_MAXN)
  369. {"maxn", maxn},
  370. #endif
  371. {"insert", tinsert},
  372. {"pack", pack},
  373. {"unpack", unpack},
  374. {"remove", tremove},
  375. {"move", tmove},
  376. {"sort", sort},
  377. {NULL, NULL}
  378. };
  379. LUAMOD_API int luaopen_table (lua_State *L) {
  380. luaL_newlib(L, tab_funcs);
  381. #if defined(LUA_COMPAT_UNPACK)
  382. /* _G.unpack = table.unpack */
  383. lua_getfield(L, -1, "unpack");
  384. lua_setglobal(L, "unpack");
  385. #endif
  386. return 1;
  387. }