lstrlib.c 43 KB

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