lstrlib.c 39 KB

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