lstrlib.c 43 KB

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