lstrlib.c 56 KB

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