ltablib.c 13 KB

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