lstrlib.c 46 KB

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