lstrlib.c 49 KB

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