You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1586 lines
46 KiB

  1. /*
  2. ** $Id: lstrlib.c,v 1.251 2016/05/20 14:13:21 roberto Exp $
  3. ** Standard library for string operations and pattern-matching
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lstrlib_c
  7. #define LUA_LIB
  8. #include "lprefix.h"
  9. #if defined HAVE_CONFIG_H // LOL BEGIN
  10. # include "config.h"
  11. #endif // LOL END
  12. #include <ctype.h>
  13. #include <float.h>
  14. #include <limits.h>
  15. #include <locale.h>
  16. #include <stddef.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include "lua.h"
  21. #include "lauxlib.h"
  22. #include "lualib.h"
  23. /*
  24. ** maximum number of captures that a pattern can do during
  25. ** pattern-matching. This limit is arbitrary, but must fit in
  26. ** an unsigned char.
  27. */
  28. #if !defined(LUA_MAXCAPTURES)
  29. #define LUA_MAXCAPTURES 32
  30. #endif
  31. /* macro to 'unsign' a character */
  32. #define uchar(c) ((unsigned char)(c))
  33. /*
  34. ** Some sizes are better limited to fit in 'int', but must also fit in
  35. ** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.)
  36. */
  37. #define MAX_SIZET ((size_t)(~(size_t)0))
  38. #define MAXSIZE \
  39. (sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX))
  40. static int str_len (lua_State *L) {
  41. size_t l;
  42. luaL_checklstring(L, 1, &l);
  43. lua_pushinteger(L, (lua_Integer)l);
  44. return 1;
  45. }
  46. /* translate a relative string position: negative means back from end */
  47. static lua_Integer posrelat (lua_Integer pos, size_t len) {
  48. if (pos >= 0) return pos;
  49. else if (0u - (size_t)pos > len) return 0;
  50. else return (lua_Integer)len + pos + 1;
  51. }
  52. static int str_sub (lua_State *L) {
  53. size_t l;
  54. const char *s = luaL_checklstring(L, 1, &l);
  55. lua_Integer start = posrelat(luaL_checkinteger(L, 2), l);
  56. lua_Integer end = posrelat(luaL_optinteger(L, 3, -1), l);
  57. if (start < 1) start = 1;
  58. if (end > (lua_Integer)l) end = l;
  59. if (start <= end)
  60. lua_pushlstring(L, s + start - 1, (size_t)(end - start) + 1);
  61. else lua_pushliteral(L, "");
  62. return 1;
  63. }
  64. static int str_reverse (lua_State *L) {
  65. size_t l, i;
  66. luaL_Buffer b;
  67. const char *s = luaL_checklstring(L, 1, &l);
  68. char *p = luaL_buffinitsize(L, &b, l);
  69. for (i = 0; i < l; i++)
  70. p[i] = s[l - i - 1];
  71. luaL_pushresultsize(&b, l);
  72. return 1;
  73. }
  74. static int str_lower (lua_State *L) {
  75. size_t l;
  76. size_t i;
  77. luaL_Buffer b;
  78. const char *s = luaL_checklstring(L, 1, &l);
  79. char *p = luaL_buffinitsize(L, &b, l);
  80. for (i=0; i<l; i++)
  81. p[i] = tolower(uchar(s[i]));
  82. luaL_pushresultsize(&b, l);
  83. return 1;
  84. }
  85. static int str_upper (lua_State *L) {
  86. size_t l;
  87. size_t i;
  88. luaL_Buffer b;
  89. const char *s = luaL_checklstring(L, 1, &l);
  90. char *p = luaL_buffinitsize(L, &b, l);
  91. for (i=0; i<l; i++)
  92. p[i] = toupper(uchar(s[i]));
  93. luaL_pushresultsize(&b, l);
  94. return 1;
  95. }
  96. static int str_rep (lua_State *L) {
  97. size_t l, lsep;
  98. const char *s = luaL_checklstring(L, 1, &l);
  99. lua_Integer n = luaL_checkinteger(L, 2);
  100. const char *sep = luaL_optlstring(L, 3, "", &lsep);
  101. if (n <= 0) lua_pushliteral(L, "");
  102. else if (l + lsep < l || l + lsep > MAXSIZE / n) /* may overflow? */
  103. return luaL_error(L, "resulting string too large");
  104. else {
  105. size_t totallen = (size_t)n * l + (size_t)(n - 1) * lsep;
  106. luaL_Buffer b;
  107. char *p = luaL_buffinitsize(L, &b, totallen);
  108. while (n-- > 1) { /* first n-1 copies (followed by separator) */
  109. memcpy(p, s, l * sizeof(char)); p += l;
  110. if (lsep > 0) { /* empty 'memcpy' is not that cheap */
  111. memcpy(p, sep, lsep * sizeof(char));
  112. p += lsep;
  113. }
  114. }
  115. memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */
  116. luaL_pushresultsize(&b, totallen);
  117. }
  118. return 1;
  119. }
  120. static int str_byte (lua_State *L) {
  121. size_t l;
  122. const char *s = luaL_checklstring(L, 1, &l);
  123. lua_Integer posi = posrelat(luaL_optinteger(L, 2, 1), l);
  124. lua_Integer pose = posrelat(luaL_optinteger(L, 3, posi), l);
  125. int n, i;
  126. if (posi < 1) posi = 1;
  127. if (pose > (lua_Integer)l) pose = l;
  128. if (posi > pose) return 0; /* empty interval; return no values */
  129. if (pose - posi >= INT_MAX) /* arithmetic overflow? */
  130. return luaL_error(L, "string slice too long");
  131. n = (int)(pose - posi) + 1;
  132. luaL_checkstack(L, n, "string slice too long");
  133. for (i=0; i<n; i++)
  134. lua_pushinteger(L, uchar(s[posi+i-1]));
  135. return n;
  136. }
  137. static int str_char (lua_State *L) {
  138. int n = lua_gettop(L); /* number of arguments */
  139. int i;
  140. luaL_Buffer b;
  141. char *p = luaL_buffinitsize(L, &b, n);
  142. for (i=1; i<=n; i++) {
  143. lua_Integer c = luaL_checkinteger(L, i);
  144. luaL_argcheck(L, uchar(c) == c, i, "value out of range");
  145. p[i - 1] = uchar(c);
  146. }
  147. luaL_pushresultsize(&b, n);
  148. return 1;
  149. }
  150. static int writer (lua_State *L, const void *b, size_t size, void *B) {
  151. (void)L;
  152. luaL_addlstring((luaL_Buffer *) B, (const char *)b, size);
  153. return 0;
  154. }
  155. static int str_dump (lua_State *L) {
  156. luaL_Buffer b;
  157. int strip = lua_toboolean(L, 2);
  158. luaL_checktype(L, 1, LUA_TFUNCTION);
  159. lua_settop(L, 1);
  160. luaL_buffinit(L,&b);
  161. if (lua_dump(L, writer, &b, strip) != 0)
  162. return luaL_error(L, "unable to dump given function");
  163. luaL_pushresult(&b);
  164. return 1;
  165. }
  166. /*
  167. ** {======================================================
  168. ** PATTERN MATCHING
  169. ** =======================================================
  170. */
  171. #define CAP_UNFINISHED (-1)
  172. #define CAP_POSITION (-2)
  173. typedef struct MatchState {
  174. const char *src_init; /* init of source string */
  175. const char *src_end; /* end ('\0') of source string */
  176. const char *p_end; /* end ('\0') of pattern */
  177. lua_State *L;
  178. int matchdepth; /* control for recursive depth (to avoid C stack overflow) */
  179. unsigned char level; /* total number of captures (finished or unfinished) */
  180. struct {
  181. const char *init;
  182. ptrdiff_t len;
  183. } capture[LUA_MAXCAPTURES];
  184. } MatchState;
  185. /* recursive function */
  186. static const char *match (MatchState *ms, const char *s, const char *p);
  187. /* maximum recursion depth for 'match' */
  188. #if !defined(MAXCCALLS)
  189. #define MAXCCALLS 200
  190. #endif
  191. #define L_ESC '%'
  192. #define SPECIALS "^$*+?.([%-"
  193. static int check_capture (MatchState *ms, int l) {
  194. l -= '1';
  195. if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
  196. return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
  197. return l;
  198. }
  199. static int capture_to_close (MatchState *ms) {
  200. int level = ms->level;
  201. for (level--; level>=0; level--)
  202. if (ms->capture[level].len == CAP_UNFINISHED) return level;
  203. return luaL_error(ms->L, "invalid pattern capture");
  204. }
  205. static const char *classend (MatchState *ms, const char *p) {
  206. switch (*p++) {
  207. case L_ESC: {
  208. if (p == ms->p_end)
  209. luaL_error(ms->L, "malformed pattern (ends with '%%')");
  210. return p+1;
  211. }
  212. case '[': {
  213. if (*p == '^') p++;
  214. do { /* look for a ']' */
  215. if (p == ms->p_end)
  216. luaL_error(ms->L, "malformed pattern (missing ']')");
  217. if (*(p++) == L_ESC && p < ms->p_end)
  218. p++; /* skip escapes (e.g. '%]') */
  219. } while (*p != ']');
  220. return p+1;
  221. }
  222. default: {
  223. return p;
  224. }
  225. }
  226. }
  227. static int match_class (int c, int cl) {
  228. int res;
  229. switch (tolower(cl)) {
  230. case 'a' : res = isalpha(c); break;
  231. case 'c' : res = iscntrl(c); break;
  232. case 'd' : res = isdigit(c); break;
  233. case 'g' : res = isgraph(c); break;
  234. case 'l' : res = islower(c); break;
  235. case 'p' : res = ispunct(c); break;
  236. case 's' : res = isspace(c); break;
  237. case 'u' : res = isupper(c); break;
  238. case 'w' : res = isalnum(c); break;
  239. case 'x' : res = isxdigit(c); break;
  240. case 'z' : res = (c == 0); break; /* deprecated option */
  241. default: return (cl == c);
  242. }
  243. return (islower(cl) ? res : !res);
  244. }
  245. static int matchbracketclass (int c, const char *p, const char *ec) {
  246. int sig = 1;
  247. if (*(p+1) == '^') {
  248. sig = 0;
  249. p++; /* skip the '^' */
  250. }
  251. while (++p < ec) {
  252. if (*p == L_ESC) {
  253. p++;
  254. if (match_class(c, uchar(*p)))
  255. return sig;
  256. }
  257. else if ((*(p+1) == '-') && (p+2 < ec)) {
  258. p+=2;
  259. if (uchar(*(p-2)) <= c && c <= uchar(*p))
  260. return sig;
  261. }
  262. else if (uchar(*p) == c) return sig;
  263. }
  264. return !sig;
  265. }
  266. static int singlematch (MatchState *ms, const char *s, const char *p,
  267. const char *ep) {
  268. if (s >= ms->src_end)
  269. return 0;
  270. else {
  271. int c = uchar(*s);
  272. switch (*p) {
  273. case '.': return 1; /* matches any char */
  274. case L_ESC: return match_class(c, uchar(*(p+1)));
  275. case '[': return matchbracketclass(c, p, ep-1);
  276. default: return (uchar(*p) == c);
  277. }
  278. }
  279. }
  280. static const char *matchbalance (MatchState *ms, const char *s,
  281. const char *p) {
  282. if (p >= ms->p_end - 1)
  283. luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')");
  284. if (*s != *p) return NULL;
  285. else {
  286. int b = *p;
  287. int e = *(p+1);
  288. int cont = 1;
  289. while (++s < ms->src_end) {
  290. if (*s == e) {
  291. if (--cont == 0) return s+1;
  292. }
  293. else if (*s == b) cont++;
  294. }
  295. }
  296. return NULL; /* string ends out of balance */
  297. }
  298. static const char *max_expand (MatchState *ms, const char *s,
  299. const char *p, const char *ep) {
  300. ptrdiff_t i = 0; /* counts maximum expand for item */
  301. while (singlematch(ms, s + i, p, ep))
  302. i++;
  303. /* keeps trying to match with the maximum repetitions */
  304. while (i>=0) {
  305. const char *res = match(ms, (s+i), ep+1);
  306. if (res) return res;
  307. i--; /* else didn't match; reduce 1 repetition to try again */
  308. }
  309. return NULL;
  310. }
  311. static const char *min_expand (MatchState *ms, const char *s,
  312. const char *p, const char *ep) {
  313. for (;;) {
  314. const char *res = match(ms, s, ep+1);
  315. if (res != NULL)
  316. return res;
  317. else if (singlematch(ms, s, p, ep))
  318. s++; /* try with one more repetition */
  319. else return NULL;
  320. }
  321. }
  322. static const char *start_capture (MatchState *ms, const char *s,
  323. const char *p, int what) {
  324. const char *res;
  325. int level = ms->level;
  326. if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
  327. ms->capture[level].init = s;
  328. ms->capture[level].len = what;
  329. ms->level = level+1;
  330. if ((res=match(ms, s, p)) == NULL) /* match failed? */
  331. ms->level--; /* undo capture */
  332. return res;
  333. }
  334. static const char *end_capture (MatchState *ms, const char *s,
  335. const char *p) {
  336. int l = capture_to_close(ms);
  337. const char *res;
  338. ms->capture[l].len = s - ms->capture[l].init; /* close capture */
  339. if ((res = match(ms, s, p)) == NULL) /* match failed? */
  340. ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
  341. return res;
  342. }
  343. static const char *match_capture (MatchState *ms, const char *s, int l) {
  344. size_t len;
  345. l = check_capture(ms, l);
  346. len = ms->capture[l].len;
  347. if ((size_t)(ms->src_end-s) >= len &&
  348. memcmp(ms->capture[l].init, s, len) == 0)
  349. return s+len;
  350. else return NULL;
  351. }
  352. static const char *match (MatchState *ms, const char *s, const char *p) {
  353. if (ms->matchdepth-- == 0)
  354. luaL_error(ms->L, "pattern too complex");
  355. init: /* using goto's to optimize tail recursion */
  356. if (p != ms->p_end) { /* end of pattern? */
  357. switch (*p) {
  358. case '(': { /* start capture */
  359. if (*(p + 1) == ')') /* position capture? */
  360. s = start_capture(ms, s, p + 2, CAP_POSITION);
  361. else
  362. s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
  363. break;
  364. }
  365. case ')': { /* end capture */
  366. s = end_capture(ms, s, p + 1);
  367. break;
  368. }
  369. case '$': {
  370. if ((p + 1) != ms->p_end) /* is the '$' the last char in pattern? */
  371. goto dflt; /* no; go to default */
  372. s = (s == ms->src_end) ? s : NULL; /* check end of string */
  373. break;
  374. }
  375. case L_ESC: { /* escaped sequences not in the format class[*+?-]? */
  376. switch (*(p + 1)) {
  377. case 'b': { /* balanced string? */
  378. s = matchbalance(ms, s, p + 2);
  379. if (s != NULL) {
  380. p += 4; goto init; /* return match(ms, s, p + 4); */
  381. } /* else fail (s == NULL) */
  382. break;
  383. }
  384. case 'f': { /* frontier? */
  385. const char *ep; char previous;
  386. p += 2;
  387. if (*p != '[')
  388. luaL_error(ms->L, "missing '[' after '%%f' in pattern");
  389. ep = classend(ms, p); /* points to what is next */
  390. previous = (s == ms->src_init) ? '\0' : *(s - 1);
  391. if (!matchbracketclass(uchar(previous), p, ep - 1) &&
  392. matchbracketclass(uchar(*s), p, ep - 1)) {
  393. p = ep; goto init; /* return match(ms, s, ep); */
  394. }
  395. s = NULL; /* match failed */
  396. break;
  397. }
  398. case '0': case '1': case '2': case '3':
  399. case '4': case '5': case '6': case '7':
  400. case '8': case '9': { /* capture results (%0-%9)? */
  401. s = match_capture(ms, s, uchar(*(p + 1)));
  402. if (s != NULL) {
  403. p += 2; goto init; /* return match(ms, s, p + 2) */
  404. }
  405. break;
  406. }
  407. default: goto dflt;
  408. }
  409. break;
  410. }
  411. default: dflt: { /* pattern class plus optional suffix */
  412. const char *ep = classend(ms, p); /* points to optional suffix */
  413. /* does not match at least once? */
  414. if (!singlematch(ms, s, p, ep)) {
  415. if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */
  416. p = ep + 1; goto init; /* return match(ms, s, ep + 1); */
  417. }
  418. else /* '+' or no suffix */
  419. s = NULL; /* fail */
  420. }
  421. else { /* matched once */
  422. switch (*ep) { /* handle optional suffix */
  423. case '?': { /* optional */
  424. const char *res;
  425. if ((res = match(ms, s + 1, ep + 1)) != NULL)
  426. s = res;
  427. else {
  428. p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */
  429. }
  430. break;
  431. }
  432. case '+': /* 1 or more repetitions */
  433. s++; /* 1 match already done */
  434. /* FALLTHROUGH */
  435. case '*': /* 0 or more repetitions */
  436. s = max_expand(ms, s, p, ep);
  437. break;
  438. case '-': /* 0 or more repetitions (minimum) */
  439. s = min_expand(ms, s, p, ep);
  440. break;
  441. default: /* no suffix */
  442. s++; p = ep; goto init; /* return match(ms, s + 1, ep); */
  443. }
  444. }
  445. break;
  446. }
  447. }
  448. }
  449. ms->matchdepth++;
  450. return s;
  451. }
  452. static const char *lmemfind (const char *s1, size_t l1,
  453. const char *s2, size_t l2) {
  454. if (l2 == 0) return s1; /* empty strings are everywhere */
  455. else if (l2 > l1) return NULL; /* avoids a negative 'l1' */
  456. else {
  457. const char *init; /* to search for a '*s2' inside 's1' */
  458. l2--; /* 1st char will be checked by 'memchr' */
  459. l1 = l1-l2; /* 's2' cannot be found after that */
  460. while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
  461. init++; /* 1st char is already checked */
  462. if (memcmp(init, s2+1, l2) == 0)
  463. return init-1;
  464. else { /* correct 'l1' and 's1' to try again */
  465. l1 -= init-s1;
  466. s1 = init;
  467. }
  468. }
  469. return NULL; /* not found */
  470. }
  471. }
  472. static void push_onecapture (MatchState *ms, int i, const char *s,
  473. const char *e) {
  474. if (i >= ms->level) {
  475. if (i == 0) /* ms->level == 0, too */
  476. lua_pushlstring(ms->L, s, e - s); /* add whole match */
  477. else
  478. luaL_error(ms->L, "invalid capture index %%%d", i + 1);
  479. }
  480. else {
  481. ptrdiff_t l = ms->capture[i].len;
  482. if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
  483. if (l == CAP_POSITION)
  484. lua_pushinteger(ms->L, (ms->capture[i].init - ms->src_init) + 1);
  485. else
  486. lua_pushlstring(ms->L, ms->capture[i].init, l);
  487. }
  488. }
  489. static int push_captures (MatchState *ms, const char *s, const char *e) {
  490. int i;
  491. int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
  492. luaL_checkstack(ms->L, nlevels, "too many captures");
  493. for (i = 0; i < nlevels; i++)
  494. push_onecapture(ms, i, s, e);
  495. return nlevels; /* number of strings pushed */
  496. }
  497. /* check whether pattern has no special characters */
  498. static int nospecials (const char *p, size_t l) {
  499. size_t upto = 0;
  500. do {
  501. if (strpbrk(p + upto, SPECIALS))
  502. return 0; /* pattern has a special character */
  503. upto += strlen(p + upto) + 1; /* may have more after \0 */
  504. } while (upto <= l);
  505. return 1; /* no special chars found */
  506. }
  507. static void prepstate (MatchState *ms, lua_State *L,
  508. const char *s, size_t ls, const char *p, size_t lp) {
  509. ms->L = L;
  510. ms->matchdepth = MAXCCALLS;
  511. ms->src_init = s;
  512. ms->src_end = s + ls;
  513. ms->p_end = p + lp;
  514. }
  515. static void reprepstate (MatchState *ms) {
  516. ms->level = 0;
  517. lua_assert(ms->matchdepth == MAXCCALLS);
  518. }
  519. static int str_find_aux (lua_State *L, int find) {
  520. size_t ls, lp;
  521. const char *s = luaL_checklstring(L, 1, &ls);
  522. const char *p = luaL_checklstring(L, 2, &lp);
  523. lua_Integer init = posrelat(luaL_optinteger(L, 3, 1), ls);
  524. if (init < 1) init = 1;
  525. else if (init > (lua_Integer)ls + 1) { /* start after string's end? */
  526. lua_pushnil(L); /* cannot find anything */
  527. return 1;
  528. }
  529. /* explicit request or no special characters? */
  530. if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
  531. /* do a plain search */
  532. const char *s2 = lmemfind(s + init - 1, ls - (size_t)init + 1, p, lp);
  533. if (s2) {
  534. lua_pushinteger(L, (s2 - s) + 1);
  535. lua_pushinteger(L, (s2 - s) + lp);
  536. return 2;
  537. }
  538. }
  539. else {
  540. MatchState ms;
  541. const char *s1 = s + init - 1;
  542. int anchor = (*p == '^');
  543. if (anchor) {
  544. p++; lp--; /* skip anchor character */
  545. }
  546. prepstate(&ms, L, s, ls, p, lp);
  547. do {
  548. const char *res;
  549. reprepstate(&ms);
  550. if ((res=match(&ms, s1, p)) != NULL) {
  551. if (find) {
  552. lua_pushinteger(L, (s1 - s) + 1); /* start */
  553. lua_pushinteger(L, res - s); /* end */
  554. return push_captures(&ms, NULL, 0) + 2;
  555. }
  556. else
  557. return push_captures(&ms, s1, res);
  558. }
  559. } while (s1++ < ms.src_end && !anchor);
  560. }
  561. lua_pushnil(L); /* not found */
  562. return 1;
  563. }
  564. static int str_find (lua_State *L) {
  565. return str_find_aux(L, 1);
  566. }
  567. static int str_match (lua_State *L) {
  568. return str_find_aux(L, 0);
  569. }
  570. /* state for 'gmatch' */
  571. typedef struct GMatchState {
  572. const char *src; /* current position */
  573. const char *p; /* pattern */
  574. const char *lastmatch; /* end of last match */
  575. MatchState ms; /* match state */
  576. } GMatchState;
  577. static int gmatch_aux (lua_State *L) {
  578. GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3));
  579. const char *src;
  580. gm->ms.L = L;
  581. for (src = gm->src; src <= gm->ms.src_end; src++) {
  582. const char *e;
  583. reprepstate(&gm->ms);
  584. if ((e = match(&gm->ms, src, gm->p)) != NULL && e != gm->lastmatch) {
  585. gm->src = gm->lastmatch = e;
  586. return push_captures(&gm->ms, src, e);
  587. }
  588. }
  589. return 0; /* not found */
  590. }
  591. static int gmatch (lua_State *L) {
  592. size_t ls, lp;
  593. const char *s = luaL_checklstring(L, 1, &ls);
  594. const char *p = luaL_checklstring(L, 2, &lp);
  595. GMatchState *gm;
  596. lua_settop(L, 2); /* keep them on closure to avoid being collected */
  597. gm = (GMatchState *)lua_newuserdata(L, sizeof(GMatchState));
  598. prepstate(&gm->ms, L, s, ls, p, lp);
  599. gm->src = s; gm->p = p; gm->lastmatch = NULL;
  600. lua_pushcclosure(L, gmatch_aux, 3);
  601. return 1;
  602. }
  603. static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
  604. const char *e) {
  605. size_t l, i;
  606. lua_State *L = ms->L;
  607. const char *news = lua_tolstring(L, 3, &l);
  608. for (i = 0; i < l; i++) {
  609. if (news[i] != L_ESC)
  610. luaL_addchar(b, news[i]);
  611. else {
  612. i++; /* skip ESC */
  613. if (!isdigit(uchar(news[i]))) {
  614. if (news[i] != L_ESC)
  615. luaL_error(L, "invalid use of '%c' in replacement string", L_ESC);
  616. luaL_addchar(b, news[i]);
  617. }
  618. else if (news[i] == '0')
  619. luaL_addlstring(b, s, e - s);
  620. else {
  621. push_onecapture(ms, news[i] - '1', s, e);
  622. luaL_tolstring(L, -1, NULL); /* if number, convert it to string */
  623. lua_remove(L, -2); /* remove original value */
  624. luaL_addvalue(b); /* add capture to accumulated result */
  625. }
  626. }
  627. }
  628. }
  629. static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
  630. const char *e, int tr) {
  631. lua_State *L = ms->L;
  632. switch (tr) {
  633. case LUA_TFUNCTION: {
  634. int n;
  635. lua_pushvalue(L, 3);
  636. n = push_captures(ms, s, e);
  637. lua_call(L, n, 1);
  638. break;
  639. }
  640. case LUA_TTABLE: {
  641. push_onecapture(ms, 0, s, e);
  642. lua_gettable(L, 3);
  643. break;
  644. }
  645. default: { /* LUA_TNUMBER or LUA_TSTRING */
  646. add_s(ms, b, s, e);
  647. return;
  648. }
  649. }
  650. if (!lua_toboolean(L, -1)) { /* nil or false? */
  651. lua_pop(L, 1);
  652. lua_pushlstring(L, s, e - s); /* keep original text */
  653. }
  654. else if (!lua_isstring(L, -1))
  655. luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
  656. luaL_addvalue(b); /* add result to accumulator */
  657. }
  658. static int str_gsub (lua_State *L) {
  659. size_t srcl, lp;
  660. const char *src = luaL_checklstring(L, 1, &srcl); /* subject */
  661. const char *p = luaL_checklstring(L, 2, &lp); /* pattern */
  662. const char *lastmatch = NULL; /* end of last match */
  663. int tr = lua_type(L, 3); /* replacement type */
  664. lua_Integer max_s = luaL_optinteger(L, 4, srcl + 1); /* max replacements */
  665. int anchor = (*p == '^');
  666. lua_Integer n = 0; /* replacement count */
  667. MatchState ms;
  668. luaL_Buffer b;
  669. luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
  670. tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
  671. "string/function/table expected");
  672. luaL_buffinit(L, &b);
  673. if (anchor) {
  674. p++; lp--; /* skip anchor character */
  675. }
  676. prepstate(&ms, L, src, srcl, p, lp);
  677. while (n < max_s) {
  678. const char *e;
  679. reprepstate(&ms); /* (re)prepare state for new match */
  680. if ((e = match(&ms, src, p)) != NULL && e != lastmatch) { /* match? */
  681. n++;
  682. add_value(&ms, &b, src, e, tr); /* add replacement to buffer */
  683. src = lastmatch = e;
  684. }
  685. else if (src < ms.src_end) /* otherwise, skip one character */
  686. luaL_addchar(&b, *src++);
  687. else break; /* end of subject */
  688. if (anchor) break;
  689. }
  690. luaL_addlstring(&b, src, ms.src_end-src);
  691. luaL_pushresult(&b);
  692. lua_pushinteger(L, n); /* number of substitutions */
  693. return 2;
  694. }
  695. /* }====================================================== */
  696. /*
  697. ** {======================================================
  698. ** STRING FORMAT
  699. ** =======================================================
  700. */
  701. #if !defined(lua_number2strx) /* { */
  702. /*
  703. ** Hexadecimal floating-point formatter
  704. */
  705. #include <math.h>
  706. #define SIZELENMOD (sizeof(LUA_NUMBER_FRMLEN)/sizeof(char))
  707. /*
  708. ** Number of bits that goes into the first digit. It can be any value
  709. ** between 1 and 4; the following definition tries to align the number
  710. ** to nibble boundaries by making what is left after that first digit a
  711. ** multiple of 4.
  712. */
  713. #define L_NBFD ((l_mathlim(MANT_DIG) - 1)%4 + 1)
  714. /*
  715. ** Add integer part of 'x' to buffer and return new 'x'
  716. */
  717. static lua_Number adddigit (char *buff, int n, lua_Number x) {
  718. lua_Number dd = l_mathop(floor)(x); /* get integer part from 'x' */
  719. int d = (int)dd;
  720. buff[n] = (d < 10 ? d + '0' : d - 10 + 'a'); /* add to buffer */
  721. return x - dd; /* return what is left */
  722. }
  723. static int num2straux (char *buff, int sz, lua_Number x) {
  724. if (x != x || x == HUGE_VAL || x == -HUGE_VAL) /* inf or NaN? */
  725. return l_sprintf(buff, sz, LUA_NUMBER_FMT, x); /* equal to '%g' */
  726. else if (x == 0) { /* can be -0... */
  727. /* create "0" or "-0" followed by exponent */
  728. return l_sprintf(buff, sz, LUA_NUMBER_FMT "x0p+0", x);
  729. }
  730. else {
  731. int e;
  732. lua_Number m = l_mathop(frexp)(x, &e); /* 'x' fraction and exponent */
  733. int n = 0; /* character count */
  734. if (m < 0) { /* is number negative? */
  735. buff[n++] = '-'; /* add signal */
  736. m = -m; /* make it positive */
  737. }
  738. buff[n++] = '0'; buff[n++] = 'x'; /* add "0x" */
  739. m = adddigit(buff, n++, m * (1 << L_NBFD)); /* add first digit */
  740. e -= L_NBFD; /* this digit goes before the radix point */
  741. if (m > 0) { /* more digits? */
  742. buff[n++] = lua_getlocaledecpoint(); /* add radix point */
  743. do { /* add as many digits as needed */
  744. m = adddigit(buff, n++, m * 16);
  745. } while (m > 0);
  746. }
  747. n += l_sprintf(buff + n, sz - n, "p%+d", e); /* add exponent */
  748. lua_assert(n < sz);
  749. return n;
  750. }
  751. }
  752. static int lua_number2strx (lua_State *L, char *buff, int sz,
  753. const char *fmt, lua_Number x) {
  754. int n = num2straux(buff, sz, x);
  755. if (fmt[SIZELENMOD] == 'A') {
  756. int i;
  757. for (i = 0; i < n; i++)
  758. buff[i] = toupper(uchar(buff[i]));
  759. }
  760. else if (fmt[SIZELENMOD] != 'a')
  761. luaL_error(L, "modifiers for format '%%a'/'%%A' not implemented");
  762. return n;
  763. }
  764. #endif /* } */
  765. /*
  766. ** Maximum size of each formatted item. This maximum size is produced
  767. ** by format('%.99f', -maxfloat), and is equal to 99 + 3 ('-', '.',
  768. ** and '\0') + number of decimal digits to represent maxfloat (which
  769. ** is maximum exponent + 1). (99+3+1 then rounded to 120 for "extra
  770. ** expenses", such as locale-dependent stuff)
  771. */
  772. #define MAX_ITEM (120 + l_mathlim(MAX_10_EXP))
  773. /* valid flags in a format specification */
  774. #define FLAGS "-+ #0"
  775. /*
  776. ** maximum size of each format specification (such as "%-099.99d")
  777. */
  778. #define MAX_FORMAT 32
  779. static void addquoted (luaL_Buffer *b, const char *s, size_t len) {
  780. luaL_addchar(b, '"');
  781. while (len--) {
  782. if (*s == '"' || *s == '\\' || *s == '\n') {
  783. luaL_addchar(b, '\\');
  784. luaL_addchar(b, *s);
  785. }
  786. else if (iscntrl(uchar(*s))) {
  787. char buff[10];
  788. if (!isdigit(uchar(*(s+1))))
  789. l_sprintf(buff, sizeof(buff), "\\%d", (int)uchar(*s));
  790. else
  791. l_sprintf(buff, sizeof(buff), "\\%03d", (int)uchar(*s));
  792. luaL_addstring(b, buff);
  793. }
  794. else
  795. luaL_addchar(b, *s);
  796. s++;
  797. }
  798. luaL_addchar(b, '"');
  799. }
  800. /*
  801. ** Ensures the 'buff' string uses a dot as the radix character.
  802. */
  803. static void checkdp (char *buff, int nb) {
  804. if (memchr(buff, '.', nb) == NULL) { /* no dot? */
  805. char point = lua_getlocaledecpoint(); /* try locale point */
  806. char *ppoint = memchr(buff, point, nb);
  807. if (ppoint) *ppoint = '.'; /* change it to a dot */
  808. }
  809. }
  810. static void addliteral (lua_State *L, luaL_Buffer *b, int arg) {
  811. switch (lua_type(L, arg)) {
  812. case LUA_TSTRING: {
  813. size_t len;
  814. const char *s = lua_tolstring(L, arg, &len);
  815. addquoted(b, s, len);
  816. break;
  817. }
  818. case LUA_TNUMBER: {
  819. char *buff = luaL_prepbuffsize(b, MAX_ITEM);
  820. int nb;
  821. if (!lua_isinteger(L, arg)) { /* float? */
  822. lua_Number n = lua_tonumber(L, arg); /* write as hexa ('%a') */
  823. nb = lua_number2strx(L, buff, MAX_ITEM, "%" LUA_NUMBER_FRMLEN "a", n);
  824. checkdp(buff, nb); /* ensure it uses a dot */
  825. }
  826. else { /* integers */
  827. lua_Integer n = lua_tointeger(L, arg);
  828. const char *format = (n == LUA_MININTEGER) /* corner case? */
  829. ? "0x%" LUA_INTEGER_FRMLEN "x" /* use hexa */
  830. : LUA_INTEGER_FMT; /* else use default format */
  831. nb = l_sprintf(buff, MAX_ITEM, format, n);
  832. }
  833. luaL_addsize(b, nb);
  834. break;
  835. }
  836. case LUA_TNIL: case LUA_TBOOLEAN: {
  837. luaL_tolstring(L, arg, NULL);
  838. luaL_addvalue(b);
  839. break;
  840. }
  841. default: {
  842. luaL_argerror(L, arg, "value has no literal form");
  843. }
  844. }
  845. }
  846. static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
  847. const char *p = strfrmt;
  848. while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */
  849. if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char))
  850. luaL_error(L, "invalid format (repeated flags)");
  851. if (isdigit(uchar(*p))) p++; /* skip width */
  852. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  853. if (*p == '.') {
  854. p++;
  855. if (isdigit(uchar(*p))) p++; /* skip precision */
  856. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  857. }
  858. if (isdigit(uchar(*p)))
  859. luaL_error(L, "invalid format (width or precision too long)");
  860. *(form++) = '%';
  861. memcpy(form, strfrmt, ((p - strfrmt) + 1) * sizeof(char));
  862. form += (p - strfrmt) + 1;
  863. *form = '\0';
  864. return p;
  865. }
  866. /*
  867. ** add length modifier into formats
  868. */
  869. static void addlenmod (char *form, const char *lenmod) {
  870. size_t l = strlen(form);
  871. size_t lm = strlen(lenmod);
  872. char spec = form[l - 1];
  873. strcpy(form + l - 1, lenmod);
  874. form[l + lm - 1] = spec;
  875. form[l + lm] = '\0';
  876. }
  877. static int str_format (lua_State *L) {
  878. int top = lua_gettop(L);
  879. int arg = 1;
  880. size_t sfl;
  881. const char *strfrmt = luaL_checklstring(L, arg, &sfl);
  882. const char *strfrmt_end = strfrmt+sfl;
  883. luaL_Buffer b;
  884. luaL_buffinit(L, &b);
  885. while (strfrmt < strfrmt_end) {
  886. if (*strfrmt != L_ESC)
  887. luaL_addchar(&b, *strfrmt++);
  888. else if (*++strfrmt == L_ESC)
  889. luaL_addchar(&b, *strfrmt++); /* %% */
  890. else { /* format item */
  891. char form[MAX_FORMAT]; /* to store the format ('%...') */
  892. char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */
  893. int nb = 0; /* number of bytes in added item */
  894. if (++arg > top)
  895. luaL_argerror(L, arg, "no value");
  896. strfrmt = scanformat(L, strfrmt, form);
  897. switch (*strfrmt++) {
  898. case 'c': {
  899. nb = l_sprintf(buff, MAX_ITEM, form, (int)luaL_checkinteger(L, arg));
  900. break;
  901. }
  902. case 'd': case 'i':
  903. case 'o': case 'u': case 'x': case 'X': {
  904. lua_Integer n = luaL_checkinteger(L, arg);
  905. addlenmod(form, LUA_INTEGER_FRMLEN);
  906. nb = l_sprintf(buff, MAX_ITEM, form, n);
  907. break;
  908. }
  909. case 'a': case 'A':
  910. addlenmod(form, LUA_NUMBER_FRMLEN);
  911. nb = lua_number2strx(L, buff, MAX_ITEM, form,
  912. luaL_checknumber(L, arg));
  913. break;
  914. case 'e': case 'E': case 'f':
  915. case 'g': case 'G': {
  916. addlenmod(form, LUA_NUMBER_FRMLEN);
  917. nb = l_sprintf(buff, MAX_ITEM, form, luaL_checknumber(L, arg));
  918. break;
  919. }
  920. case 'q': {
  921. addliteral(L, &b, arg);
  922. break;
  923. }
  924. case 's': {
  925. size_t l;
  926. const char *s = luaL_tolstring(L, arg, &l);
  927. if (form[2] == '\0') /* no modifiers? */
  928. luaL_addvalue(&b); /* keep entire string */
  929. else {
  930. luaL_argcheck(L, l == strlen(s), arg, "string contains zeros");
  931. if (!strchr(form, '.') && l >= 100) {
  932. /* no precision and string is too long to be formatted */
  933. luaL_addvalue(&b); /* keep entire string */
  934. }
  935. else { /* format the string into 'buff' */
  936. nb = l_sprintf(buff, MAX_ITEM, form, s);
  937. lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
  938. }
  939. }
  940. break;
  941. }
  942. default: { /* also treat cases 'pnLlh' */
  943. return luaL_error(L, "invalid option '%%%c' to 'format'",
  944. *(strfrmt - 1));
  945. }
  946. }
  947. lua_assert(nb < MAX_ITEM);
  948. luaL_addsize(&b, nb);
  949. }
  950. }
  951. luaL_pushresult(&b);
  952. return 1;
  953. }
  954. /* }====================================================== */
  955. /*
  956. ** {======================================================
  957. ** PACK/UNPACK
  958. ** =======================================================
  959. */
  960. /* value used for padding */
  961. #if !defined(LUAL_PACKPADBYTE)
  962. #define LUAL_PACKPADBYTE 0x00
  963. #endif
  964. /* maximum size for the binary representation of an integer */
  965. #define MAXINTSIZE 16
  966. /* number of bits in a character */
  967. #define NB CHAR_BIT
  968. /* mask for one character (NB 1's) */
  969. #define MC ((1 << NB) - 1)
  970. /* size of a lua_Integer */
  971. #define SZINT ((int)sizeof(lua_Integer))
  972. /* dummy union to get native endianness */
  973. static const union {
  974. int dummy;
  975. char little; /* true iff machine is little endian */
  976. } nativeendian = {1};
  977. /* dummy structure to get native alignment requirements */
  978. struct cD {
  979. char c;
  980. union { double d; void *p; lua_Integer i; lua_Number n; } u;
  981. };
  982. #define MAXALIGN (offsetof(struct cD, u))
  983. /*
  984. ** Union for serializing floats
  985. */
  986. typedef union Ftypes {
  987. float f;
  988. double d;
  989. lua_Number n;
  990. char buff[5 * sizeof(lua_Number)]; /* enough for any float type */
  991. } Ftypes;
  992. /*
  993. ** information to pack/unpack stuff
  994. */
  995. typedef struct Header {
  996. lua_State *L;
  997. int islittle;
  998. int maxalign;
  999. } Header;
  1000. /*
  1001. ** options for pack/unpack
  1002. */
  1003. typedef enum KOption {
  1004. Kint, /* signed integers */
  1005. Kuint, /* unsigned integers */
  1006. Kfloat, /* floating-point numbers */
  1007. Kchar, /* fixed-length strings */
  1008. Kstring, /* strings with prefixed length */
  1009. Kzstr, /* zero-terminated strings */
  1010. Kpadding, /* padding */
  1011. Kpaddalign, /* padding for alignment */
  1012. Knop /* no-op (configuration or spaces) */
  1013. } KOption;
  1014. /*
  1015. ** Read an integer numeral from string 'fmt' or return 'df' if
  1016. ** there is no numeral
  1017. */
  1018. static int digit (int c) { return '0' <= c && c <= '9'; }
  1019. static int getnum (const char **fmt, int df) {
  1020. if (!digit(**fmt)) /* no number? */
  1021. return df; /* return default value */
  1022. else {
  1023. int a = 0;
  1024. do {
  1025. a = a*10 + (*((*fmt)++) - '0');
  1026. } while (digit(**fmt) && a <= ((int)MAXSIZE - 9)/10);
  1027. return a;
  1028. }
  1029. }
  1030. /*
  1031. ** Read an integer numeral and raises an error if it is larger
  1032. ** than the maximum size for integers.
  1033. */
  1034. static int getnumlimit (Header *h, const char **fmt, int df) {
  1035. int sz = getnum(fmt, df);
  1036. if (sz > MAXINTSIZE || sz <= 0)
  1037. luaL_error(h->L, "integral size (%d) out of limits [1,%d]",
  1038. sz, MAXINTSIZE);
  1039. return sz;
  1040. }
  1041. /*
  1042. ** Initialize Header
  1043. */
  1044. static void initheader (lua_State *L, Header *h) {
  1045. h->L = L;
  1046. h->islittle = nativeendian.little;
  1047. h->maxalign = 1;
  1048. }
  1049. /*
  1050. ** Read and classify next option. 'size' is filled with option's size.
  1051. */
  1052. static KOption getoption (Header *h, const char **fmt, int *size) {
  1053. int opt = *((*fmt)++);
  1054. *size = 0; /* default */
  1055. switch (opt) {
  1056. case 'b': *size = sizeof(char); return Kint;
  1057. case 'B': *size = sizeof(char); return Kuint;
  1058. case 'h': *size = sizeof(short); return Kint;
  1059. case 'H': *size = sizeof(short); return Kuint;
  1060. case 'l': *size = sizeof(long); return Kint;
  1061. case 'L': *size = sizeof(long); return Kuint;
  1062. case 'j': *size = sizeof(lua_Integer); return Kint;
  1063. case 'J': *size = sizeof(lua_Integer); return Kuint;
  1064. case 'T': *size = sizeof(size_t); return Kuint;
  1065. case 'f': *size = sizeof(float); return Kfloat;
  1066. case 'd': *size = sizeof(double); return Kfloat;
  1067. case 'n': *size = sizeof(lua_Number); return Kfloat;
  1068. case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint;
  1069. case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint;
  1070. case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring;
  1071. case 'c':
  1072. *size = getnum(fmt, -1);
  1073. if (*size == -1)
  1074. luaL_error(h->L, "missing size for format option 'c'");
  1075. return Kchar;
  1076. case 'z': return Kzstr;
  1077. case 'x': *size = 1; return Kpadding;
  1078. case 'X': return Kpaddalign;
  1079. case ' ': break;
  1080. case '<': h->islittle = 1; break;
  1081. case '>': h->islittle = 0; break;
  1082. case '=': h->islittle = nativeendian.little; break;
  1083. case '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); break;
  1084. default: luaL_error(h->L, "invalid format option '%c'", opt);
  1085. }
  1086. return Knop;
  1087. }
  1088. /*
  1089. ** Read, classify, and fill other details about the next option.
  1090. ** 'psize' is filled with option's size, 'notoalign' with its
  1091. ** alignment requirements.
  1092. ** Local variable 'size' gets the size to be aligned. (Kpadal option
  1093. ** always gets its full alignment, other options are limited by
  1094. ** the maximum alignment ('maxalign'). Kchar option needs no alignment
  1095. ** despite its size.
  1096. */
  1097. static KOption getdetails (Header *h, size_t totalsize,
  1098. const char **fmt, int *psize, int *ntoalign) {
  1099. KOption opt = getoption(h, fmt, psize);
  1100. int align = *psize; /* usually, alignment follows size */
  1101. if (opt == Kpaddalign) { /* 'X' gets alignment from following option */
  1102. if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0)
  1103. luaL_argerror(h->L, 1, "invalid next option for option 'X'");
  1104. }
  1105. if (align <= 1 || opt == Kchar) /* need no alignment? */
  1106. *ntoalign = 0;
  1107. else {
  1108. if (align > h->maxalign) /* enforce maximum alignment */
  1109. align = h->maxalign;
  1110. if ((align & (align - 1)) != 0) /* is 'align' not a power of 2? */
  1111. luaL_argerror(h->L, 1, "format asks for alignment not power of 2");
  1112. *ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1);
  1113. }
  1114. return opt;
  1115. }
  1116. /*
  1117. ** Pack integer 'n' with 'size' bytes and 'islittle' endianness.
  1118. ** The final 'if' handles the case when 'size' is larger than
  1119. ** the size of a Lua integer, correcting the extra sign-extension
  1120. ** bytes if necessary (by default they would be zeros).
  1121. */
  1122. static void packint (luaL_Buffer *b, lua_Unsigned n,
  1123. int islittle, int size, int neg) {
  1124. char *buff = luaL_prepbuffsize(b, size);
  1125. int i;
  1126. buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */
  1127. for (i = 1; i < size; i++) {
  1128. n >>= NB;
  1129. buff[islittle ? i : size - 1 - i] = (char)(n & MC);
  1130. }
  1131. if (neg && size > SZINT) { /* negative number need sign extension? */
  1132. for (i = SZINT; i < size; i++) /* correct extra bytes */
  1133. buff[islittle ? i : size - 1 - i] = (char)MC;
  1134. }
  1135. luaL_addsize(b, size); /* add result to buffer */
  1136. }
  1137. /*
  1138. ** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
  1139. ** given 'islittle' is different from native endianness.
  1140. */
  1141. static void copywithendian (volatile char *dest, volatile const char *src,
  1142. int size, int islittle) {
  1143. if (islittle == nativeendian.little) {
  1144. while (size-- != 0)
  1145. *(dest++) = *(src++);
  1146. }
  1147. else {
  1148. dest += size - 1;
  1149. while (size-- != 0)
  1150. *(dest--) = *(src++);
  1151. }
  1152. }
  1153. static int str_pack (lua_State *L) {
  1154. luaL_Buffer b;
  1155. Header h;
  1156. const char *fmt = luaL_checkstring(L, 1); /* format string */
  1157. int arg = 1; /* current argument to pack */
  1158. size_t totalsize = 0; /* accumulate total size of result */
  1159. initheader(L, &h);
  1160. lua_pushnil(L); /* mark to separate arguments from string buffer */
  1161. luaL_buffinit(L, &b);
  1162. while (*fmt != '\0') {
  1163. int size, ntoalign;
  1164. KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
  1165. totalsize += ntoalign + size;
  1166. while (ntoalign-- > 0)
  1167. luaL_addchar(&b, LUAL_PACKPADBYTE); /* fill alignment */
  1168. arg++;
  1169. switch (opt) {
  1170. case Kint: { /* signed integers */
  1171. lua_Integer n = luaL_checkinteger(L, arg);
  1172. if (size < SZINT) { /* need overflow check? */
  1173. lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);
  1174. luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
  1175. }
  1176. packint(&b, (lua_Unsigned)n, h.islittle, size, (n < 0));
  1177. break;
  1178. }
  1179. case Kuint: { /* unsigned integers */
  1180. lua_Integer n = luaL_checkinteger(L, arg);
  1181. if (size < SZINT) /* need overflow check? */
  1182. luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),
  1183. arg, "unsigned overflow");
  1184. packint(&b, (lua_Unsigned)n, h.islittle, size, 0);
  1185. break;
  1186. }
  1187. case Kfloat: { /* floating-point options */
  1188. volatile Ftypes u;
  1189. char *buff = luaL_prepbuffsize(&b, size);
  1190. lua_Number n = luaL_checknumber(L, arg); /* get argument */
  1191. if (size == sizeof(u.f)) u.f = (float)n; /* copy it into 'u' */
  1192. else if (size == sizeof(u.d)) u.d = (double)n;
  1193. else u.n = n;
  1194. /* move 'u' to final result, correcting endianness if needed */
  1195. copywithendian(buff, u.buff, size, h.islittle);
  1196. luaL_addsize(&b, size);
  1197. break;
  1198. }
  1199. case Kchar: { /* fixed-size string */
  1200. size_t len;
  1201. const char *s = luaL_checklstring(L, arg, &len);
  1202. luaL_argcheck(L, len <= (size_t)size, arg,
  1203. "string longer than given size");
  1204. luaL_addlstring(&b, s, len); /* add string */
  1205. while (len++ < (size_t)size) /* pad extra space */
  1206. luaL_addchar(&b, LUAL_PACKPADBYTE);
  1207. break;
  1208. }
  1209. case Kstring: { /* strings with length count */
  1210. size_t len;
  1211. const char *s = luaL_checklstring(L, arg, &len);
  1212. luaL_argcheck(L, size >= (int)sizeof(size_t) ||
  1213. len < ((size_t)1 << (size * NB)),
  1214. arg, "string length does not fit in given size");
  1215. packint(&b, (lua_Unsigned)len, h.islittle, size, 0); /* pack length */
  1216. luaL_addlstring(&b, s, len);
  1217. totalsize += len;
  1218. break;
  1219. }
  1220. case Kzstr: { /* zero-terminated string */
  1221. size_t len;
  1222. const char *s = luaL_checklstring(L, arg, &len);
  1223. luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros");
  1224. luaL_addlstring(&b, s, len);
  1225. luaL_addchar(&b, '\0'); /* add zero at the end */
  1226. totalsize += len + 1;
  1227. break;
  1228. }
  1229. case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE); /* FALLTHROUGH */
  1230. case Kpaddalign: case Knop:
  1231. arg--; /* undo increment */
  1232. break;
  1233. }
  1234. }
  1235. luaL_pushresult(&b);
  1236. return 1;
  1237. }
  1238. static int str_packsize (lua_State *L) {
  1239. Header h;
  1240. const char *fmt = luaL_checkstring(L, 1); /* format string */
  1241. size_t totalsize = 0; /* accumulate total size of result */
  1242. initheader(L, &h);
  1243. while (*fmt != '\0') {
  1244. int size, ntoalign;
  1245. KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
  1246. size += ntoalign; /* total space used by option */
  1247. luaL_argcheck(L, totalsize <= MAXSIZE - size, 1,
  1248. "format result too large");
  1249. totalsize += size;
  1250. switch (opt) {
  1251. case Kstring: /* strings with length count */
  1252. case Kzstr: /* zero-terminated string */
  1253. luaL_argerror(L, 1, "variable-length format");
  1254. /* call never return, but to avoid warnings: *//* FALLTHROUGH */
  1255. default: break;
  1256. }
  1257. }
  1258. lua_pushinteger(L, (lua_Integer)totalsize);
  1259. return 1;
  1260. }
  1261. /*
  1262. ** Unpack an integer with 'size' bytes and 'islittle' endianness.
  1263. ** If size is smaller than the size of a Lua integer and integer
  1264. ** is signed, must do sign extension (propagating the sign to the
  1265. ** higher bits); if size is larger than the size of a Lua integer,
  1266. ** it must check the unread bytes to see whether they do not cause an
  1267. ** overflow.
  1268. */
  1269. static lua_Integer unpackint (lua_State *L, const char *str,
  1270. int islittle, int size, int issigned) {
  1271. lua_Unsigned res = 0;
  1272. int i;
  1273. int limit = (size <= SZINT) ? size : SZINT;
  1274. for (i = limit - 1; i >= 0; i--) {
  1275. res <<= NB;
  1276. res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i];
  1277. }
  1278. if (size < SZINT) { /* real size smaller than lua_Integer? */
  1279. if (issigned) { /* needs sign extension? */
  1280. lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
  1281. res = ((res ^ mask) - mask); /* do sign extension */
  1282. }
  1283. }
  1284. else if (size > SZINT) { /* must check unread bytes */
  1285. int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
  1286. for (i = limit; i < size; i++) {
  1287. if ((unsigned char)str[islittle ? i : size - 1 - i] != mask)
  1288. luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
  1289. }
  1290. }
  1291. return (lua_Integer)res;
  1292. }
  1293. static int str_unpack (lua_State *L) {
  1294. Header h;
  1295. const char *fmt = luaL_checkstring(L, 1);
  1296. size_t ld;
  1297. const char *data = luaL_checklstring(L, 2, &ld);
  1298. size_t pos = (size_t)posrelat(luaL_optinteger(L, 3, 1), ld) - 1;
  1299. int n = 0; /* number of results */
  1300. luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
  1301. initheader(L, &h);
  1302. while (*fmt != '\0') {
  1303. int size, ntoalign;
  1304. KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);
  1305. if ((size_t)ntoalign + size > ~pos || pos + ntoalign + size > ld)
  1306. luaL_argerror(L, 2, "data string too short");
  1307. pos += ntoalign; /* skip alignment */
  1308. /* stack space for item + next position */
  1309. luaL_checkstack(L, 2, "too many results");
  1310. n++;
  1311. switch (opt) {
  1312. case Kint:
  1313. case Kuint: {
  1314. lua_Integer res = unpackint(L, data + pos, h.islittle, size,
  1315. (opt == Kint));
  1316. lua_pushinteger(L, res);
  1317. break;
  1318. }
  1319. case Kfloat: {
  1320. volatile Ftypes u;
  1321. lua_Number num;
  1322. copywithendian(u.buff, data + pos, size, h.islittle);
  1323. if (size == sizeof(u.f)) num = (lua_Number)u.f;
  1324. else if (size == sizeof(u.d)) num = (lua_Number)u.d;
  1325. else num = u.n;
  1326. lua_pushnumber(L, num);
  1327. break;
  1328. }
  1329. case Kchar: {
  1330. lua_pushlstring(L, data + pos, size);
  1331. break;
  1332. }
  1333. case Kstring: {
  1334. size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0);
  1335. luaL_argcheck(L, pos + len + size <= ld, 2, "data string too short");
  1336. lua_pushlstring(L, data + pos + size, len);
  1337. pos += len; /* skip string */
  1338. break;
  1339. }
  1340. case Kzstr: {
  1341. size_t len = (int)strlen(data + pos);
  1342. lua_pushlstring(L, data + pos, len);
  1343. pos += len + 1; /* skip string plus final '\0' */
  1344. break;
  1345. }
  1346. case Kpaddalign: case Kpadding: case Knop:
  1347. n--; /* undo increment */
  1348. break;
  1349. }
  1350. pos += size;
  1351. }
  1352. lua_pushinteger(L, pos + 1); /* next position */
  1353. return n + 1;
  1354. }
  1355. /* }====================================================== */
  1356. static const luaL_Reg strlib[] = {
  1357. {"byte", str_byte},
  1358. {"char", str_char},
  1359. {"dump", str_dump},
  1360. {"find", str_find},
  1361. {"format", str_format},
  1362. {"gmatch", gmatch},
  1363. {"gsub", str_gsub},
  1364. {"len", str_len},
  1365. {"lower", str_lower},
  1366. {"match", str_match},
  1367. {"rep", str_rep},
  1368. {"reverse", str_reverse},
  1369. {"sub", str_sub},
  1370. {"upper", str_upper},
  1371. {"pack", str_pack},
  1372. {"packsize", str_packsize},
  1373. {"unpack", str_unpack},
  1374. {NULL, NULL}
  1375. };
  1376. static void createmetatable (lua_State *L) {
  1377. lua_createtable(L, 0, 1); /* table to be metatable for strings */
  1378. lua_pushliteral(L, ""); /* dummy string */
  1379. lua_pushvalue(L, -2); /* copy table */
  1380. lua_setmetatable(L, -2); /* set table as metatable for strings */
  1381. lua_pop(L, 1); /* pop dummy string */
  1382. lua_pushvalue(L, -2); /* get string library */
  1383. lua_setfield(L, -2, "__index"); /* metatable.__index = string */
  1384. lua_pop(L, 1); /* pop metatable */
  1385. }
  1386. /*
  1387. ** Open string library
  1388. */
  1389. LUAMOD_API int luaopen_string (lua_State *L) {
  1390. luaL_newlib(L, strlib);
  1391. createmetatable(L);
  1392. return 1;
  1393. }