ltablib.c 14 KB

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