lstrlib.c 43 KB

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